ngram
listlengths
0
67.8k
[ "include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to manage\" \" configurations for", "__version__ def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"],", "import __version__ def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir],", "template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True)", "\"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\") src =", "filename dst = outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js')", "= pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args)", "for x in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files = data_files", "render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles:", "mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str: template_dir", "= outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered =", "any case buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files", "filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq')", "in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if", "find_packages, setup import pathlib import shutil from mako.lookup import TemplateLookup from intelmq_manager.version import", "TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates')", "a graphical interface to manage\" \" configurations for the IntelMQ framework.\"), data_files=data_files )", "from mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str:", "directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*')", "+ [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/',", "setup, we build the html files in any case buildhtml() htmlsubdirs = [directory", "controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the html files in any", "Manager is a graphical interface to manage\" \" configurations for the IntelMQ framework.\"),", "= render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the html", "rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the", "buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\",", "x in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files = data_files +", "= data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files =", "2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import", "version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical", "\"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename", "htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering", "is a graphical interface to manage\" \" configurations for the IntelMQ framework.\"), data_files=data_files", "return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\",", "**template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\",", "-> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako')", "install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to manage\"", "pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def", "in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\",", "dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build", "directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x)", "htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])]", "\"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles", "we build the html files in any case buildhtml() htmlsubdirs = [directory for", "+ [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files +", "template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename,", "\"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename)", "for directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in", "for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup(", "[\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\") src", "outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"]", "staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir /", "= render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in", "= data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ],", "= [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for", "[('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq',", "\"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to manage\" \"", "from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup", "= pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for", "pathlib import shutil from mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str,", "[(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files", "render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template", "outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying", "htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\",", "**template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template =", "filename in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst =", "input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True,", "= template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles", "outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the html files in any case", "= pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src,", "the html files in any case buildhtml() htmlsubdirs = [directory for directory in", "\"\"\" from setuptools import find_packages, setup import pathlib import shutil from mako.lookup import", "[directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x", "running setup, we build the html files in any case buildhtml() htmlsubdirs =", "outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in", "Setup file for intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from", "[\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html", "case buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files =", "dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) #", "<<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import pathlib import shutil", "description=(\"IntelMQ Manager is a graphical interface to manage\" \" configurations for the IntelMQ", "import find_packages, setup import pathlib import shutil from mako.lookup import TemplateLookup from intelmq_manager.version", "data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True,", "in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html',", "# Before running setup, we build the html files in any case buildhtml()", "files in any case buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if", "pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst)", "allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the html files in", "intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup =", "html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename", "import shutil from mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args)", "for filename in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst", "= [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\")", "render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we build the html files", "\"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html =", "[str(x) for x in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs] data_files =", "SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import pathlib import shutil from", "shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running", "in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir", "filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\",", "outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar',", "pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5',", "print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"]", "shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before", "file for intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools", "import pathlib import shutil from mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def", "for filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\",", "if x.is_file()]) for directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for", "for intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import", "\"\"\" Setup file for intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\"", "build the html files in any case buildhtml() htmlsubdirs = [directory for directory", "[('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ", "x.is_file()]) for directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x", "htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x)", "x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[", "\"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') /", "= [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\")", "SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup", "packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to", "shutil from mako.lookup import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) ->", "Before running setup, we build the html files in any case buildhtml() htmlsubdirs", "staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename}", "<reponame>monoidic/intelmq-manager \"\"\" Setup file for intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later", "= TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir", "if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(),", "setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is", "/ filename dst = outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering", "name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a", "pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()])", "print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup, we", "Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import pathlib import", "template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\",", "= [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()]) for directory in htmlsubdirs]", "data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\",", "/ filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/',", "{filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename if", "python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface", "print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename", "in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if", "], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to manage\" \" configurations", "intelmq-manager SPDX-FileCopyrightText: 2020 IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages,", "setup import pathlib import shutil from mako.lookup import TemplateLookup from intelmq_manager.version import __version__", "\"js\", \"plugins\", \"less\"] for filename in staticfiles: print(f\"Copying {filename} recursively\") src = pathlib.Path('intelmq_manager/static')", "AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import pathlib import shutil from mako.lookup", "src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename if dst.exists(): shutil.rmtree(dst)", "def render_page(pagename:str, **template_args) -> str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8')", "directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()]) for directory", "directory in htmlsubdirs] data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir()", "in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__,", "str: template_dir = pathlib.Path('intelmq_manager/templates') template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return", "if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()]) for", "setuptools import find_packages, setup import pathlib import shutil from mako.lookup import TemplateLookup from", "data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files", "\"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles =", "html files in any case buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**')", "from setuptools import find_packages, setup import pathlib import shutil from mako.lookup import TemplateLookup", "[str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])]", "x in pathlib.Path('html').iterdir() if x.is_file()])] data_files = data_files + [('/etc/intelmq', ['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\",", "pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename", "default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html')", "for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in", "template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles =", "def buildhtml(): outputdir = pathlib.Path('html') outputdir.mkdir(parents=True, exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\",", "buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()] data_files = [(f'/usr/share/intelmq_manager/{directory}',", "recursively\") src = pathlib.Path('intelmq_manager/static') / filename dst = outputdir / filename if dst.exists():", "import TemplateLookup from intelmq_manager.version import __version__ def render_page(pagename:str, **template_args) -> str: template_dir =", "data_files = [(f'/usr/share/intelmq_manager/{directory}', [str(x) for x in directory.glob('*') if x.is_file()]) for directory in", "dst = outputdir / filename if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered", "exist_ok=True) htmlfiles = [\"configs\", \"management\", \"monitor\", \"check\", \"about\", \"index\"] for filename in htmlfiles:", "if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered)", "in any case buildhtml() htmlsubdirs = [directory for directory in pathlib.Path('html').glob('**') if directory.is_dir()]", "\"check\", \"about\", \"index\"] for filename in htmlfiles: print(f\"Rendering {filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html)", "template_lookup = TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml():", "data_files = data_files + [('/usr/share/intelmq_manager/html', [str(x) for x in pathlib.Path('html').iterdir() if x.is_file()])] data_files", "['contrib/manager-apache.conf'])] setup( name=\"intelmq-manager\", version=__version__, python_requires='>=3.5', packages=find_packages(), install_requires=[ \"intelmq-api\", ], include_package_data=True, url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager", "url='https://github.com/certtools/intelmq-manager/', description=(\"IntelMQ Manager is a graphical interface to manage\" \" configurations for the", "IntelMQ Team <<EMAIL>> SPDX-License-Identifier: AGPL-3.0-or-later \"\"\" from setuptools import find_packages, setup import pathlib", "dst) print('rendering dynvar.js') rendered = render_page('dynvar', allowed_path='/opt/intelmq/var/lib/bots/', controller_cmd='intelmq') outputdir.joinpath('js/dynvar.js').write_text(rendered) # Before running setup,", "TemplateLookup(directories=[template_dir], default_filters=[\"h\"], input_encoding='utf8') template = template_lookup.get_template(f'{pagename}.mako') return template.render(pagename=pagename, **template_args) def buildhtml(): outputdir =", "{filename}.html\") html = render_page(filename) outputdir.joinpath(f\"{filename}.html\").write_text(html) staticfiles = [\"css\", \"images\", \"js\", \"plugins\", \"less\"] for" ]
[ "alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case ID\") plt.show() return", "time import pandas as pd import numpy as np import stellargraph as sg", "embs_2d = get_TSNE(node_embeddings) # Draw the embedding points, coloring them by the target", "import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph", "in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id)", "e_sets) #### Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G)", "import pandas as pd import numpy as np import stellargraph as sg from", "walk] for walk in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8,", "model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word # list of node IDs", "number of nodes times embeddings dimensionality # Retrieve corresponding targets # from training", "node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete:", "(CaseID) alpha = 0.6 label_map = {l: i for i, l in enumerate(np.unique(ext_targets),", "embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time()", "dimensionality # Retrieve corresponding targets # from training csv # core_targets = core_target_sample.loc[[int(node_id)", "n in walk] for walk in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0,", "the target label (CaseID) alpha = 0.6 label_map = {l: i for i,", "i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target]", "sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw =", "(unormalised) probability, 1/p, of returning to source node q=1.7, # Defines (unormalised) probability,", "node q=1.7, # Defines (unormalised) probability, 1/q, for moving away from source node", "1/q, for moving away from source node ) t1 = time.time() print(\"Number of", "time.time() print(\"Number of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n)", "embedding vector # The embedding vectors can be retrieved from model.wv using the", "# list of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size number", "if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if", "embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding points, coloring them", "with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding points, coloring them by", "import time import pandas as pd import numpy as np import stellargraph as", "= time.time() print(\"Number of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks =", "enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target) else", "v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2", "TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding points, coloring them by the", "v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and WORD2VEC", "# Defines (unormalised) probability, 1/p, of returning to source node q=1.7, # Defines", "node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids", "ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f}", "random walks per root node p=0.6, # Defines (unormalised) probability, 1/p, of returning", "Defines (unormalised) probability, 1/q, for moving away from source node ) t1 =", "= time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum length", "s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in walk] for walk in walks]", "WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()),", "random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in", "t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d", "to source node q=1.7, # Defines (unormalised) probability, 1/q, for moving away from", "pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target) else 0 for target", "vectors can be retrieved from model.wv using the node ID. # model.wv[\"19231\"].shape #", "complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw", "= 1 node_colours = [label_map[target] if pd.notna(target) else 0 for target in ext_targets]", "for walk in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5)", "= 0.6 label_map = {l: i for i, l in enumerate(np.unique(ext_targets), start=10) if", "numpy as np import stellargraph as sg from gensim.models import Word2Vec import matplotlib.pyplot", "nodes times embeddings dimensionality # Retrieve corresponding targets # from training csv #", "#### Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0", "node embeddings node_ids = model.wv.index2word # list of node IDs node_embeddings = (model.wv.vectors)", "from gensim.models import Word2Vec import matplotlib.pyplot as plt from utils.visualization import get_TSNE def", "# from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets =", "label (CaseID) alpha = 0.6 label_map = {l: i for i, l in", "node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings", "sg=1, workers=8, iter=5) # size: length of embedding vector # The embedding vectors", "for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize", "returning to source node q=1.7, # Defines (unormalised) probability, 1/q, for moving away", "plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node", "points, coloring them by the target label (CaseID) alpha = 0.6 label_map =", "stellargraph as sg from gensim.models import Word2Vec import matplotlib.pyplot as plt from utils.visualization", "from source node ) t1 = time.time() print(\"Number of random walks: {} in", "Retrieve node embeddings node_ids = model.wv.index2word # list of node IDs node_embeddings =", "csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID", "in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in", "# Draw the embedding points, coloring them by the target label (CaseID) alpha", "size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size: length of embedding vector #", "moving away from source node ) t1 = time.time() print(\"Number of random walks:", "Draw the embedding points, coloring them by the target label (CaseID) alpha =", "targets # from training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids", "coloring them by the target label (CaseID) alpha = 0.6 label_map = {l:", "embeddings node_ids = model.wv.index2word # list of node IDs node_embeddings = (model.wv.vectors) #", "label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target) else 0 for target in", "ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, )", "q=1.7, # Defines (unormalised) probability, 1/q, for moving away from source node )", "target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\",", "import Word2Vec import matplotlib.pyplot as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets,", "walk n=10, # number of random walks per root node p=0.6, # Defines", "of size number of nodes times embeddings dimensionality # Retrieve corresponding targets #", "as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G =", "for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours =", "= model.wv.index2word # list of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of", "p=0.6, # Defines (unormalised) probability, 1/p, of returning to source node q=1.7, #", "and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run(", "print(\"Number of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for", "# from training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if", "0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1],", "[label_map[target] if pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter(", "# Retrieve node embeddings node_ids = model.wv.index2word # list of node IDs node_embeddings", "nodes=list(G.nodes()), # root nodes length=10, # maximum length of a random walk n=10,", "# number of random walks per root node p=0.6, # Defines (unormalised) probability,", "s\") # Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding", "int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id)", "0.6 label_map = {l: i for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)}", "start=10) if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target) else 0", "if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target) else 0 for", "t1 = time.time() print(\"Number of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks", "Retrieve corresponding targets # from training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id", "embedding points, coloring them by the target label (CaseID) alpha = 0.6 label_map", "embedding vectors can be retrieved from model.wv using the node ID. # model.wv[\"19231\"].shape", "# The embedding vectors can be retrieved from model.wv using the node ID.", "import matplotlib.pyplot as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample):", "= v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\")", "= sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes length=10,", "get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding", "DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()), # root", "time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum length of", "source node q=1.7, # Defines (unormalised) probability, 1/q, for moving away from source", "source node ) t1 = time.time() print(\"Number of random walks: {} in {:.2f}", "1 node_colours = [label_map[target] if pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15,", "core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets", "as sg from gensim.models import Word2Vec import matplotlib.pyplot as plt from utils.visualization import", "walks per root node p=0.6, # Defines (unormalised) probability, 1/p, of returning to", "for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for", "15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization", "length of a random walk n=10, # number of random walks per root", "NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks =", "print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()), #", "be retrieved from model.wv using the node ID. # model.wv[\"19231\"].shape # Retrieve node", "data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id", "node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE", "corresponding targets # from training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in", "label_map = {l: i for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0]", "pd import numpy as np import stellargraph as sg from gensim.models import Word2Vec", "of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size number of nodes", "list of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size number of", "walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in walk]", "in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size:", "from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id)", "workers=8, iter=5) # size: length of embedding vector # The embedding vectors can", "{l: i for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1", "for moving away from source node ) t1 = time.time() print(\"Number of random", "# ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID #", "# Defines (unormalised) probability, 1/q, for moving away from source node ) t1", "(unormalised) probability, 1/q, for moving away from source node ) t1 = time.time()", "Defines (unormalised) probability, 1/p, of returning to source node q=1.7, # Defines (unormalised)", "= v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID", "plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE", "The embedding vectors can be retrieved from model.wv using the node ID. #", "sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes length=10, #", "vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for", "gensim.models import Word2Vec import matplotlib.pyplot as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets,", "nodes length=10, # maximum length of a random walk n=10, # number of", "root nodes length=10, # maximum length of a random walk n=10, # number", "cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case ID\") plt.show()", "vector # The embedding vectors can be retrieved from model.wv using the node", "node_embeddings = (model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality", "Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 =", "node p=0.6, # Defines (unormalised) probability, 1/p, of returning to source node q=1.7,", "n=10, # number of random walks per root node p=0.6, # Defines (unormalised)", "probability, 1/p, of returning to source node q=1.7, # Defines (unormalised) probability, 1/q,", "in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha,", "node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size number of nodes times", "1/p, of returning to source node q=1.7, # Defines (unormalised) probability, 1/q, for", "import numpy as np import stellargraph as sg from gensim.models import Word2Vec import", "# root nodes length=10, # maximum length of a random walk n=10, #", "from model.wv using the node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids", "target label (CaseID) alpha = 0.6 label_map = {l: i for i, l", "get_TSNE(node_embeddings) # Draw the embedding points, coloring them by the target label (CaseID)", "the node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word #", "walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size: length", "# size: length of embedding vector # The embedding vectors can be retrieved", "model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size: length of", "# Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding points,", "for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours,", "a random walk n=10, # number of random walks per root node p=0.6,", "as np import stellargraph as sg from gensim.models import Word2Vec import matplotlib.pyplot as", "window=5, min_count=0, sg=1, workers=8, iter=5) # size: length of embedding vector # The", "core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id)", "from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets)", "t0 = time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum", "= core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets =", "1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case", "node_ids = model.wv.index2word # list of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray", "plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case ID\") plt.show() return node_ids, node_embeddings,", "length of embedding vector # The embedding vectors can be retrieved from model.wv", "number of random walks per root node p=0.6, # Defines (unormalised) probability, 1/p,", "for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets", "embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings", "node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets =", "maximum length of a random walk n=10, # number of random walks per", "with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks", "embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t. Extended", "= rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum length of a random", "iter=5) # size: length of embedding vector # The embedding vectors can be", "np import stellargraph as sg from gensim.models import Word2Vec import matplotlib.pyplot as plt", "IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings", "probability, 1/q, for moving away from source node ) t1 = time.time() print(\"Number", "from training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id)", "def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with", "ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data", "ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from", "if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id", "int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in", ") plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case ID\") plt.show() return node_ids,", "# numpy.ndarray of size number of nodes times embeddings dimensionality # Retrieve corresponding", "node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time()", "# model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word # list of node", "Word2Vec import matplotlib.pyplot as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample,", "of node embeddings w.r.t. Extended Case ID\") plt.show() return node_ids, node_embeddings, core_targets, ext_targets", "matplotlib.pyplot as plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G", "{(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the", "them by the target label (CaseID) alpha = 0.6 label_map = {l: i", "model.wv.index2word # list of node IDs node_embeddings = (model.wv.vectors) # numpy.ndarray of size", "the embedding points, coloring them by the target label (CaseID) alpha = 0.6", "in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if pd.notna(target)", "sg from gensim.models import Word2Vec import matplotlib.pyplot as plt from utils.visualization import get_TSNE", "(model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality # Retrieve", "= time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d =", "node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word # list", "= {l: i for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] =", "= [label_map[target] if pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\")", "node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id", "plt from utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets,", "away from source node ) t1 = time.time() print(\"Number of random walks: {}", "random walk n=10, # number of random walks per root node p=0.6, #", "walks = rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum length of a", "node ) t1 = time.time() print(\"Number of random walks: {} in {:.2f} s\".format(len(walks),", "embeddings dimensionality # Retrieve corresponding targets # from training csv # core_targets =", "walk in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) #", "core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in", "pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0],", "else 0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:,", "node_colours = [label_map[target] if pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15, 15))", "in walk] for walk in walks] model = Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1,", "print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) #", "pandas as pd import numpy as np import stellargraph as sg from gensim.models", "size: length of embedding vector # The embedding vectors can be retrieved from", "import stellargraph as sg from gensim.models import Word2Vec import matplotlib.pyplot as plt from", "e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and", "using the node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word", "in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID", "numpy.ndarray of size number of nodes times embeddings dimensionality # Retrieve corresponding targets", "as pd import numpy as np import stellargraph as sg from gensim.models import", "0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t.", "can be retrieved from model.wv using the node ID. # model.wv[\"19231\"].shape # Retrieve", "if pd.notna(target) else 0 for target in ext_targets] plt.figure(figsize=(15, 15)) plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:,", "Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings) # Draw the embedding points, coloring", "of nodes times embeddings dimensionality # Retrieve corresponding targets # from training csv", "for node_id in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 =", "by the target label (CaseID) alpha = 0.6 label_map = {l: i for", "(t1-t0))) str_walks = [[str(n) for n in walk] for walk in walks] model", "plt.axes().set(aspect=\"equal\") plt.scatter( embs_2d[:, 0], embs_2d[:, 1], c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of", "c=node_colours, cmap=\"jet\", alpha=alpha, ) plt.title(\"TSNE visualization of node embeddings w.r.t. Extended Case ID\")", "i for i, l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours", "time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with TSNE embs_2d = get_TSNE(node_embeddings)", "[[str(n) for n in walk] for walk in walks] model = Word2Vec(str_walks, size=128,", "list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID", "length=10, # maximum length of a random walk n=10, # number of random", "{:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in walk] for walk in", "of a random walk n=10, # number of random walks per root node", ") t1 = time.time() print(\"Number of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0)))", "Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size: length of embedding vector", "= ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices'", "in node_ids]].CoreCaseGraphID ext_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk", "visualization of node embeddings w.r.t. Extended Case ID\") plt.show() return node_ids, node_embeddings, core_targets,", "= (model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality #", "of random walks per root node p=0.6, # Defines (unormalised) probability, 1/p, of", "sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC", "list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id) for node_id in node_ids]].CoreCaseGraphID ext_targets", "per root node p=0.6, # Defines (unormalised) probability, 1/p, of returning to source", "of returning to source node q=1.7, # Defines (unormalised) probability, 1/q, for moving", "size number of nodes times embeddings dimensionality # Retrieve corresponding targets # from", "= get_TSNE(node_embeddings) # Draw the embedding points, coloring them by the target label", "{} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in walk] for", "min_count=0, sg=1, workers=8, iter=5) # size: length of embedding vector # The embedding", "G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\")", "in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n in walk] for walk", "of embedding vector # The embedding vectors can be retrieved from model.wv using", "times embeddings dimensionality # Retrieve corresponding targets # from training csv # core_targets", "# Retrieve corresponding targets # from training csv # core_targets = core_target_sample.loc[[int(node_id) for", "alpha = 0.6 label_map = {l: i for i, l in enumerate(np.unique(ext_targets), start=10)", "# maximum length of a random walk n=10, # number of random walks", "training csv # core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in", "v_sample.loc[[int(node_id) for node_id in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") #", "<reponame>nicolas-racchi/hpc2020-graphML import time import pandas as pd import numpy as np import stellargraph", "in node_ids]].ExtendedCaseGraphID t2 = time.time() print(f\"Deepwalk complete: {(t2-t0):.2f} s\") # Visualize embeddings with", "utils.visualization import get_TSNE def sg_DeepWalk(v_sets, e_sets, v_sample, e_sample): G = sg.StellarDiGraph(v_sets, e_sets) ####", "ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids = model.wv.index2word # list of", "e_sample): G = sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and WORD2VEC print(\"Running", "for n in walk] for walk in walks] model = Word2Vec(str_walks, size=128, window=5,", "l in enumerate(np.unique(ext_targets), start=10) if pd.notna(l)} label_map[0] = 1 node_colours = [label_map[target] if", "# core_targets = core_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in list(core_target_sample.index)]].CaseID #", "root node p=0.6, # Defines (unormalised) probability, 1/p, of returning to source node", "retrieved from model.wv using the node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings", "model.wv using the node ID. # model.wv[\"19231\"].shape # Retrieve node embeddings node_ids =", "of random walks: {} in {:.2f} s\".format(len(walks), (t1-t0))) str_walks = [[str(n) for n", "= Word2Vec(str_walks, size=128, window=5, min_count=0, sg=1, workers=8, iter=5) # size: length of embedding", "in list(core_target_sample.index)]].CaseID # ext_targets = ext_target_sample.loc[[int(node_id) for node_id in node_ids if int(node_id) in", "rw.run( nodes=list(G.nodes()), # root nodes length=10, # maximum length of a random walk", "= sg.StellarDiGraph(v_sets, e_sets) #### Graph embedding with NODE2VEC and WORD2VEC print(\"Running DeepWalk\") rw", "str_walks = [[str(n) for n in walk] for walk in walks] model =", "rw = sg.data.BiasedRandomWalk(G) t0 = time.time() walks = rw.run( nodes=list(G.nodes()), # root nodes", "= [[str(n) for n in walk] for walk in walks] model = Word2Vec(str_walks,", "node_ids if int(node_id) in list(ext_target_sample.index)]].CaseID # from vertices' data core_targets = v_sample.loc[[int(node_id) for" ]
[ "myStr = '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False 不支持 .", ". print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1' print(myStr.isalnum()) # False 不支持", "myStr = '123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) # False 不支持", "支持 包含num myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123'", "False myStr = '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False 不支持", "= '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False 不支持 . myStr", "符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True 支持", "不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr = '123' print(myStr.isnumeric()) # True", "'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持", "print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1' print(myStr.isalnum()) # False 不支持 .", "= 'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持", "# False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum())", "print(myStr.isalnum()) # True 支持 包含num myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字", "False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) #", "print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr =", "只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) #", "print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1'", "print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr = '123'", "# True 支持 包含num myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr", "'0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False 不支持 . myStr =", "不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha()) #", "True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1'", "支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1' print(myStr.isalpha())", "= '' print(myStr.isalnum()) # False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写", "print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr", "# False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr = '123' print(myStr.isnumeric())", "= 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr", "= '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False", "'123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum())", "myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False", "= 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False", "'123' print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr", "# True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr = '0.1'", "= '123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) # False 不支持 .", "True 支持 包含num myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr =", "'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr =", "myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num", "myStr = '' print(myStr.isalnum()) # False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True", "包含num print(myStr.isalnum()) # True 支持 包含num myStr = '123' print(myStr.isnumeric()) # True 只支持", "myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) #", "# False 不支持 . print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1' print(myStr.isalnum())", "包含num myStr = '123' print(myStr.isnumeric()) # True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric())", "不支持 . print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1' print(myStr.isalnum()) # False", "# True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr =", "False 不支持 包含num print(myStr.isalnum()) # True 支持 包含num myStr = '123' print(myStr.isnumeric()) #", "# False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*'", "True 只支持 全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric())", "myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) #", "print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) #", "'' print(myStr.isalnum()) # False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr", "# False myStr = '0.1' print(myStr.isnumeric()) # False 不支持 . print(myStr.isalnum()) # False", "print(myStr.isalnum()) # False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr =", "False 不支持 . print(myStr.isalnum()) # False 不支持 . myStr = 'abc123.1' print(myStr.isalnum()) #", "'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha()) # False 不支持 符号", "不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num print(myStr.isalnum()) # True", "False 不支持空 myStr = 'abCC' print(myStr.isalpha()) # True 支持大写 myStr = 'abc*' print(myStr.isalpha())", "print(myStr.isalpha()) # False 不支持 符号 myStr = 'abc1' print(myStr.isalpha()) # False 不支持 包含num", "全数字 myStr = '123.123' print(myStr.isnumeric()) # False myStr = '0.1' print(myStr.isnumeric()) # False" ]
[ "41.7 & 40.5 SCWS & 54.1 & 65.6 & 60.7 & 61.8 &", "& 77.7 An-SYN & 61.8 & 59.8 & 51.0 & 42.7 & 60.0", "& 62.9 WS-REL & 53.4 & 63.6 & 59.6 & 60.1 & 65.1", "them as boxes on the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height),", "& 53.4 & 63.6 & 59.6 & 60.1 & 65.1 & 63.5 WS-SEM", "fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0]", "bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist)", "& 59.8 & 59.1 & 59.7 & 62.9 WS-REL & 53.4 & 63.6", "dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot the", "73.5 & 36.2 & 38.6 & 77.2 TOEFL & 83.8 & 81.2 &", "29.0 & 41.7 & 40.5 SCWS & 54.1 & 65.6 & 60.7 &", "TOEFL & 83.8 & 81.2 & 86.2 & 78.8 & 87.5 & 88.8\"\"\"", "88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab", "Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74),", "(\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest of them as boxes on", "ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black')", "66.4 SIMLEX & 33.7 & 36.7 & 41.1 & 34.5 & 42.4 &", "WS & 58.6 & 70.8 & 67.4 & 68.0 & 70.8 & 70.1", "61.8 & 67.3 & 66.4 SIMLEX & 33.7 & 36.7 & 41.1 &", "& 28.1 & 32.9 & 37.2 & 29.0 & 41.7 & 40.5 SCWS", "& 81.2 & 86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import", "for e in row[1:]] # Plot the last number as a bar bar_artist,=plt.bar(idx+0.1,", "pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e", "enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white',", "& 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from", "the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot the last number", "86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import", "ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3],", "63.5 WS-SEM & 69.0 & 78.4 & 76.1 & 76.8 & 78.8 &", "import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig fig = plt.figure() ax", "75.9 & 77.7 An-SYN & 61.8 & 59.8 & 51.0 & 42.7 &", "& 54.1 & 65.6 & 60.7 & 61.8 & 67.3 & 66.4 SIMLEX", "(\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter", "61.8 & 59.8 & 51.0 & 42.7 & 60.0 & 64.3 An-SEM &", "in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for", "viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import", "& 65.1 & 63.5 WS-SEM & 69.0 & 78.4 & 76.1 & 76.8", "# Plot the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black',", "color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the", "75.8 RW & 28.1 & 32.9 & 37.2 & 29.0 & 41.7 &", "patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4,", "70.1 MTURK & 61.7 & 65.1 & 59.8 & 59.1 & 59.7 &", "76.6 & 75.9 & 77.7 An-SYN & 61.8 & 59.8 & 51.0 &", "ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy', fontsize=13, rotation=270, color='gray') savefig(\"comparative_figure.pdf\", bbox_inches='tight')", "59.1 & 59.7 & 62.9 WS-REL & 53.4 & 63.6 & 59.6 &", "edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab,", "76.0 & 71.4 & 71.2 & 75.8 RW & 28.1 & 32.9 &", "pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1))", "& 66.4 SIMLEX & 33.7 & 36.7 & 41.1 & 34.5 & 42.4", "& 68.0 & 70.8 & 70.1 MTURK & 61.7 & 65.1 & 59.8", "rest of them as boxes on the bar. for j, p in enumerate(perf[0:-1]):", "& 41.7 & 40.5 SCWS & 54.1 & 65.6 & 60.7 & 61.8", "& 33.7 & 36.7 & 41.1 & 34.5 & 42.4 & 43.9 WS", "& 78.5 & 82.7 & 76.6 & 75.9 & 77.7 An-SYN & 61.8", "loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)])", "41.1 & 34.5 & 42.4 & 43.9 WS & 58.6 & 70.8 &", "51.0 & 42.7 & 60.0 & 64.3 An-SEM & 80.9 & 73.7 &", "& 37.2 & 29.0 & 41.7 & 40.5 SCWS & 54.1 & 65.6", "& 73.7 & 73.5 & 36.2 & 38.6 & 77.2 TOEFL & 83.8", "59.8 & 59.1 & 59.7 & 62.9 WS-REL & 53.4 & 63.6 &", "67.3 & 66.4 SIMLEX & 33.7 & 36.7 & 41.1 & 34.5 &", "j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\",", "ba.append(bar_artist) # Plot the rest of them as boxes on the bar. for", "& 76.8 & 78.8 & 79.2 RG & 73.8 & 78.2 & 80.4", "alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest of them", "for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel", "ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95,", ".74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2,", "& 76.6 & 75.9 & 77.7 An-SYN & 61.8 & 59.8 & 51.0", "& 71.4 & 71.2 & 75.8 RW & 28.1 & 32.9 & 37.2", "Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both')", "last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\",", "80.9 & 73.7 & 73.5 & 36.2 & 38.6 & 77.2 TOEFL &", "pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the", "& 70.8 & 70.1 MTURK & 61.7 & 65.1 & 59.8 & 59.1", "of them as boxes on the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j,", "& 75.8 RW & 28.1 & 32.9 & 37.2 & 29.0 & 41.7", "& 59.6 & 60.1 & 65.1 & 63.5 WS-SEM & 69.0 & 78.4", "& 78.2 & 80.4 & 71.2 & 74.4 & 80.8 MC & 70.5", "& 61.8 & 59.8 & 51.0 & 42.7 & 60.0 & 64.3 An-SEM", "pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin)", "\"All Views\")) ba.append(bar_artist) # Plot the rest of them as boxes on the", "& 60.1 & 65.1 & 63.5 WS-SEM & 69.0 & 78.4 & 76.1", "& 60.0 & 64.3 An-SEM & 80.9 & 73.7 & 73.5 & 36.2", "= plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row", "& 69.0 & 78.4 & 76.1 & 76.8 & 78.8 & 79.2 RG", "71.2 & 74.4 & 80.8 MC & 70.5 & 78.5 & 82.7 &", "RW & 28.1 & 32.9 & 37.2 & 29.0 & 41.7 & 40.5", "xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot the last number as", "& 63.5 WS-SEM & 69.0 & 78.4 & 76.1 & 76.8 & 78.8", "ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is", "38.6 & 77.2 TOEFL & 83.8 & 81.2 & 86.2 & 78.8 &", "& 82.7 & 76.6 & 75.9 & 77.7 An-SYN & 61.8 & 59.8", "& 36.2 & 38.6 & 77.2 TOEFL & 83.8 & 81.2 & 86.2", "# The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] #", "& 29.0 & 41.7 & 40.5 SCWS & 54.1 & 65.6 & 60.7", "& 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot", "58.6 & 70.8 & 67.4 & 68.0 & 70.8 & 70.1 MTURK &", "43.9 WS & 58.6 & 70.8 & 67.4 & 68.0 & 70.8 &", "& 60.7 & 61.8 & 67.3 & 66.4 SIMLEX & 33.7 & 36.7", "the rest of them as boxes on the bar. for j, p in", "ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy', fontsize=13,", "MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0 &", "matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig fig = plt.figure()", "34.5 & 42.4 & 43.9 WS & 58.6 & 70.8 & 67.4 &", "71.2 & 75.8 RW & 28.1 & 32.9 & 37.2 & 29.0 &", "pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100)", "import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec,", "import division conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 &", "& 79.2 RG & 73.8 & 78.2 & 80.4 & 71.2 & 74.4", "from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison", "69.0 & 78.4 & 76.1 & 76.8 & 78.8 & 79.2 RG &", "WS-SEM & 69.0 & 78.4 & 76.1 & 76.8 & 78.8 & 79.2", "36.2 & 38.6 & 77.2 TOEFL & 83.8 & 81.2 & 86.2 &", "The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot", "61.7 & 65.1 & 59.8 & 59.1 & 59.7 & 62.9 WS-REL &", "# Plot the rest of them as boxes on the bar. for j,", "67.4 & 68.0 & 70.8 & 70.1 MTURK & 61.7 & 65.1 &", "and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9},", "80.4 & 71.2 & 74.4 & 80.8 MC & 70.5 & 78.5 &", "MC & 70.5 & 78.5 & 82.7 & 76.6 & 75.9 & 77.7", "width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The", "Views\")) ba.append(bar_artist) # Plot the rest of them as boxes on the bar.", "from pylab import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7", "pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for", "83.8 & 81.2 & 86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\"", "& 76.0 & 71.4 & 71.2 & 75.8 RW & 28.1 & 32.9", "alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker", "77.7 An-SYN & 61.8 & 59.8 & 51.0 & 42.7 & 60.0 &", "label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import", "facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from", "81.2 & 86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib", "53.4 & 63.6 & 59.6 & 60.1 & 65.1 & 63.5 WS-SEM &", "& 73.9 & 76.0 & 71.4 & 71.2 & 75.8 RW & 28.1", "in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"),", "MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0 & 71.4 & 71.2", "colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig", "& 86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg')", "ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom')", "65.1 & 59.8 & 59.1 & 59.7 & 62.9 WS-REL & 53.4 &", "viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0 & 71.4 & 71.2 &", "54.1 & 65.6 & 60.7 & 61.8 & 67.3 & 66.4 SIMLEX &", "64.3 An-SEM & 80.9 & 73.7 & 73.5 & 36.2 & 38.6 &", "on the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j],", "65.6 & 60.7 & 61.8 & 67.3 & 66.4 SIMLEX & 33.7 &", "& 80.4 & 71.2 & 74.4 & 80.8 MC & 70.5 & 78.5", "& 80.9 & 73.7 & 73.5 & 36.2 & 38.6 & 77.2 TOEFL", "number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \"", "ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy', fontsize=13, rotation=270, color='gray') savefig(\"comparative_figure.pdf\",", "as boxes on the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width,", "xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot the last number as a", "__future__ import division conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4", "from __future__ import division conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN &", "40.5 SCWS & 54.1 & 65.6 & 60.7 & 61.8 & 67.3 &", "& 65.6 & 60.7 & 61.8 & 67.3 & 66.4 SIMLEX & 33.7", "boxes on the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height,", "An-SEM & 80.9 & 73.7 & 73.5 & 36.2 & 38.6 & 77.2", "conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 &", "Plot the rest of them as boxes on the bar. for j, p", "42.7 & 60.0 & 64.3 An-SEM & 80.9 & 73.7 & 73.5 &", "shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy',", "70.4 & 73.9 & 76.0 & 71.4 & 71.2 & 75.8 RW &", "width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist)", "& 71.2 & 74.4 & 80.8 MC & 70.5 & 78.5 & 82.7", "is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]] # Plot the last", "& 67.3 & 66.4 SIMLEX & 33.7 & 36.7 & 41.1 & 34.5", "An-SYN & 61.8 & 59.8 & 51.0 & 42.7 & 60.0 & 64.3", "matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between", "MTURK & 61.7 & 65.1 & 59.8 & 59.1 & 59.7 & 62.9", "& 42.4 & 43.9 WS & 58.6 & 70.8 & 67.4 & 68.0", "70.5 & 78.5 & 82.7 & 76.6 & 75.9 & 77.7 An-SYN &", "& 70.1 MTURK & 61.7 & 65.1 & 59.8 & 59.1 & 59.7", "& 78.8 & 79.2 RG & 73.8 & 78.2 & 80.4 & 71.2", "& 38.6 & 77.2 TOEFL & 83.8 & 81.2 & 86.2 & 78.8", "dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in row[1:]]", "78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as", "bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"))", "MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove", "e in row[1:]] # Plot the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1],", "60.1 & 65.1 & 63.5 WS-SEM & 69.0 & 78.4 & 76.1 &", "& 70.4 & 73.9 & 76.0 & 71.4 & 71.2 & 75.8 RW", "between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]],", "& 34.5 & 42.4 & 43.9 WS & 58.6 & 70.8 & 67.4", "row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e in", "as plt plt.style.use('ggplot') from pylab import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1)", "& 75.9 & 77.7 An-SYN & 61.8 & 59.8 & 51.0 & 42.7", "74.4 & 80.8 MC & 70.5 & 78.5 & 82.7 & 76.6 &", "68.0 & 70.8 & 70.1 MTURK & 61.7 & 65.1 & 59.8 &", "color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\")", "bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\",", "& 67.4 & 68.0 & 70.8 & 70.1 MTURK & 61.7 & 65.1", "ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black')", "78.2 & 80.4 & 71.2 & 74.4 & 80.8 MC & 70.5 &", "a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All", "matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig fig = plt.figure() ax =", "32.9 & 37.2 & 29.0 & 41.7 & 40.5 SCWS & 54.1 &", "& 63.6 & 59.6 & 60.1 & 65.1 & 63.5 WS-SEM & 69.0", "for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \"", "73.8 & 78.2 & 80.4 & 71.2 & 74.4 & 80.8 MC &", "W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0", "73.9 & 76.0 & 71.4 & 71.2 & 75.8 RW & 28.1 &", "perf=[float(e) for e in row[1:]] # Plot the last number as a bar", "edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest", "63.6 & 59.6 & 60.1 & 65.1 & 63.5 WS-SEM & 69.0 &", "width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot", "row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e)", "the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8)", "37.2 & 29.0 & 41.7 & 40.5 SCWS & 54.1 & 65.6 &", "import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig fig", "& 83.8 & 81.2 & 86.2 & 78.8 & 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\")", "SCWS & 54.1 & 65.6 & 60.7 & 61.8 & 67.3 & 66.4", "65.1 & 63.5 WS-SEM & 69.0 & 78.4 & 76.1 & 76.8 &", "& 51.0 & 42.7 & 60.0 & 64.3 An-SEM & 80.9 & 73.7", "36.7 & 41.1 & 34.5 & 42.4 & 43.9 WS & 58.6 &", "& 64.3 An-SEM & 80.9 & 73.7 & 73.5 & 36.2 & 38.6", "xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] #", "71.4 & 71.2 & 75.8 RW & 28.1 & 32.9 & 37.2 &", "& 80.8 MC & 70.5 & 78.5 & 82.7 & 76.6 & 75.9", "& 76.1 & 76.8 & 78.8 & 79.2 RG & 73.8 & 78.2", "MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0 & 71.4 &", "76.8 & 78.8 & 79.2 RG & 73.8 & 78.2 & 80.4 &", "division conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9", "78.5 & 82.7 & 76.6 & 75.9 & 77.7 An-SYN & 61.8 &", "77.2 TOEFL & 83.8 & 81.2 & 86.2 & 78.8 & 87.5 &", "MEN & 70.4 & 73.9 & 76.0 & 71.4 & 71.2 & 75.8", "p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, ))", "33.7 & 36.7 & 41.1 & 34.5 & 42.4 & 43.9 WS &", "60.0 & 64.3 An-SEM & 80.9 & 73.7 & 73.5 & 36.2 &", "\" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator,", "SIMLEX & 33.7 & 36.7 & 41.1 & 34.5 & 42.4 & 43.9", "as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\",", "& 43.9 WS & 58.6 & 70.8 & 67.4 & 68.0 & 70.8", "70.8 & 67.4 & 68.0 & 70.8 & 70.1 MTURK & 61.7 &", "ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1],", "& 70.5 & 78.5 & 82.7 & 76.6 & 75.9 & 77.7 An-SYN", "& 58.6 & 70.8 & 67.4 & 68.0 & 70.8 & 70.1 MTURK", "ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5],", "76.1 & 76.8 & 78.8 & 79.2 RG & 73.8 & 78.2 &", "87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot')", "savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for", "80.8 MC & 70.5 & 78.5 & 82.7 & 76.6 & 75.9 &", "& 42.7 & 60.0 & 64.3 An-SEM & 80.9 & 73.7 & 73.5", "pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in", "patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset", "& 87.5 & 88.8\"\"\" viewperf=viewperf.split(\"\\n\") colors=\"gbcykr\" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt", "WS-REL & 53.4 & 63.6 & 59.6 & 60.1 & 65.1 & 63.5", "bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest of them as", "& 61.7 & 65.1 & 59.8 & 59.1 & 59.7 & 62.9 WS-REL", "& 71.2 & 75.8 RW & 28.1 & 32.9 & 37.2 & 29.0", "enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip()) perf=[float(e) for e", "perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) #", "59.8 & 51.0 & 42.7 & 60.0 & 64.3 An-SEM & 80.9 &", "42.4 & 43.9 WS & 58.6 & 70.8 & 67.4 & 68.0 &", "& 65.1 & 59.8 & 59.1 & 59.7 & 62.9 WS-REL & 53.4", "Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08,", "59.6 & 60.1 & 65.1 & 63.5 WS-SEM & 69.0 & 78.4 &", "ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA',", "MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2], pa[-5], pa[-4]], loc=(.08, .74), prop={'size':9}, shadow=True)", "78.8 & 79.2 RG & 73.8 & 78.2 & 80.4 & 71.2 &", "plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in", "79.2 RG & 73.8 & 78.2 & 80.4 & 71.2 & 74.4 &", "& 40.5 SCWS & 54.1 & 65.6 & 60.7 & 61.8 & 67.3", "& 36.7 & 41.1 & 34.5 & 42.4 & 43.9 WS & 58.6", "& 32.9 & 37.2 & 29.0 & 41.7 & 40.5 SCWS & 54.1", "73.7 & 73.5 & 36.2 & 38.6 & 77.2 TOEFL & 83.8 &", "78.4 & 76.1 & 76.8 & 78.8 & 79.2 RG & 73.8 &", "70.8 & 70.1 MTURK & 61.7 & 65.1 & 59.8 & 59.1 &", "p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All", "\" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest of them as boxes", "\"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5))", "fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx,", "62.9 WS-REL & 53.4 & 63.6 & 59.6 & 60.1 & 65.1 &", "row[1:]] # Plot the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1],", "ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25", "in row[1:]] # Plot the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width,", "Plot the last number as a bar bar_artist,=plt.bar(idx+0.1, perf[-1], width=width, color=colors[-1], edgecolor='black', linewidth=0.4,", "matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') from pylab import savefig fig =", "ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]):", "& 41.1 & 34.5 & 42.4 & 43.9 WS & 58.6 & 70.8", "& 73.8 & 78.2 & 80.4 & 71.2 & 74.4 & 80.8 MC", "& 78.4 & 76.1 & 76.8 & 78.8 & 79.2 RG & 73.8", "59.7 & 62.9 WS-REL & 53.4 & 63.6 & 59.6 & 60.1 &", "& 74.4 & 80.8 MC & 70.5 & 78.5 & 82.7 & 76.6", "idx, row in enumerate(viewperf[1:]): row=row.split(\"&\") dataset=row[0] # The dataset is the xlabel xlab.append(dataset.strip())", "linewidth=0.4, alpha=0.8) bar_artist.set_label(conditions[-1].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\")) ba.append(bar_artist) # Plot the rest of", "import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[]", "the bar. for j, p in enumerate(perf[0:-1]): patch_artist=ax.add_patch(plt.Rectangle((idx+0.01*j, p-patch_height), width, patch_height, facecolor=colors[j], alpha=0.7,", "plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy', fontsize=13, rotation=270,", ")) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left')", "82.7 & 76.6 & 75.9 & 77.7 An-SYN & 61.8 & 59.8 &", "linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45,", "& 73.5 & 36.2 & 38.6 & 77.2 TOEFL & 83.8 & 81.2", "28.1 & 32.9 & 37.2 & 29.0 & 41.7 & 40.5 SCWS &", "& 59.1 & 59.7 & 62.9 WS-REL & 53.4 & 63.6 & 59.6", "60.7 & 61.8 & 67.3 & 66.4 SIMLEX & 33.7 & 36.7 &", "pylab import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[]", "rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1],", "patch_height, facecolor=colors[j], alpha=0.7, label=conditions[j].replace(\"(\", \" (\").replace(\"Allviews\", \"All Views\"), edgecolor='white', linewidth=0.4, )) pa.append(patch_artist) ax.set_xlim(xmax=len(xlab))", "= fig.add_subplot(1,1,1) xlab=[] width=0.8 patch_height=0.7 ba=[] pa=[] for idx, row in enumerate(viewperf[1:]): row=row.split(\"&\")", "& 61.8 & 67.3 & 66.4 SIMLEX & 33.7 & 36.7 & 41.1", "color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37, 'Accuracy', fontsize=13, rotation=270, color='gray')", "ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and MVLSA', color='black') ymin=25 ax.legend(handles=[ba[-1], pa[-3], pa[-1], pa[-2],", "plt.style.use('ggplot') from pylab import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[] width=0.8", "& 59.7 & 62.9 WS-REL & 53.4 & 63.6 & 59.6 & 60.1", "FormatStrFormatter ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.yaxis.set_ticks_position('both') ax.set_xticklabels([\"\"]+xlab, rotation=45, ha='left') ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_ticks_position('bottom') ax.set_title('Comparison between Word2Vec, Glove and", "prop={'size':9}, shadow=True) ax.set_ylabel(\"Correlation\") plt.axvline(x=9.95, color='black') ax.set_ylim(ymin=ymin) ax.set_yticklabels([\"%.2f\"%(e/100) for e in range(ymin-5,100,10)]) ax.text(13.2, ymin+37,", "plt plt.style.use('ggplot') from pylab import savefig fig = plt.figure() ax = fig.add_subplot(1,1,1) xlab=[]", "& 77.2 TOEFL & 83.8 & 81.2 & 86.2 & 78.8 & 87.5", "& 70.8 & 67.4 & 68.0 & 70.8 & 70.1 MTURK & 61.7", "& 59.8 & 51.0 & 42.7 & 60.0 & 64.3 An-SEM & 80.9", "MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN & 70.4 & 73.9 & 76.0 & 71.4", "<reponame>se4u/mvlsa from __future__ import division conditions=\"Glove W2Vec(Skipgram) MVLSA(Glove+W2Vec) MVLSA(Wiki) MVLSA(Allviews) MVLSA(Allviews+Glove+W2Vec)\".split() viewperf=r\"\"\" MEN", "RG & 73.8 & 78.2 & 80.4 & 71.2 & 74.4 & 80.8" ]
[ "from django.contrib import admin from .. import models from .bind import BindAdmin admin.site.register(models.Bind,", "coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin from", "utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin from ..", "unicode_literals from django.contrib import admin from .. import models from .bind import BindAdmin", "django.contrib import admin from .. import models from .bind import BindAdmin admin.site.register(models.Bind, BindAdmin)", "absolute_import, unicode_literals from django.contrib import admin from .. import models from .bind import", "import absolute_import, unicode_literals from django.contrib import admin from .. import models from .bind", "__future__ import absolute_import, unicode_literals from django.contrib import admin from .. import models from", "-*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin", "# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import", "from __future__ import absolute_import, unicode_literals from django.contrib import admin from .. import models", "-*- from __future__ import absolute_import, unicode_literals from django.contrib import admin from .. import" ]
[ "torch.nn import utils import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1):", "= x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 +", "in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True),", "__init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride,", "import torch.nn as nn import torch.nn.functional as F from torch.nn import utils import", "+= ', bias=False' return s.format(**self.__dict__) def forward(self, x): b, n, h, w =", "conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size **", "self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if bias: self.bias =", "** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def", "def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride,", "F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2)", "nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if", "dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module):", "stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class", "out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x):", "self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels,", "h = F.elu(h) h = self.conv2(h) h = F.elu(h) return h class upsample(nn.Module):", "utils import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__()", "def forward(self, x): h = self.conv1(x) h = F.elu(h) h = self.conv2(h) h", "2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self,", "else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d", "nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x):", "self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x)", "in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation,", "return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv =", "bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self,", "conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h = self.conv1(x)", "in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels,", "def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight,", "def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 =", "class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2", "stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in,", "def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size =", "self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x):", "x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv", "return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight,", "out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv =", "self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module):", "out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x) h =", "F.elu(h) h = self.conv2(h) h = F.elu(h) return h class upsample(nn.Module): def __init__(self,", "kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self):", "out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation,", "nn import torch.nn.functional as F from torch.nn import utils import math class conv5x5(nn.Module):", "out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return", "* len(self.padding): s += ', padding={padding}' if self.bias is None: s += ',", "if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 /", "class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels)", "self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d,", "fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def", "padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module):", "forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv", "padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module):", "def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1,", "super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv", "bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels,", "h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4)", "stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)", "stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect',", "self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h,", "kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1))", "in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation,", "out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self,", "self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv =", "out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def", "stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class", "+= ', padding={padding}' if self.bias is None: s += ', bias=False' return s.format(**self.__dict__)", "def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)", "s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding):", "in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def", "utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1,", "x): b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2,", "self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias", "1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels,", "self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self,", "import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import", "('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s +=", "out_channels) def forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h, 2) h =", "stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def", "dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation)", "return h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels,", "self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h", "math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv =", "in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation,", "import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv", ") self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), )", "torch.nn.functional as F from torch.nn import utils import math class conv5x5(nn.Module): def __init__(self,", "= PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self,", "', bias=False' return s.format(**self.__dict__) def forward(self, x): b, n, h, w = x.shape", "x): h = self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h) h =", "out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation,", "w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels,", "s.format(**self.__dict__) def forward(self, x): b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n,", "nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters()", "class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels,", "conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def", "= F.elu(h) h = self.conv2(h) h = F.elu(h) return h class upsample(nn.Module): def", "nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x)", "forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h) h", "-bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding", "= nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is", "kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x)", "** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight,", "utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1):", "stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels,", "super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv =", "kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return", "h = F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h) h = F.elu(h)", "if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride),", "bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self,", "def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1):", "class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels,", "x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__()", "F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 =", "None: s += ', bias=False' return s.format(**self.__dict__) def forward(self, x): b, n, h,", "nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size", "x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1,", "out_channels, stride=2) def forward(self, x): h = self.conv1(x) h = F.elu(h) h =", "return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv", "self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels,", "self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def", "stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight", "hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h = self.conv1(x) h", "self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv)", "def forward(self, x): b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size", "stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv)", "self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in)", "in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride", "import utils import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5,", "= nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self,", "h = F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__()", "def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,)", "nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size,", "utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3,", "in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv", "bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding !=", "return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels,", "math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}')", "padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight =", "conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h = self.conv1(x) h = F.elu(h) h", "downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2", "super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size", "self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ =", "is None: s += ', bias=False' return s.format(**self.__dict__) def forward(self, x): b, n,", "a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1", "upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 =", "h = self.conv2(h) h = F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels,", "padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class", "self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels,", "conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,", "', padding={padding}' if self.bias is None: s += ', bias=False' return s.format(**self.__dict__) def", "in_channels, kernel_size ** 2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias',", "from torch.nn import utils import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1,", "dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv", "bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels},", "reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound", "None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels,", "= ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s", "= self.conv1(x) h = F.elu(h) h = self.conv2(h) h = F.elu(h) return h", "self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d =", "in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def", "dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def", "torch import torch.nn as nn import torch.nn.functional as F from torch.nn import utils", "= conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h =", "return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv", "!= (0,) * len(self.padding): s += ', padding={padding}' if self.bias is None: s", "hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2)", "forward(self, x): h = self.conv1(x) h = F.elu(h) h = self.conv2(h) h =", "= nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def", "h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels,", "forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__()", "out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self,", "kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride", "class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__()", "self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h) h =", "super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x):", "torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else:", "nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels,", "out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation,", "self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv =", "def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5,", "1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels,", "= utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels,", ") self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if", "out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class", "self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels,", "= self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h) h", "conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h, 2) h", "nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not", "if self.bias is None: s += ', bias=False' return s.format(**self.__dict__) def forward(self, x):", "padding={padding}' if self.bias is None: s += ', bias=False' return s.format(**self.__dict__) def forward(self,", "h = self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h)", "PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels,", "torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), )", "conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)", "self.bias is None: s += ', bias=False' return s.format(**self.__dict__) def forward(self, x): b,", "= self.conv2(h) h = F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels, out_channels):", "PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size", "_ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self):", "class conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,", "conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,", "if self.padding != (0,) * len(self.padding): s += ', padding={padding}' if self.bias is", "x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))),", "__init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size", "bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self,", "__init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride,", "self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if", "kernel_size ** 2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None)", "__init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels)", "= nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride,", "= nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class", "self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h", "self.conv1(x) h = F.elu(h) h = self.conv2(h) h = F.elu(h) return h class", "dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False) self.conv", "def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3,", "def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels,", "class conv5x5(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels,", "n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class", "forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3,", "out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return", "= kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1,", "__init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0)", "dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False)", "s += ', padding={padding}' if self.bias is None: s += ', bias=False' return", "= conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h, 2)", "{out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s += ',", "= utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels):", "kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s += ', padding={padding}'", "2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c =", "kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self,", "+ torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__()", "0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1,", "= nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold =", "def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3,", "= nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return", "super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x):", "2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))", "self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold", "dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _", "= conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x)", "is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias,", "bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True),", "self.kernel_size = kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2,", "torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1", "self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h = self.conv1(x) h =", "utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros,", "nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module):", "stride=2) def forward(self, x): h = self.conv1(x) h = F.elu(h) h = self.conv2(h)", "def forward(self, x): h = self.conv1(x) h = F.pixel_shuffle(h, 2) h = F.elu(h)", "stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding, stride=stride,", "self.conv1 = conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h =", "self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv)", "forward(self, x): b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size **", "in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2),", "= torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels),", "as nn import torch.nn.functional as F from torch.nn import utils import math class", "padding=padding, stride=stride, dilation=dilation) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None:", "in_channels, stride, dilation=dilation), nn.ReLU(True), conv_zeros(in_channels, kernel_size ** 2), ) self.unfold = nn.Unfold(kernel_size, padding=padding,", "self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels,", "= stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if bias:", "self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels,", "def forward(self, x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__()", "nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s =", "bias=False' return s.format(**self.__dict__) def forward(self, x): b, n, h, w = x.shape return", "self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(PAKA3x3, self).__init__() self.conv =", "return s.format(**self.__dict__) def forward(self, x): b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b,", "x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__()", "= utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def __init__(self, in_channels, out_channels,", "stride={stride}') if self.padding != (0,) * len(self.padding): s += ', padding={padding}' if self.bias", "super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def", "padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv1x1(nn.Module): def", "import torch.nn.functional as F from torch.nn import utils import math class conv5x5(nn.Module): def", "x): return self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv =", "stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x)", "extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) *", "self.padding != (0,) * len(self.padding): s += ', padding={padding}' if self.bias is None:", "__init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)", "self.conv2(h) h = F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample,", "n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride)", "self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def", "/ math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' ',", "self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels,", "(1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample,", "class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1,", "super(PAKA3x3, self).__init__() self.conv = PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv =", "kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv_zeros(nn.Module):", "self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x):", "dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels,", "1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'", "None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound)", "= F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h) h = F.elu(h) return", "out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride =", "= 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s = ('{in_channels}, {out_channels},", "= F.elu(h) return h class upsample(nn.Module): def __init__(self, in_channels, out_channels): super(upsample, self).__init__() self.conv1", "return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, bias=False):", "self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv)", "self.conv_c = nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels,", "= torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels))", "= conv3x3(hidden_channels, out_channels, stride=2) def forward(self, x): h = self.conv1(x) h = F.elu(h)", "stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size ** 2, 1, 1)) if bias: self.bias", "* (1 + torch.tanh(self.conv_d(x).unsqueeze(1)+self.conv_c(x).unsqueeze(2))), self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels):", "len(self.padding): s += ', padding={padding}' if self.bias is None: s += ', bias=False'", "nn.Sequential(conv1x1(in_channels, in_channels, stride), nn.ReLU(True), conv_zeros(in_channels, in_channels), ) self.conv_d = nn.Sequential(conv3x3(in_channels, in_channels, stride, dilation=dilation),", "self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return", "= utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels,", "F from torch.nn import utils import math class conv5x5(nn.Module): def __init__(self, in_channels, out_channels,", "super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels, out_channels, stride=2) def forward(self,", "not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound,", "h = self.conv1(x) h = F.elu(h) h = self.conv2(h) h = F.elu(h) return", "nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, padding_mode='reflect', bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self,", "as F from torch.nn import utils import math class conv5x5(nn.Module): def __init__(self, in_channels,", "x): h = self.conv1(x) h = F.elu(h) h = self.conv2(h) h = F.elu(h)", "', stride={stride}') if self.padding != (0,) * len(self.padding): s += ', padding={padding}' if", "b, n, h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride,", "stride=1, dilation=1): super(conv5x5, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=stride, padding=2*dilation, dilation=dilation, bias=False)", "F.pixel_shuffle(h, 2) h = F.elu(h) h = self.conv2(h) h = F.elu(h) return h", "nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound =", "self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size **", "forward(self, x): return self.conv(x) class conv3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3,", "= nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def extra_repr(self): s", "** 2, 1, 1)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.conv_c", "dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class conv3x3(nn.Module): def", "bias=False): super(PAKA2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.weight = torch.nn.Parameter(torch.Tensor(out_channels, in_channels,", "forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0,", "conv3x3(in_channels, out_channels*4) self.conv2 = conv3x3(out_channels, out_channels) def forward(self, x): h = self.conv1(x) h", "__init__(self, in_channels, out_channels, stride=1, dilation=1): super(conv3x3, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride,", "out_channels, kernel_size=1, bias=False) nn.init.constant_(self.conv.weight, 0) def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def", "h, w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) *", "def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,", "torch.nn as nn import torch.nn.functional as F from torch.nn import utils import math", "conv1x1(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1,", "def forward(self, x): return self.conv(x) class PAKA3x3(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1):", "self.conv(x) class conv_zeros(nn.Module): def __init__(self, in_channels, out_channels): super(conv_zeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,", "kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x)", "w = x.shape return F.conv3d(self.unfold(x).view(b, n, self.kernel_size ** 2, h//self.stride, w//self.stride) * (1", "s += ', bias=False' return s.format(**self.__dict__) def forward(self, x): b, n, h, w", "PAKA2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x):", "bias=False) self.conv = utils.spectral_norm(self.conv) def forward(self, x): return self.conv(x) class PAKA2d(nn.Module): def __init__(self,", "__init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 = conv3x3(in_channels, hidden_channels) self.conv2 = conv3x3(hidden_channels,", "(0,) * len(self.padding): s += ', padding={padding}' if self.bias is None: s +=", "self.weight, self.bias).squeeze(2) class downsample(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(downsample, self).__init__() self.conv1 =" ]
[ "1 NOTE_OFF = 2 class Event: def __init__(self, etype): self.type = etype class", "EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class", "def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class EventNoteOff(Event):", "super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self, midi_note): super().__init__(EventType.NOTE_OFF)", "= etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity", "midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self,", "= 2 class Event: def __init__(self, etype): self.type = etype class EventNoteOn(Event): def", "EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class Event: def __init__(self, etype): self.type", "from enum import Enum class EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class", "velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self, midi_note):", "self.note = midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self, midi_note): super().__init__(EventType.NOTE_OFF) self.note", "NOTE_OFF = 2 class Event: def __init__(self, etype): self.type = etype class EventNoteOn(Event):", "import Enum class EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class Event: def", "class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity", "2 class Event: def __init__(self, etype): self.type = etype class EventNoteOn(Event): def __init__(self,", "etype): self.type = etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note =", "enum import Enum class EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class Event:", "midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self, midi_note): super().__init__(EventType.NOTE_OFF) self.note = midi_note", "__init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity = velocity class EventNoteOff(Event): def", "self.type = etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note", "= midi_note self.velocity = velocity class EventNoteOff(Event): def __init__(self, midi_note): super().__init__(EventType.NOTE_OFF) self.note =", "Enum class EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class Event: def __init__(self,", "Event: def __init__(self, etype): self.type = etype class EventNoteOn(Event): def __init__(self, midi_note, velocity):", "etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note = midi_note self.velocity =", "= 1 NOTE_OFF = 2 class Event: def __init__(self, etype): self.type = etype", "def __init__(self, etype): self.type = etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON)", "class Event: def __init__(self, etype): self.type = etype class EventNoteOn(Event): def __init__(self, midi_note,", "NOTE_ON = 1 NOTE_OFF = 2 class Event: def __init__(self, etype): self.type =", "class EventType(Enum): NOTE_ON = 1 NOTE_OFF = 2 class Event: def __init__(self, etype):", "__init__(self, etype): self.type = etype class EventNoteOn(Event): def __init__(self, midi_note, velocity): super().__init__(EventType.NOTE_ON) self.note" ]
[ "<gh_stars>0 #!/usr/bin/python import time for i in range(2 * 3600): print(f\"hello world {i}\",", "range(2 * 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello", "for i in range(2 * 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\")", "i in range(2 * 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as", "in range(2 * 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f:", "#!/usr/bin/python import time for i in range(2 * 3600): print(f\"hello world {i}\", flush=True)", "3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello", "print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello father,", "{i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello father, I'm here!\",", "world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello father, I'm", "* 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother,", "with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello father, I'm here!\", file=f) time.sleep(1)", "time for i in range(2 * 3600): print(f\"hello world {i}\", flush=True) with open(f\"artifacts-{i}.txt\",", "flush=True) with open(f\"artifacts-{i}.txt\", \"w\") as f: print(\"Hello mother, hello father, I'm here!\", file=f)", "import time for i in range(2 * 3600): print(f\"hello world {i}\", flush=True) with" ]
[ "{\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [],", "= {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\",", "= { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\":", "\"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc,", "cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == {", "repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data,", "\"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [", "assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}},", "= PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage)", "\"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc,", "== {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\":", "dvc.dvcfile import Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def", "= Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\",", "PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\",", "\"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize(", "\"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc,", "\"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\":", "def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as", "lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info: lockfile.load() assert \"Dvcfile.lock\" in str(exc_info.value)", "test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\":", "[ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\",", ") def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError)", "\"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir,", "Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc):", "== { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc,", "], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with", "{\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc,", "LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage", "path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\":", "= PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\":", "lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc):", "{ \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"}", "== { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc,", "repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\":", "\"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile", "{} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, {", "lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"},", "[{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc,", "from dvc.dvcfile import Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml", "\"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile", "lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load()", "[], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile =", "}, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data):", "assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data", "\"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage =", "stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load()", "def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\",", "lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data =", "{ **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\":", "dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage)", "dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage)", "lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert", "cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\":", "{\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\":", "[]}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\")", "\"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def", "{\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\":", "{\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data)", "cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc):", "from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage =", "import Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir,", "= PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"},", "**data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": {", "= PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() ==", "} def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\":", "dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\":", "{\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\",", "assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\":", "dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc,", "import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile =", "def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\")", "\"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\")", "\"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage =", "\"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\":", "from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\")", "Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": {", "= Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, }", "lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\":", "= Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc):", "dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert", "\"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\",", "data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage =", "\"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\":", "[{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage", "dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info: lockfile.load() assert \"Dvcfile.lock\"", "def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\":", "assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {}", "\"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc,", "PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {", "def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\",", "PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\":", "\"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data =", "stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\":", "path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir,", "repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, }", "stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\":", "\"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\":", "\"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } }", "Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc,", "test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage)", "PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert", "dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info: lockfile.load()", "\"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\":", "} } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\",", "\"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], )", "data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert", "= Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() ==", "\"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\": \"command\", \"deps\":", "data = { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\":", "path=\"path\", cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}}", "dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage", "{ \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], }", "{}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\":", "\"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\")", "\"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\":", "lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile =", "{ **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",)", "dvc): data = { \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}],", "{ \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}],", "{\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\",", "import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc,", "Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data", "stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load()", "[]}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\":", "repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def", "[{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data)", "{\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\",", "cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir,", "{ \"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\",", "corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info: lockfile.load() assert", "{\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\":", "cmd=\"command\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def", "repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load()", "path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() ==", "\"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\",", "lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} ==", "{\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = { \"s1\": { \"cmd\": \"command\",", "\"path\": \"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}},", "== Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\":", "== { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc): data = {", "pytest from dvc.dvcfile import Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize import", "lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage =", "\"path\", \"random\": \"value\"} ], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ],", "lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\",", "test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage)", "\"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], }", "**data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage", "\"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile", "dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data) stage", "[ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [", "test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}},", "} }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc,", "lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\":", "lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == {\"s1\": {\"cmd\": \"command\"}} def test_stage_dump_when_already_exists(tmp_dir,", "test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info:", "Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == {", "def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\")", "path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def", "\"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\",", "\"command\"}} def test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}}", "} def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\":", "@pytest.mark.parametrize( \"corrupt_data\", [ {\"s1\": {\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\",", "Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def", "{\"outs\": []}}, {\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\",", "data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert", "{\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load() @pytest.mark.parametrize( \"corrupt_data\",", "dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\", repo=dvc, path=\"path\", cmd=\"command\") lockfile", "import pytest from dvc.dvcfile import Lockfile, LockfileCorruptedError from dvc.stage import PipelineStage from dvc.utils.serialize", "} dump_yaml(\"path.lock\", data) lockfile = Lockfile(dvc, \"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\")", "assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile", "\"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ], } },", "\"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\": \"checksum\"}], } } dump_yaml(\"path.lock\", data) lockfile =", "\"path.lock\") stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data,", "{ \"s2\": {\"cmd\": \"command3\"}, } def test_load_when_lockfile_does_not_exist(tmp_dir, dvc): assert {} == Lockfile(dvc, \"pipelines.lock\").load()", "{\"s1\": {}}, { \"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\",", "= PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile = Lockfile(dvc, \"path.lock\") lockfile.dump(stage) assert lockfile.load() ==", "\"s1\": { \"cmd\": \"command\", \"outs\": [ {\"md5\": \"checksum\", \"path\": \"path\", \"random\": \"value\"} ],", "corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\") with pytest.raises(LockfileCorruptedError) as exc_info: lockfile.load() assert \"Dvcfile.lock\" in", "dvc.stage import PipelineStage from dvc.utils.serialize import dump_yaml def test_stage_dump_no_outs_deps(tmp_dir, dvc): stage = PipelineStage(name=\"s1\",", "test_stage_dump_when_already_exists(tmp_dir, dvc): data = {\"s1\": {\"cmd\": \"command\", \"deps\": [], \"outs\": []}} dump_yaml(\"path.lock\", data)", "\"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile = Lockfile(dvc, \"Dvcfile.lock\")", "PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\") lockfile.dump(stage) assert lockfile.load() == { \"s2\": {\"cmd\": \"command3\"}, }", "PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"},", "} def test_stage_overwrites_if_already_exists(tmp_dir, dvc): lockfile = Lockfile(dvc, \"path.lock\",) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\",", "\"s1\": { \"cmd\": \"command\", \"deps\": [{\"md5\": \"1.txt\", \"path\": \"checksum\"}], \"outs\": [{\"md5\": \"2.txt\", \"path\":", "\"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir, dvc, corrupt_data): dump_yaml(\"Dvcfile.lock\", corrupt_data) lockfile =", "lockfile.dump(stage) assert lockfile.load() == { **data, \"s2\": {\"cmd\": \"command2\"}, } def test_stage_dump_with_deps_and_outs(tmp_dir, dvc):", "], } }, {\"s1\": {\"cmd\": \"command\", \"deps\": [{\"md5\": \"checksum\"}]}}, ], ) def test_load_when_lockfile_is_corrupted(tmp_dir,", "stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command2\") lockfile.dump(stage) stage = PipelineStage(name=\"s2\", repo=dvc, path=\"path\", cmd=\"command3\")" ]
[ "store # Actions def save(self, data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None):", "InvalidPypeDataType(data_type) kwargs = {} if query is None else {'query_model': query} getattr(self, method)(data_type,", "raise NotImplementedError() # Source action invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self,", "in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.source] =", "class StorePype(Pype): def __init__(self, set, store): self._set = set self._store = store #", "**kwargs) return self.set def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype", "set import Set from model import Model from source import Source from store", "getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__')", "return self.set def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in", "raise NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source):", "data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError()", "StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store]", "def delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation def _store_method(self, method, data_type,", "Model from source import Source from store import Store class Pype(object): @property def", "source import Source from store import Store class Pype(object): @property def set(self): raise", "@property def set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError() @property def store(self):", "update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model):", "Action invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method += \"_set\"", "method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and", "SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.source]", "if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store]", "set, source): self._set = set self._source = source # Actions def one(self, query_model):", "self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def __init__(self, set, store): self._set =", "def latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self, query_model):", "self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define", "query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model)", "is None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for", "query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError()", "<filename>datapypes/pype.py from set import Set from model import Model from source import Source", "method += \"_set\" elif isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs", "result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results]) class", "raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError()", "kwargs = {} if query is None else {'query_model': query} getattr(self, method)(data_type, **kwargs)", "hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] =", "raise NotImplementedError() # Action invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set):", "from source import Source from store import Store class Pype(object): @property def set(self):", "NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self,", "results]) class StorePype(Pype): def __init__(self, set, store): self._set = set self._store = store", "def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return", "def all(self, query_model): raise NotImplementedError() # Source action invocation def retrieve_model(self, result): return", "method, data_type, query=None): if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model): method", "= cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in", "raise NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source action invocation def retrieve_model(self,", "def __init__(self, set, store): self._set = set self._store = store # Actions def", "Set from model import Model from source import Source from store import Store", "NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self,", "+= \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if query is None else", "search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise", "set, store): self._set = set self._store = store # Actions def save(self, data_type):", "NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() #", "__init__(self, set, store): self._set = set self._store = store # Actions def save(self,", "return self._store_method('save', data_type, query_model) # Define bindings in subclass def save_model(self, data_model): raise", "hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source] =", "and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source] = cls", "cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls", "Set): method += \"_set\" elif isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type)", "= cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__')", "action invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for", "self._store_method('save', data_type, query_model) # Define bindings in subclass def save_model(self, data_model): raise NotImplementedError()", "data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation def", "raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def", "query_model=None): return self._store_method('save', data_type, query_model) # Define bindings in subclass def save_model(self, data_model):", "def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define bindings in subclass", "self._set = set self._store = store # Actions def save(self, data_type): return self._store_method('save',", "Store class Pype(object): @property def set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError()", "query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source action invocation def", "def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() # Action", "self._set = set self._source = source # Actions def one(self, query_model): raise NotImplementedError()", "cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls", "class Pype(object): @property def set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError() @property", "return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) #", "SourcePype(Pype): def __init__(self, set, source): self._set = set self._source = source # Actions", "store import Store class Pype(object): @property def set(self): raise NotImplementedError() @property def source(self):", "Pype(object): @property def set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError() @property def", "NotImplementedError() # Source action invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results):", "raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation def _store_method(self,", "all(self, query_model): raise NotImplementedError() # Source action invocation def retrieve_model(self, result): return self.set.model(**result)", "raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError()", "cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.source] = cls", "self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type,", "Define bindings in subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise", "in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] =", "retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def __init__(self, set,", "update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set,", "self.set def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__:", "in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] =", "raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def", "def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def __init__(self,", "cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls", "Actions def one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self,", "raise NotImplementedError() @property def source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError() class", "set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError()", "@property def source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype): def", "r in results]) class StorePype(Pype): def __init__(self, set, store): self._set = set self._store", "Actions def save(self, data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update',", "data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type,", "class SourcePype(Pype): def __init__(self, set, source): self._set = set self._source = source #", "Source from store import Store class Pype(object): @property def set(self): raise NotImplementedError() @property", "NotImplementedError() @property def source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype):", "data_type, query_model) # Define bindings in subclass def save_model(self, data_model): raise NotImplementedError() def", "# Source action invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return", "NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set = set self._source = source", "raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError() #", "def source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self,", "else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls in", "if query is None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def", "def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set = set", "None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls", "for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls", "data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise", "data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def", "query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define bindings in", "def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type,", "delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define bindings in subclass def", "import Store class Pype(object): @property def set(self): raise NotImplementedError() @property def source(self): raise", "invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r", "in subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def", "stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source action invocation", "data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define bindings in subclass def save_model(self,", "save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise", "query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError()", "register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] =", "results): return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def __init__(self, set, store):", "self._store = store # Actions def save(self, data_type): return self._store_method('save', data_type) def update(self,", "isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model): method += \"_model\" else: raise", "= cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] =", "retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results])", "if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model): method += \"_model\" else:", "# Action invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method +=", "method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if query is None", "elif isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if", "cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model]", "from model import Model from source import Source from store import Store class", "data_type, query=None): if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model): method +=", "delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation", "Source action invocation def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r)", "def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set,", "import Model from source import Source from store import Store class Pype(object): @property", "from store import Store class Pype(object): @property def set(self): raise NotImplementedError() @property def", "store): self._set = set self._store = store # Actions def save(self, data_type): return", "set self._source = source # Actions def one(self, query_model): raise NotImplementedError() def latest(self,", "delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation def _store_method(self, method, data_type, query=None):", "def register_pypes(*pype_classes): for cls in pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set]", "NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def", "data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None):", "NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError() # Action invocation def _store_method(self, method,", "def stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source action", "\"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if query is None else {'query_model':", "return self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self,", "in results]) class StorePype(Pype): def __init__(self, set, store): self._set = set self._store =", "raise InvalidPypeDataType(data_type) kwargs = {} if query is None else {'query_model': query} getattr(self,", "= {} if query is None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return", "cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and", "Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set]", "def __init__(self, set, source): self._set = set self._source = source # Actions def", "# Actions def save(self, data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None): return", "source(self): raise NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set,", "query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls in pype_classes: if", "import Source from store import Store class Pype(object): @property def set(self): raise NotImplementedError()", "source # Actions def one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError()", "data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model):", "= cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] =", "def set(self): raise NotImplementedError() @property def source(self): raise NotImplementedError() @property def store(self): raise", "= set self._source = source # Actions def one(self, query_model): raise NotImplementedError() def", "save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model):", "pype_classes: if hasattr(cls,'__bases__') and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls", "query=None): if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model): method += \"_model\"", "update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save',", "self._source = source # Actions def one(self, query_model): raise NotImplementedError() def latest(self, query_model):", "def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self,", "query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError()", "def save(self, data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type,", "NotImplementedError() # Action invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method", "def update_set(self, data_set, query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self,", "from set import Set from model import Model from source import Source from", "@property def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set =", "model import Model from source import Source from store import Store class Pype(object):", "Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if query is", "# Define bindings in subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set):", "= set self._store = store # Actions def save(self, data_type): return self._store_method('save', data_type)", "def retrieve_model(self, result): return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in", "+= \"_set\" elif isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs =", "else: raise InvalidPypeDataType(data_type) kwargs = {} if query is None else {'query_model': query}", "Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype", "= source # Actions def one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise", "return self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype):", "data_set, query_model): raise NotImplementedError() # Action invocation def _store_method(self, method, data_type, query=None): if", "data_type, query_model) def delete(self, data_type, query_model=None): return self._store_method('save', data_type, query_model) # Define bindings", "NotImplementedError() @property def store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set", "raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def", "query_model): raise NotImplementedError() # Action invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type,", "save(self, data_type): return self._store_method('save', data_type) def update(self, data_type, query_model=None): return self._store_method('update', data_type, query_model)", "store(self): raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set = set self._source", "{} if query is None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set", "source): self._set = set self._source = source # Actions def one(self, query_model): raise", "query_model) # Define bindings in subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self,", "Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif", "NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise NotImplementedError() def", "StorePype(Pype): def __init__(self, set, store): self._set = set self._store = store # Actions", "__init__(self, set, source): self._set = set self._source = source # Actions def one(self,", "Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model]", "subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self,", "self.set.model(**result) def retrieve_set(self, results): return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def", "raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise NotImplementedError()", "\"_set\" elif isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {}", "def one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self, query_model):", "NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source", "query_model): raise NotImplementedError() def delete_model(self, data_model): raise NotImplementedError() def delete_set(self, data_set, query_model): raise", "elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__: Source.__pypes__.setdefault(cls.source,{})[cls.set] = cls Source.__pypes__.setdefault(cls.source,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.source]", "query is None else {'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes):", "= store # Actions def save(self, data_type): return self._store_method('save', data_type) def update(self, data_type,", "return self.set(*[self.retrieve_model(r) for r in results]) class StorePype(Pype): def __init__(self, set, store): self._set", "latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise", "cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls Model.__pypes__.setdefault(cls.set.model,{})[cls.store] = cls elif hasattr(cls,'__bases__') and SourcePype in cls.__bases__:", "and StorePype in cls.__bases__: Store.__pypes__.setdefault(cls.store,{})[cls.set] = cls Store.__pypes__.setdefault(cls.store,{})[cls.set.model] = cls Set.__pypes__.setdefault(cls.set,{})[cls.store] = cls", "for r in results]) class StorePype(Pype): def __init__(self, set, store): self._set = set", "def search(self, query_model): raise NotImplementedError() def stream(self, query_model): raise NotImplementedError() def all(self, query_model):", "query_model): raise NotImplementedError() # Source action invocation def retrieve_model(self, result): return self.set.model(**result) def", "set self._store = store # Actions def save(self, data_type): return self._store_method('save', data_type) def", "data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self, data_set, query_model): raise", "bindings in subclass def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError()", "def save_model(self, data_model): raise NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model):", "_store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method += \"_set\" elif isinstance(data_type, Model):", "import Set from model import Model from source import Source from store import", "invocation def _store_method(self, method, data_type, query=None): if isinstance(data_type, Set): method += \"_set\" elif", "raise NotImplementedError() class SourcePype(Pype): def __init__(self, set, source): self._set = set self._source =", "NotImplementedError() def all(self, query_model): raise NotImplementedError() # Source action invocation def retrieve_model(self, result):", "one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def search(self, query_model): raise", "NotImplementedError() def save_set(self, data_set): raise NotImplementedError() def update_model(self, data_model): raise NotImplementedError() def update_set(self,", "isinstance(data_type, Model): method += \"_model\" else: raise InvalidPypeDataType(data_type) kwargs = {} if query", "{'query_model': query} getattr(self, method)(data_type, **kwargs) return self.set def register_pypes(*pype_classes): for cls in pype_classes:", "# Actions def one(self, query_model): raise NotImplementedError() def latest(self, query_model): raise NotImplementedError() def" ]
[ "choose from, # including web pages, email senders, and IRC bots. from buildbot.status.mail", "= 'xdd', branch = 'testing') ####### BUILDERS # The 'builders' list defines the", "\"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\"))", "# c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) #", "2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so that", "GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master',", "# # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py", "to react to incoming changes. In this # case, just kick off a", "config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project", "# only take place on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from", "them. Note that any particular build will # only take place on one", "import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() # Check out the source", "STATUS TARGETS # 'status' is a list of Status Targets. The results of", "Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available", "# c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) #", "urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot mail message and", "place on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git", "builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status'", "# The buildbot settings for XDD. We assume the following build slaves are", "# # This uses the BuildmasterConfig object referenced in master.cfg def loadConfig(config): #######", "\"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "factory to each of the available builders described in the master.cfg from buildbot.config", "setting tells the buildmaster how it should find out # about source code", "to enable these tests, add the # following lines to the bottom of", "# Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) #", "Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||',", "import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version of this", "Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() # Check", "including web pages, email senders, and IRC bots. from buildbot.status.mail import MailNotifier xddMN", "config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which", "loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells the buildmaster how it should", "= [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\",", "env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory,", "# config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd'))", "slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"],", "variety to choose from, # including web pages, email senders, and IRC bots.", "object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells", "build # Configure the nightly testing so that every test lives in the", "body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body += \"Build Result:", "(build.getSlavename(), name) body += \"Build Result: %s\\n\" % Results[results] body += \"Build Status:", "config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\",", "from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand,", "# # Generate the BuildSetSummary mail format for XDD's nightly build # and", "are # defined in the master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\",", "repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd',", "configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make',", "\"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE", "Import the configuration to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from", "decide how to react to incoming changes. In this # case, just kick", "the BuildSetSummary mail format for XDD's nightly build # and test information #", "order to enable these tests, add the # following lines to the bottom", "Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD Acceptance Test", "buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() # Check out the", "tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return { 'subject' : subject, 'body'", "BUILDERS # The 'builders' list defines the Builders, which tell Buildbot how to", "to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import *", "buildbot/status/*.py has a variety to choose from, # including web pages, email senders,", "body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available at:", "from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner'", "BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test", "available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename()", "buildbot settings for XDD. We assume the following build slaves are # defined", "xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig object referenced", "add the # following lines to the bottom of the default master.cfg #", "the buildmaster how it should find out # about source code changes. Here", "import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']},", "- --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig object referenced in", "just kick off a 'runtests' build # Configure the nightly testing so that", "test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code", "\"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},", "build will # only take place on one slave. from buildbot.process.factory import BuildFactory,", "build will be # pushed to these targets. buildbot/status/*.py has a variety to", "build # and test information # from buildbot.status.builder import Results from buildbot.status.results import", "category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd'))", "import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter =", "Compile, Test xdd_factory = BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master'))", "is a list of Status Targets. The results of each build will be", "we point to the buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from", "slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import", "buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail format for XDD's nightly", "pages, email senders, and IRC bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\",", "def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells the buildmaster how it", "the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd'))", "config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) #", "defines the Builders, which tell Buildbot how to perform a build: # what", "XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c)", "perform a build: # what steps, and which slaves can execute them. Note", "buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"],", "from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name, build,", "'status' is a list of Status Targets. The results of each build will", "'-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add the XDD Build", "Here we point to the buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller", "settings for XDD. We assume the following build slaves are # defined in", "and return a tuple of the subject, message text, and mail type.\"\"\" #", "Generate the BuildSetSummary mail format for XDD's nightly build # and test information", "\"\"\"Generate a buildbot mail message and return a tuple of the subject, message", "Acceptance Test -- FAILURE\" # Construct the mail body body = \"\" body", "body += \"--\\n\\n\" return { 'subject' : subject, 'body' : body, 'type' :", "this # case, just kick off a 'runtests' build # Configure the nightly", "# and test information # from buildbot.status.builder import Results from buildbot.status.results import FAILURE,", "results != SUCCESS: body += \"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\"", "they live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) #", "-- XDD Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD", "+= \"--\\n\\n\" return { 'subject' : subject, 'body' : body, 'type' : 'plain'", "the mail subject subject = \"\" if results == SUCCESS: subject = \"[Buildbot]", "--prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses", "buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # #", "# To retrieve the latest version of this file, run the following command:", "this file, run the following command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git", "and IRC bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True,", "seperately so that they live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler #", "from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory =", "make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"],", "archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # #", "and test information # from buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS,", "builders described in the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory,", "Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(),", "Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) #", "project = 'xdd', branch = 'testing') ####### BUILDERS # The 'builders' list defines", "c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) #", "following build slaves are # defined in the master.cfg: # # c['slaves'] =", "react to incoming changes. In this # case, just kick off a 'runtests'", "bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN)", "from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() # Check out", "# Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make',", "'xdd', branch = 'testing') ####### BUILDERS # The 'builders' list defines the Builders,", "one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell", "build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute", "in master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells the buildmaster", "assume the following build slaves are # defined in the master.cfg: # #", "= ChangeFilter( project = 'xdd', branch = 'testing') ####### BUILDERS # The 'builders'", "category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the", "= BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the", "name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform", "XDD Acceptance Test -- FAILURE\" # Construct the mail body body = \"\"", "Host: %s (%s)\\n\" % (build.getSlavename(), name) body += \"Build Result: %s\\n\" % Results[results]", "+= \"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return { 'subject' :", "to perform a build: # what steps, and which slaves can execute them.", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory,", "slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) #######", "SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\",", "'check'], name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform", "check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill',", "Build: %s\\n\" % build.getSlavename() if results != SUCCESS: body += \"Failed tests: %s\\n\"", "to incoming changes. In this # case, just kick off a 'runtests' build", "out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\"))", "SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\" #", "+= \"Build Result: %s\\n\" % Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build)", "# defined in the master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\"))", "a list of Status Targets. The results of each build will be #", "'change_source' setting tells the buildmaster how it should find out # about source", "ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git',", "# config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers,", "find out # about source code changes. Here we point to the buildbot", "maxTime=60)) # Add the XDD Build factory to each of the available builders", "'<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch =", "buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure,", "Test xdd_factory = BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) #", "FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate", "+= \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build:", "Schedulers, which decide how to react to incoming changes. In this # case,", "= '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch", "% build.getText() body += \"--\\n\\n\" return { 'subject' : subject, 'body' : body,", "of the default master.cfg # ####### Import the configuration to build/test XDD #", "slaves are # defined in the master.cfg: # # c['slaves'] = [] #", "point to the buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter", "The results of each build will be # pushed to these targets. buildbot/status/*.py", "if results != SUCCESS: body += \"Failed tests: %s\\n\" % build.getText() body +=", "\"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "body += \"Build Result: %s\\n\" % Results[results] body += \"Build Status: %s\\n\" %", "Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" %", "We assume the following build slaves are # defined in the master.cfg: #", "xdd_factory = BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate", "the bottom of the default master.cfg # ####### Import the configuration to build/test", "git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # #", "so that every test lives in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler", "buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour", "import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory,", "xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) #", "in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"]))", "version of this file, run the following command: # # git archive --format=tar", "name, build, results, master_status): \"\"\"Generate a buildbot mail message and return a tuple", "slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which decide", "FAILURE\" # Construct the mail body body = \"\" body += \"Build Host:", "targets. buildbot/status/*.py has a variety to choose from, # including web pages, email", "these tests, add the # following lines to the bottom of the default", "command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2", "slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"],", "Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install", "'||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add the XDD Build factory to", "from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd'))", "Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'],", "Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2,", "buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\",", "#body += \"Flagged Build: %s\\n\" % build.getSlavename() if results != SUCCESS: body +=", "test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'],", "# git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py #", "buildmaster how it should find out # about source code changes. Here we", "env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS #", "import FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name, build, results, master_status):", "configuration to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import", "Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'],", "how to perform a build: # what steps, and which slaves can execute", "import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure, Compile,", "the BuildmasterConfig object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source'", "which decide how to react to incoming changes. In this # case, just", "env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "nightly testing so that every test lives in the same buildset from buildbot.schedulers.basic", "\"Build Result: %s\\n\" % Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body", "#!/usr/bin/python # # The buildbot settings for XDD. We assume the following build", "MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the", "% build.getSlavename() if results != SUCCESS: body += \"Failed tests: %s\\n\" % build.getText()", "subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\" else: subject =", "subject = \"\" if results == SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD", "from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) #", "each of the available builders described in the master.cfg from buildbot.config import BuilderConfig", "which tell Buildbot how to perform a build: # what steps, and which", "buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version of", "xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'],", "email senders, and IRC bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'],", "% Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs", "buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\",", "changes. Here we point to the buildbot clone of pyflakes. from buildbot.changes.gitpoller import", "and which slaves can execute them. Note that any particular build will #", "%s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:')", "xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot mail message and return a", "CHANGESOURCES # the 'change_source' setting tells the buildmaster how it should find out", "the mail body body = \"\" body += \"Build Host: %s (%s)\\n\" %", "# # To retrieve the latest version of this file, run the following", "import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"]))", "Construct the mail body body = \"\" body += \"Build Host: %s (%s)\\n\"", "# Add the XDD Build factory to each of the available builders described", "\"banana\")) # # In order to enable these tests, add the # following", "a variety to choose from, # including web pages, email senders, and IRC", "pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch = 'testing') #######", "% master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body", "referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells the", "['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each", "off a 'runtests' build # Configure the nightly testing so that every test", "list defines the Builders, which tell Buildbot how to perform a build: #", "Buildbot how to perform a build: # what steps, and which slaves can", "from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"],", "# # The buildbot settings for XDD. We assume the following build slaves", "particular build will # only take place on one slave. from buildbot.process.factory import", "of this file, run the following command: # # git archive --format=tar --prefix=xdd/", "buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\",", "%s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename() if results", "buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory()", "'echo \"\"'], name='process cleanup', maxTime=60)) # Add the XDD Build factory to each", "build, results, master_status): \"\"\"Generate a buildbot mail message and return a tuple of", "else: subject = \"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\" # Construct", "# from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest", "the nightly testing so that every test lives in the same buildset from", "# c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\"))", "# case, just kick off a 'runtests' build # Configure the nightly testing", "text, and mail type.\"\"\" # Construct the mail subject subject = \"\" if", "# Configure each force build seperately so that they live in differing buildsets", "# This uses the BuildmasterConfig object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES", "master_status): \"\"\"Generate a buildbot mail message and return a tuple of the subject,", "results == SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\"", "will # only take place on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf", "name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup", "the latest version of this file, run the following command: # # git", "This uses the BuildmasterConfig object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES #", "\"\"'], name='process cleanup', maxTime=60)) # Add the XDD Build factory to each of", "BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "SCHEDULERS # Configure the Schedulers, which decide how to react to incoming changes.", "body += \"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return { 'subject'", "= \"\" body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body +=", "workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch = 'testing')", "% (build.getSlavename(), name) body += \"Build Result: %s\\n\" % Results[results] body += \"Build", "build.getSlavename() if results != SUCCESS: body += \"Failed tests: %s\\n\" % build.getText() body", "file, run the following command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master", "= \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3)", "# Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd',", "so that they live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\",", "def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot mail message and return", "\"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return { 'subject' : subject,", "which slaves can execute them. Note that any particular build will # only", "# config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"]))", "master.cfg # ####### Import the configuration to build/test XDD # import buildbot_master_xdd #", "of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl", "name='process cleanup', maxTime=60)) # Add the XDD Build factory to each of the", "# Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) #", "--format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This", "####### CHANGESOURCES # the 'change_source' setting tells the buildmaster how it should find", "\"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In", "--strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig object referenced in master.cfg", "master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body +=", "xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add the XDD", "BuildSetSummary mail format for XDD's nightly build # and test information # from", "mail message and return a tuple of the subject, message text, and mail", "the XDD Build factory to each of the available builders described in the", "subject = \"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\" # Construct the", "mail body body = \"\" body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(),", "tests, add the # following lines to the bottom of the default master.cfg", "\"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd)", "# Configure the nightly testing so that every test lives in the same", "\"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\" # Construct the mail body", "project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch = 'testing') ####### BUILDERS #", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"],", "master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) #", "= 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so that they live", "Note that any particular build will # only take place on one slave.", "categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail format for XDD's", "tells the buildmaster how it should find out # about source code changes.", "!= SUCCESS: body += \"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return", "buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append(", "how to react to incoming changes. In this # case, just kick off", "# # In order to enable these tests, add the # following lines", "config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) #", "steps, and which slaves can execute them. Note that any particular build will", "of Status Targets. The results of each build will be # pushed to", "branch = 'testing') ####### BUILDERS # The 'builders' list defines the Builders, which", "install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make", "branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute =", "latest version of this file, run the following command: # # git archive", "messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail format for XDD's nightly build", "results of each build will be # pushed to these targets. buildbot/status/*.py has", "builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a list of", "from buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib", "# c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order", "any particular build will # only take place on one slave. from buildbot.process.factory", "bottom of the default master.cfg # ####### Import the configuration to build/test XDD", "XDD Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD Acceptance", "Construct the mail subject subject = \"\" if results == SUCCESS: subject =", "--remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the", "'runtests' build # Configure the nightly testing so that every test lives in", "the subject, message text, and mail type.\"\"\" # Construct the mail subject subject", "at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename() if", "env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which decide how to", "slaves can execute them. Note that any particular build will # only take", "= MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail", "####### SCHEDULERS # Configure the Schedulers, which decide how to react to incoming", "config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS #", "slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\",", "c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\",", "testing so that every test lives in the same buildset from buildbot.schedulers.basic import", "buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master',", "has a variety to choose from, # including web pages, email senders, and", "config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\",", "message and return a tuple of the subject, message text, and mail type.\"\"\"", "= 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so", "to the buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import", "the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make", "in the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},", "in the master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\",", "ChangeFilter( project = 'xdd', branch = 'testing') ####### BUILDERS # The 'builders' list", "SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a", "mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code", "= \"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot]", "buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib def", "Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name,", "To retrieve the latest version of this file, run the following command: #", "only take place on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source", "what steps, and which slaves can execute them. Note that any particular build", "\"Flagged Build: %s\\n\" % build.getSlavename() if results != SUCCESS: body += \"Failed tests:", "config['status'].append(xddMN) # # Generate the BuildSetSummary mail format for XDD's nightly build #", "that any particular build will # only take place on one slave. from", "from, # including web pages, email senders, and IRC bots. from buildbot.status.mail import", "body body = \"\" body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name)", "c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # #", "the following build slaves are # defined in the master.cfg: # # c['slaves']", "clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller(", "the 'change_source' setting tells the buildmaster how it should find out # about", "can execute them. Note that any particular build will # only take place", "lives in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly", "= \"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\" # Construct the mail", "execute them. Note that any particular build will # only take place on", "WARNINGS, Results import urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot", "Configure the Schedulers, which decide how to react to incoming changes. In this", "= 'testing') ####### BUILDERS # The 'builders' list defines the Builders, which tell", "env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory,", "mail format for XDD's nightly build # and test information # from buildbot.status.builder", "maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f',", "-- SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD Acceptance Test -- FAILURE\"", "category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},", "defined in the master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) #", "config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a list of Status Targets.", "%s\\n\" % build.getText() body += \"--\\n\\n\" return { 'subject' : subject, 'body' :", "# c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable these tests, add the", "source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile", "should find out # about source code changes. Here we point to the", "kick off a 'runtests' build # Configure the nightly testing so that every", "the master.cfg: # # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\"))", "these targets. buildbot/status/*.py has a variety to choose from, # including web pages,", "'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add the XDD Build factory", "ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter(", "In this # case, just kick off a 'runtests' build # Configure the", "message text, and mail type.\"\"\" # Construct the mail subject subject = \"\"", "In order to enable these tests, add the # following lines to the", "the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the", "the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform", "category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},", "the # following lines to the bottom of the default master.cfg # #######", "enable these tests, add the # following lines to the bottom of the", "import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour =", "xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the", "of the subject, message text, and mail type.\"\"\" # Construct the mail subject", "\"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\"))", "Targets. The results of each build will be # pushed to these targets.", "for XDD's nightly build # and test information # from buildbot.status.builder import Results", "pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl =", "will be # pushed to these targets. buildbot/status/*.py has a variety to choose", "Results import urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot mail", "# config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a list of Status", "pushed to these targets. buildbot/status/*.py has a variety to choose from, # including", "XDD's nightly build # and test information # from buildbot.status.builder import Results from", "type.\"\"\" # Construct the mail subject subject = \"\" if results == SUCCESS:", "Add the XDD Build factory to each of the available builders described in", "cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add the", "source code changes. Here we point to the buildbot clone of pyflakes. from", "how it should find out # about source code changes. Here we point", "lines to the bottom of the default master.cfg # ####### Import the configuration", "to the bottom of the default master.cfg # ####### Import the configuration to", "code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make", "config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a list", "# # c['slaves'] = [] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\",", "env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "described in the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\":", "build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import * #", "####### Import the configuration to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) #", "GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter = ChangeFilter( project =", "xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check", "the default master.cfg # ####### Import the configuration to build/test XDD # import", "# about source code changes. Here we point to the buildbot clone of", "name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make", "xdd_filter = ChangeFilter( project = 'xdd', branch = 'testing') ####### BUILDERS # The", "mail subject subject = \"\" if results == SUCCESS: subject = \"[Buildbot] SUCCESS", "web pages, email senders, and IRC bots. from buildbot.status.mail import MailNotifier xddMN =", "the available builders described in the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\",", "<reponame>eunsungc/gt6-RAMSES_8_5 #!/usr/bin/python # # The buildbot settings for XDD. We assume the following", "The buildbot settings for XDD. We assume the following build slaves are #", "Configure the nightly testing so that every test lives in the same buildset", "hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately", "builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a", "build seperately so that they live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler", "import Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory = BuildFactory() #", "live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\",", "the following command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf", "c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable these tests, add the #", "that every test lives in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from", "buildbot mail message and return a tuple of the subject, message text, and", "urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename() if results != SUCCESS:", "% urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename() if results !=", "MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail format", "master |tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig", "buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch = \"master\", properties={'owner' :", "# config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"]))", "# 'status' is a list of Status Targets. The results of each build", "master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting tells the buildmaster how", "# buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version of this file, run", "\"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which decide how to react", "to these targets. buildbot/status/*.py has a variety to choose from, # including web", "\"--\\n\\n\" return { 'subject' : subject, 'body' : body, 'type' : 'plain' }", "buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To", "# # # This uses the BuildmasterConfig object referenced in master.cfg def loadConfig(config):", "check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600))", "test information # from buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS,", "buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version of this file, run the", "Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60)) # Add", "\"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body += \"Build Result: %s\\n\" %", "# c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable these", "config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd'))", "and mail type.\"\"\" # Construct the mail subject subject = \"\" if results", "# c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) #", "\"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable", "xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process", "%s\\n\" % Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build", "each build will be # pushed to these targets. buildbot/status/*.py has a variety", "Builders, which tell Buildbot how to perform a build: # what steps, and", "take place on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import", "from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\",", "c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to", "+= \"Flagged Build: %s\\n\" % build.getSlavename() if results != SUCCESS: body += \"Failed", "code changes. Here we point to the buildbot clone of pyflakes. from buildbot.changes.gitpoller", "# from buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import", "config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so that they live in differing", "senders, and IRC bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd',", "name) body += \"Build Result: %s\\n\" % Results[results] body += \"Build Status: %s\\n\"", "a build: # what steps, and which slaves can execute them. Note that", "# reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve", "XDD Build factory to each of the available builders described in the master.cfg", "SUCCESS -- XDD Acceptance Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE --", "\"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable these tests, add", "# config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd'))", "slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\",", "== SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\" else:", "Test -- SUCCESS\" else: subject = \"[Buildbot] FAILURE -- XDD Acceptance Test --", "the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch", "if results == SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test --", "builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS", "extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary mail format for", "Result: %s\\n\" % Results[results] body += \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body +=", "# the 'change_source' setting tells the buildmaster how it should find out #", "code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\",", "results, master_status): \"\"\"Generate a buildbot mail message and return a tuple of the", "the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) #", "uses the BuildmasterConfig object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES # the", "#body += \"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged", "the buildbot clone of pyflakes. from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter", "# Construct the mail subject subject = \"\" if results == SUCCESS: subject", ": ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure", "# ####### Import the configuration to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd)", "IRC bots. from buildbot.status.mail import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail)", "case, just kick off a 'runtests' build # Configure the nightly testing so", "= \"\" if results == SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance", "build: # what steps, and which slaves can execute them. Note that any", "# pushed to these targets. buildbot/status/*.py has a variety to choose from, #", "'/:') #body += \"Flagged Build: %s\\n\" % build.getSlavename() if results != SUCCESS: body", "every test lives in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed", "return a tuple of the subject, message text, and mail type.\"\"\" # Construct", "builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force", "buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120, branch='master', project='xdd')) xdd_filter", "config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) #######", "for XDD. We assume the following build slaves are # defined in the", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS", "from buildbot.changes.gitpoller import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git',", "Build factory to each of the available builders described in the master.cfg from", "same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\", branch =", "list of Status Targets. The results of each build will be # pushed", "\"Build Logs available at: %s\\n\" % urllib.quote(master_status.getBuildbotURL(), '/:') #body += \"Flagged Build: %s\\n\"", "'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) #", "in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import Periodic,Nightly build_nightly_xdd=Nightly(name=\"xdd-nightly1\",", "Status Targets. The results of each build will be # pushed to these", "Configure each force build seperately so that they live in differing buildsets from", "SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test -- SUCCESS\" else: subject", "(%s)\\n\" % (build.getSlavename(), name) body += \"Build Result: %s\\n\" % Results[results] body +=", "category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which decide how to react to", "tell Buildbot how to perform a build: # what steps, and which slaves", "-- XDD Acceptance Test -- FAILURE\" # Construct the mail body body =", "# Construct the mail body body = \"\" body += \"Build Host: %s", "[] # c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\"))", "The 'builders' list defines the Builders, which tell Buildbot how to perform a", "the Builders, which tell Buildbot how to perform a build: # what steps,", "information # from buildbot.status.builder import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results", "about source code changes. Here we point to the buildbot clone of pyflakes.", "changes. In this # case, just kick off a 'runtests' build # Configure", "format for XDD's nightly build # and test information # from buildbot.status.builder import", "following command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar xf -", "-- FAILURE\" # Construct the mail body body = \"\" body += \"Build", "Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make test xdd_factory.addStep(Test(description=[\"make", "default master.cfg # ####### Import the configuration to build/test XDD # import buildbot_master_xdd", "# The 'builders' list defines the Builders, which tell Buildbot how to perform", "subject, message text, and mail type.\"\"\" # Construct the mail subject subject =", "each force build seperately so that they live in differing buildsets from buildbot.schedulers.forcesched", "make test xdd_factory.addStep(Test(description=[\"make test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo", "master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) #", "config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-x86_64\", slavenames=[\"pod9\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) #", "config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is", "# Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"])) # Install the code xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\"))", "a buildbot mail message and return a tuple of the subject, message text,", "+= \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body += \"Build Result: %s\\n\"", "c['slaves'].append(BuildSlave(\"spry02\", \"banana\")) # c['slaves'].append(BuildSlave(\"natureboy\", \"banana\")) # # In order to enable these tests,", "that they live in differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"]))", "\"\" body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body += \"Build", "# import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) #", "run the following command: # # git archive --format=tar --prefix=xdd/ --remote=/ccs/proj/csc040/var/git/xdd.git master |tar", "import Results from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode,", "Configure, Compile, Test xdd_factory = BuildFactory() # Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy',", "to choose from, # including web pages, email senders, and IRC bots. from", "SUCCESS: body += \"Failed tests: %s\\n\" % build.getText() body += \"--\\n\\n\" return {", "\"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},", "body = \"\" body += \"Build Host: %s (%s)\\n\" % (build.getSlavename(), name) body", "the Schedulers, which decide how to react to incoming changes. In this #", "cleanup', maxTime=60)) # Add the XDD Build factory to each of the available", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"},category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory,", "builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS # 'status' is a list of Status Targets. The", "\"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure", "# Configure the Schedulers, which decide how to react to incoming changes. In", "tuple of the subject, message text, and mail type.\"\"\" # Construct the mail", "\"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\" %", "+= \"Build Status: %s\\n\" % master_status.getURLForThing(build) #body += \"Build Logs available at: %s\\n\"", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) ####### SCHEDULERS # Configure the Schedulers, which decide how", "Test -- FAILURE\" # Construct the mail body body = \"\" body +=", "builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\",", "'builders' list defines the Builders, which tell Buildbot how to perform a build:", "import MailNotifier xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate", "TARGETS # 'status' is a list of Status Targets. The results of each", "maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup', maxTime=60))", "out # about source code changes. Here we point to the buildbot clone", "import GitPoller from buildbot.changes.filter import ChangeFilter config['change_source'].append( GitPoller( repourl = '<EMAIL>:ORNL/xdd.git', workdir='gitpoller-workdir-xdd-master', pollinterval=120,", "# config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\", builderNames=[\"xdd-osx-10-8\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force7\", builderNames=[\"xdd-rhel6-ppc64\"])) ####### STATUS TARGETS", "mail type.\"\"\" # Construct the mail subject subject = \"\" if results ==", "build slaves are # defined in the master.cfg: # # c['slaves'] = []", "reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the", "following lines to the bottom of the default master.cfg # ####### Import the", "xddMN = MailNotifier(fromaddr=\"<EMAIL>\", extraRecipients=['<EMAIL>'], categories='xdd', buildSetSummary=True, messageFormatter=xddSummaryMail) config['status'].append(xddMN) # # Generate the BuildSetSummary", "|tar xf - --strip=2 xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig object", "of each build will be # pushed to these targets. buildbot/status/*.py has a", "%s\\n\" % build.getSlavename() if results != SUCCESS: body += \"Failed tests: %s\\n\" %", "GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test xdd_factory", "xdd/contrib/buildbot_master_xdd.py # # # This uses the BuildmasterConfig object referenced in master.cfg def", "'testing') ####### BUILDERS # The 'builders' list defines the Builders, which tell Buildbot", "BuildmasterConfig object referenced in master.cfg def loadConfig(config): ####### CHANGESOURCES # the 'change_source' setting", "test lives in the same buildset from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.schedulers.timed import", "FAILURE -- XDD Acceptance Test -- FAILURE\" # Construct the mail body body", "XDD. We assume the following build slaves are # defined in the master.cfg:", "branch='master')) # Generate the test configuration xdd_factory.addStep(ShellCommand(command=['./contrib/buildbot_gen_test_config.sh'], name=\"configuring\")) # Compile the code xdd_factory.addStep(Compile(description=[\"compiling\"]))", "to each of the available builders described in the master.cfg from buildbot.config import", "buildbot.status.results import FAILURE, SUCCESS, WARNINGS, Results import urllib def xddSummaryMail(mode, name, build, results,", "be # pushed to these targets. buildbot/status/*.py has a variety to choose from,", "it should find out # about source code changes. Here we point to", "of the available builders described in the master.cfg from buildbot.config import BuilderConfig #", "3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so that they live in", "force build seperately so that they live in differing buildsets from buildbot.schedulers.forcesched import", "nightly build # and test information # from buildbot.status.builder import Results from buildbot.status.results", "# config['builders'].append(BuilderConfig(name=\"xdd-sles10-x86_64\", slavenames=[\"pod10\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-sles11-x86_64\", slavenames=[\"pod11\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd'))", "import urllib def xddSummaryMail(mode, name, build, results, master_status): \"\"\"Generate a buildbot mail message", "differing buildsets from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) #", "\"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build", "a 'runtests' build # Configure the nightly testing so that every test lives", "on one slave. from buildbot.process.factory import BuildFactory, GNUAutoconf from buildbot.steps.source import Git from", "a tuple of the subject, message text, and mail type.\"\"\" # Construct the", "####### STATUS TARGETS # 'status' is a list of Status Targets. The results", "# Generate the BuildSetSummary mail format for XDD's nightly build # and test", "import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # #", "the configuration to build/test XDD # import buildbot_master_xdd # reload(buildbot_master_xdd) # from buildbot_master_xdd", "from buildbot_master_xdd import * # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version", "BuildFactory, GNUAutoconf from buildbot.steps.source import Git from buildbot.steps.shell import ShellCommand, Configure, Compile, Test", "# In order to enable these tests, add the # following lines to", "* # buildbot_master_xdd.loadConfig(config=c) # # To retrieve the latest version of this file,", "factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) config['builders'].append(BuilderConfig(name=\"xdd-osx-10-8\", slavenames=[\"natureboy\"], factory=xdd_factory, env={\"XDDTEST_TIMEOUT\": \"900\"}, category='xdd')) # config['builders'].append(BuilderConfig(name=\"xdd-rhel6-ppc64\", slavenames=[\"spry02\"],", "xdd_factory.addStep(ShellCommand(command=['make', 'install'], name=\"make install\")) # Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600))", "from buildbot.schedulers.forcesched import ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"]))", "# following lines to the bottom of the default master.cfg # ####### Import", "available builders described in the master.cfg from buildbot.config import BuilderConfig # config['builders'].append(BuilderConfig(name=\"xdd-rhel5-x86_64\", slavenames=[\"pod7\"],", "ForceScheduler # config['schedulers'].append(ForceScheduler(name=\"xdd-force1\", builderNames=[\"xdd-rhel5-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force2\", builderNames=[\"xdd-rhel6-x86_64\"])) # config['schedulers'].append(ForceScheduler(name=\"xdd-force3\", builderNames=[\"xdd-sles10-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force4\", builderNames=[\"xdd-sles11-x86_64\"])) config['schedulers'].append(ForceScheduler(name=\"xdd-force6\",", "c['slaves'].append(BuildSlave(\"pod9\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod7\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod10\", \"banana\")) # c['slaves'].append(BuildSlave(\"pod11\", \"banana\")) # c['slaves'].append(BuildSlave(\"spry02\",", "properties={'owner' : ['<EMAIL>']}, builderNames=[\"xdd-sles11-x86_64\", \"xdd-osx-10-8\"], hour = 2, minute = 3) config['schedulers'].append(build_nightly_xdd) #", "# Check out the source xdd_factory.addStep(Git(repourl='<EMAIL>:ORNL/xdd.git', mode='copy', branch='master')) # Generate the test configuration", "minute = 3) config['schedulers'].append(build_nightly_xdd) # Configure each force build seperately so that they", "incoming changes. In this # case, just kick off a 'runtests' build #", "# including web pages, email senders, and IRC bots. from buildbot.status.mail import MailNotifier", "\"\" if results == SUCCESS: subject = \"[Buildbot] SUCCESS -- XDD Acceptance Test", "%s (%s)\\n\" % (build.getSlavename(), name) body += \"Build Result: %s\\n\" % Results[results] body", "subject subject = \"\" if results == SUCCESS: subject = \"[Buildbot] SUCCESS --", "retrieve the latest version of this file, run the following command: # #", "branch='master', project='xdd')) xdd_filter = ChangeFilter( project = 'xdd', branch = 'testing') ####### BUILDERS", "# Perform make check xdd_factory.addStep(ShellCommand(command=['make', 'check'], name=\"make check\", maxTime=600)) # Perform make test", "build.getText() body += \"--\\n\\n\" return { 'subject' : subject, 'body' : body, 'type'", "# what steps, and which slaves can execute them. Note that any particular", "test\"], maxTime=600)) # Perform cleanup xdd_factory.addStep(ShellCommand(command=['pkill', '-f', 'xdd', '||', 'echo \"\"'], name='process cleanup',", "####### BUILDERS # The 'builders' list defines the Builders, which tell Buildbot how" ]
[ "xmax]\" ymin = xmin ymax = xmax yn = xn # Počet vzorkovacích", "as np import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) #", "yngrad = xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod v smere osi", "/ 2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\",", "# Import modulov import numpy as np import matplotlib.pyplot as plt from matplotlib", "-1.0 xmax = 1.0 xn = 101 # Počet vzorkovacích bodov funkcie \"f\"", "* y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54))", "osi \"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax,", "rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0 xmax = 1.0 xn =", "::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin, ymax, 6)) fig.colorbar(im) plt.show()", "2.0 * np.cos(2.0 * x) fy = -2.0 * np.sin(2.0 * y) #", "= np.sin(2.0 * x) + np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa", "funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený bude každý", "= np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f = np.sin(2.0", "Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad = 10 #", "cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\")", "intervale \"[xmin, xmax]\" ymin = xmin ymax = xmax yn = xn #", "Výpočet funkcie f = np.sin(2.0 * x) + np.cos(2.0 * y) # Výpočet", "fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin, ymax, 6)) fig.colorbar(im) plt.show() fig.savefig(\"../latex/fig-f-gradf.pdf\")", "v smere osi \"x\" yngrad = xngrad # Zobrazený bude každý \"yngrad\" vzorkovací", "f = np.sin(2.0 * x) + np.cos(2.0 * y) # Výpočet derivácií \"f\"", "ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad,", "-2.0 * np.sin(2.0 * y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54,", "extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad,", "xn = 101 # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\"", "Zobrazený bude každý \"yngrad\" vzorkovací bod v smere osi \"y\" # Tvorba gridu", "bod v smere osi \"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax,", "\"yngrad\" vzorkovací bod v smere osi \"y\" # Tvorba gridu x, y =", "xmax yn = xn # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin,", "\"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn))", "Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im = ax.imshow(f,", "v smere osi \"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn),", "np.linspace(ymin, ymax, yn)) # Výpočet funkcie f = np.sin(2.0 * x) + np.cos(2.0", "každý \"yngrad\" vzorkovací bod v smere osi \"y\" # Tvorba gridu x, y", "import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť", "= xmin ymax = xmax yn = xn # Počet vzorkovacích bodov funkcie", "# Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im =", "y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im", "= xn # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad", "na intervale \"[xmin, xmax]\" ymin = xmin ymax = xmax yn = xn", "vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený", "vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin = xmin ymax =", "= 1.0 xn = 101 # Počet vzorkovacích bodov funkcie \"f\" na intervale", "intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený bude každý \"xngrad\" vzorkovací bod", "= plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin,", "xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad],", "1.0 xn = 101 # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin,", "xmax = 1.0 xn = 101 # Počet vzorkovacích bodov funkcie \"f\" na", "vzorkovací bod v smere osi \"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin,", "vzorkovací bod v smere osi \"x\" yngrad = xngrad # Zobrazený bude každý", "bude každý \"xngrad\" vzorkovací bod v smere osi \"x\" yngrad = xngrad #", "\"f\" na intervale \"[xmin, xmax]\" ymin = xmin ymax = xmax yn =", "fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin,", "vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin,", "xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f = np.sin(2.0 * x) +", "np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f = np.sin(2.0 *", "= 101 # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin", "\"[xmin, xmax]\" ymin = xmin ymax = xmax yn = xn # Počet", "np.sin(2.0 * x) + np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa \"x\"", "2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad,", "as plt from matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť xmin =", "Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx = 2.0 * np.cos(2.0 *", "ymax = xmax yn = xn # Počet vzorkovacích bodov funkcie \"f\" na", "# Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) #", "np.cos(2.0 * x) fy = -2.0 * np.sin(2.0 * y) # Vykreslenie fig,", "bod v smere osi \"x\" yngrad = xngrad # Zobrazený bude každý \"yngrad\"", "a \"y\" fx = 2.0 * np.cos(2.0 * x) fy = -2.0 *", "každý \"xngrad\" vzorkovací bod v smere osi \"x\" yngrad = xngrad # Zobrazený", "# Výpočet funkcie f = np.sin(2.0 * x) + np.cos(2.0 * y) #", "* np.sin(2.0 * y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0", "numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True)", "= 2.0 * np.cos(2.0 * x) fy = -2.0 * np.sin(2.0 * y)", "usetex=True) # Výpočtová oblasť xmin = -1.0 xmax = 1.0 xn = 101", "xngrad = 10 # Zobrazený bude každý \"xngrad\" vzorkovací bod v smere osi", "2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(),", "rc rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0 xmax = 1.0 xn", "fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin, ymax, 6)) fig.colorbar(im)", "# Zobrazený bude každý \"xngrad\" vzorkovací bod v smere osi \"x\" yngrad =", "np.sin(2.0 * y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 /", "\"xngrad\" vzorkovací bod v smere osi \"x\" yngrad = xngrad # Zobrazený bude", "::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin, ymax, 6))", "xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod v smere osi \"y\" #", "vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\")", "smere osi \"x\" yngrad = xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod", "funkcie f = np.sin(2.0 * x) + np.cos(2.0 * y) # Výpočet derivácií", "np import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) # Výpočtová", "* y) # Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx = 2.0", "ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad])", "xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f = np.sin(2.0 * x)", "funkcie \"f\" na intervale \"[xmin, xmax]\" ymin = xmin ymax = xmax yn", "plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax),", "bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin = xmin ymax = xmax", "gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie", "= 10 # Zobrazený bude každý \"xngrad\" vzorkovací bod v smere osi \"x\"", "# Zobrazený bude každý \"yngrad\" vzorkovací bod v smere osi \"y\" # Tvorba", "Import modulov import numpy as np import matplotlib.pyplot as plt from matplotlib import", "from matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0 xmax", "Zobrazený bude každý \"xngrad\" vzorkovací bod v smere osi \"x\" yngrad = xngrad", "matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0 xmax =", "Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet", "yn = xn # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\"", "fx = 2.0 * np.cos(2.0 * x) fy = -2.0 * np.sin(2.0 *", "= xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod v smere osi \"y\"", "::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin,", "Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin = xmin ymax", "y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6)) ax.set_yticks(np.linspace(ymin, ymax,", "ymax]\" xngrad = 10 # Zobrazený bude každý \"xngrad\" vzorkovací bod v smere", "\"[ymin, ymax]\" xngrad = 10 # Zobrazený bude každý \"xngrad\" vzorkovací bod v", "modulov import numpy as np import matplotlib.pyplot as plt from matplotlib import rc", "import rc rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0 xmax = 1.0", "ymin = xmin ymax = xmax yn = xn # Počet vzorkovacích bodov", "xmin = -1.0 xmax = 1.0 xn = 101 # Počet vzorkovacích bodov", "* x) + np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa \"x\" a", "\"x\" a \"y\" fx = 2.0 * np.cos(2.0 * x) fy = -2.0", "# Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx = 2.0 * np.cos(2.0", "np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx =", "matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť xmin", "# Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin = xmin", "= xmax yn = xn # Počet vzorkovacích bodov funkcie \"f\" na intervale", "= -2.0 * np.sin(2.0 * y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0 /", "xn # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad =", "y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f =", "Výpočtová oblasť xmin = -1.0 xmax = 1.0 xn = 101 # Počet", "101 # Počet vzorkovacích bodov funkcie \"f\" na intervale \"[xmin, xmax]\" ymin =", "derivácií \"f\" podľa \"x\" a \"y\" fx = 2.0 * np.cos(2.0 * x)", "ax = plt.subplots(figsize=(12.0 / 2.54, 8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax,", "osi \"x\" yngrad = xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod v", "= -1.0 xmax = 1.0 xn = 101 # Počet vzorkovacích bodov funkcie", "\"f\" podľa \"x\" a \"y\" fx = 2.0 * np.cos(2.0 * x) fy", "bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený bude", "x) fy = -2.0 * np.sin(2.0 * y) # Vykreslenie fig, ax =", "\"y\" fx = 2.0 * np.cos(2.0 * x) fy = -2.0 * np.sin(2.0", "x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax, 6))", "\"f\" na intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený bude každý \"xngrad\"", "ymax, yn)) # Výpočet funkcie f = np.sin(2.0 * x) + np.cos(2.0 *", "import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('text',", "bude každý \"yngrad\" vzorkovací bod v smere osi \"y\" # Tvorba gridu x,", "ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad],", "/ 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver(", "plt from matplotlib import rc rc('text', usetex=True) # Výpočtová oblasť xmin = -1.0", "* x) fy = -2.0 * np.sin(2.0 * y) # Vykreslenie fig, ax", "+ np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx", "ax.quiver( x[::xngrad, ::xngrad], y[::yngrad, ::yngrad], fx[::xngrad, ::xngrad], fy[::yngrad, ::yngrad]) ax.set_xlabel(\"$x$\") ax.set_ylabel(\"$y$\") ax.set_xticks(np.linspace(xmin, xmax,", "= ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad], y[::yngrad,", "10 # Zobrazený bude každý \"xngrad\" vzorkovací bod v smere osi \"x\" yngrad", "fy = -2.0 * np.sin(2.0 * y) # Vykreslenie fig, ax = plt.subplots(figsize=(12.0", "na intervale \"[ymin, ymax]\" xngrad = 10 # Zobrazený bude každý \"xngrad\" vzorkovací", "x) + np.cos(2.0 * y) # Výpočet derivácií \"f\" podľa \"x\" a \"y\"", "# Výpočtová oblasť xmin = -1.0 xmax = 1.0 xn = 101 #", "# Počet vzorkovacích bodov funkcie \"f\" na intervale \"[ymin, ymax]\" xngrad = 10", "podľa \"x\" a \"y\" fx = 2.0 * np.cos(2.0 * x) fy =", "im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max()) ax.quiver( x[::xngrad, ::xngrad],", "oblasť xmin = -1.0 xmax = 1.0 xn = 101 # Počet vzorkovacích", "smere osi \"y\" # Tvorba gridu x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin,", "* np.cos(2.0 * x) fy = -2.0 * np.sin(2.0 * y) # Vykreslenie", "x, y = np.meshgrid(np.linspace(xmin, xmax, xn), np.linspace(ymin, ymax, yn)) # Výpočet funkcie f", "yn)) # Výpočet funkcie f = np.sin(2.0 * x) + np.cos(2.0 * y)", "y) # Výpočet derivácií \"f\" podľa \"x\" a \"y\" fx = 2.0 *", "8.0 / 2.54)) im = ax.imshow(f, extent=(xmin, xmax, ymin, ymax), cmap=\"bwr\", vmin=-np.abs(f).max(), vmax=np.abs(f).max())", "\"x\" yngrad = xngrad # Zobrazený bude každý \"yngrad\" vzorkovací bod v smere", "xmin ymax = xmax yn = xn # Počet vzorkovacích bodov funkcie \"f\"" ]
[ "solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>'", "['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab", "fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church',", "['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x in light_icons if '\\t<option>fal fa-'", "+ '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article')", "import By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15", "in blacklist items in the following format blacklist = ['far fa-reply', 'fal fa-reply',", "not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values =", "fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong',", "'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal", "icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' +", "x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception')", "in light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list", "'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal", "'\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] +", "{'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x in", "= requests.get(url) # markup = req.text # print(markup) from selenium import webdriver from", "# Please enter in blacklist items in the following format blacklist = ['far", "'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas", "# url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup = req.text #", "'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist] try: myElem = WebDriverWait(browser,", "fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church',", "fa-' + x.attrs['id'] + '</option>' for x in brand_icons if '\\t<option>fab fa-' +", "x in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in blacklist]", "webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by", "solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x in solid_icons if", "enter in blacklist items in the following format blacklist = ['far fa-reply', 'fal", "features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] +", "fa-' + x.attrs['id'] + '</option>' for x in regular_icons if '\\t<option>far fa-' +", "+ x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\",", "+ font_awesome_icon + '</option>' # Please enter in blacklist items in the following", "for x in light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in", "x.attrs['id'] + '</option>' for x in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] +", "+= '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with open('fa-icons.txt', 'w+') as", "return \"\\t<option>\" + font_awesome_icon + '</option>' # Please enter in blacklist items in", "not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values =", "'</option>' for x in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not", "fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong',", "blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-'", "as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome()", "in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab", "'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup = req.text # print(markup) from selenium", "in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list", "from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import", "icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' # Please enter in", "'\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons", "['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x in regular_icons if '\\t<option>far fa-'", "= ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x in brand_icons if '\\t<option>fab", "soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x", "fa-' + x.attrs['id'] + '</option>' for x in light_icons if '\\t<option>fal fa-' +", "soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-'", "+ x.attrs['id'] + '</option>' for x in regular_icons if '\\t<option>far fa-' + x.attrs['id']", "x in regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not in blacklist]", "# seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon", "'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist]", "soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x", "try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\",", "'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal", "'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string)", "'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x in light_icons", "+ '</option>' for x in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>'", "\"\\t<option>\" + font_awesome_icon + '</option>' # Please enter in blacklist items in the", "fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat',", "[make_icon_format_string(string) for string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup =", "brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x in brand_icons if", "blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-'", "req = requests.get(url) # markup = req.text # print(markup) from selenium import webdriver", "brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list +=", "blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with open('fa-icons.txt',", "url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup = req.text # print(markup)", "'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far", "+ x.attrs['id'] + '</option>' for x in light_icons if '\\t<option>fal fa-' + x.attrs['id']", "'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x in brand_icons", "selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC", "= ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x in light_icons if '\\t<option>fal", "x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id':", "light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list +=", "print(markup) from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions", "TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list = '<select>\\n\\t<option", "if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values)", "+ '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article')", "'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist] try: myElem", "from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds", "brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>'", "fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in", "delay = 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return", "from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay", "+= '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id']", "'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas", "selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By", "= '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' #", "webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def", "for x in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in", "solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list +=", "fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for", "# print(markup) from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import", "font_awesome_icon + '</option>' # Please enter in blacklist items in the following format", "'</option>' for x in regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not", "= 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup = req.text # print(markup) from", "icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' +", "'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas", "'\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons", "'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far", "'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal", "'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas", "fa-' + x.attrs['id'] + '</option>' for x in solid_icons if '\\t<option>fas fa-' +", "'<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' # Please", "for string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source,", "'\\t<option>far fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons", "'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x in solid_icons", "icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' +", "'</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list +=", "seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon +", "x in light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not in blacklist]", "fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons =", "make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' # Please enter in blacklist items", "requests from bs4 import BeautifulSoup from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro'", "fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard',", "fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis',", "delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values =", "+ '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article')", "fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong',", "= soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for", "fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons =", "blacklist = [make_icon_format_string(string) for string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply')))", "fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger',", "fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat',", "blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons =", "'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far", "+ '</option>' for x in light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>'", "not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>'", "x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id':", "blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas", "'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist", "selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup", "# req = requests.get(url) # markup = req.text # print(markup) from selenium import", "browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No", "value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' # Please enter", "for x in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in", "'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal", "fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat']", "req.text # print(markup) from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support", "By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 #", "WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions", "'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal", "requests.get(url) # markup = req.text # print(markup) from selenium import webdriver from selenium.webdriver.support.ui", "in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons", "from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as", "= BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' +", "fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons =", "fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square',", "+ '</option>' for x in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>'", "import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser", "'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x in regular_icons", "Please enter in blacklist items in the following format blacklist = ['far fa-reply',", "WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values", "in regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list", "'\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with open('fa-icons.txt', 'w+') as file:", "blacklist items in the following format blacklist = ['far fa-reply', 'fal fa-reply', 'fas", "'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church', 'far fa-clipboard', 'far", "'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas", "['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x in solid_icons if '\\t<option>fas fa-'", "15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" +", "expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser =", "x.attrs['id'] + '</option>' for x in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] +", "'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string", "x.attrs['id'] + '</option>' for x in regular_icons if '\\t<option>far fa-' + x.attrs['id'] +", "['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x in brand_icons if '\\t<option>fab fa-'", "import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from", "x.attrs['id'] + '</option>' for x in light_icons if '\\t<option>fal fa-' + x.attrs['id'] +", "import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list =", "'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas", "fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up',", "fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque',", "if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values)", "import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup =", "'</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values", "browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon):", "selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay =", "+ '</option>' for x in regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>'", "if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(solid_icon_values)", "'\\t<option>fab fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except", "in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal", "soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for x", "'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far", "'</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values", "fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID,", "'</option>' for x in light_icons if '\\t<option>fal fa-' + x.attrs['id'] + '</option>' not", "BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id']", "if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values)", "fa-hand-middle-finger', 'far fa-hand-middle-finger', 'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis',", "fa-church', 'fas fa-church', 'far fa-clipboard', 'far fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist =", "{'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x in", "+= '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id']", "+ x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\",", "'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas", "string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser')", "fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist] try: myElem =", "import BeautifulSoup from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req =", "regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>'", "items in the following format blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply',", "'\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] +", "+ x.attrs['id'] + '</option>' for x in brand_icons if '\\t<option>fab fa-' + x.attrs['id']", "+ x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout", "'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far", "= [make_icon_format_string(string) for string in blacklist] try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup", "blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-'", "{'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x in", "# markup = req.text # print(markup) from selenium import webdriver from selenium.webdriver.support.ui import", "light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for x in light_icons if", "fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque',", "x in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in blacklist]", "icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>'", "in blacklist] icon_list += '\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far", "+ x.attrs['id'] + '</option>' for x in solid_icons if '\\t<option>fas fa-' + x.attrs['id']", "bs4 import BeautifulSoup from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req", "= ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x in solid_icons if '\\t<option>fas", "in solid_icons if '\\t<option>fas fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list", "{'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x in", "'</option>' # Please enter in blacklist items in the following format blacklist =", "'</option>' not in blacklist] icon_list += '\\n'.join(light_icon_values) brand_icons = soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values", "myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id':", "markup = req.text # print(markup) from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait", "= ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican',", "= 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n' def make_icon_format_string(font_awesome_icon): return \"\\t<option>\"", "for x in regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not in", "+ x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\",", "from bs4 import BeautifulSoup from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' #", "def make_icon_format_string(font_awesome_icon): return \"\\t<option>\" + font_awesome_icon + '</option>' # Please enter in blacklist", "= soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>' for", "= soup.find(\"section\", {'id': 'brands'}).find_all('article') brand_icon_values = ['\\t<option>fab fa-' + x.attrs['id'] + '</option>' for", "following format blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal", "import requests from bs4 import BeautifulSoup from selenium import webdriver # url =", "x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id':", "icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with open('fa-icons.txt', 'w+')", "= req.text # print(markup) from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from", "= soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for", "from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) #", "light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id'] + '</option>'", "import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from", "not in blacklist] icon_list += '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values =", "'</option>' for x in brand_icons if '\\t<option>fab fa-' + x.attrs['id'] + '</option>' not", "= webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list = '<select>\\n\\t<option value=\"\">No icon</option>\\n'", "from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import", "except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with open('fa-icons.txt', 'w+') as file: file.write(icon_list)", "'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas", "+ '</option>' # Please enter in blacklist items in the following format blacklist", "fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque',", "in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list += '\\n</select>' with", "fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException:", "webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url) # markup = req.text", "= WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'reply'))) soup = BeautifulSoup(browser.page_source, features='html.parser') solid_icons = soup.find(\"section\", {'id': 'solid'}).find_all('article')", "fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far fa-cannabis',", "in the following format blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far", "selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException", "fa-reply', 'far fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger',", "soup.find(\"section\", {'id': 'solid'}).find_all('article') solid_icon_values = ['\\t<option>fas fa-' + x.attrs['id'] + '</option>' for x", "fa-cannabis', 'fas fa-mosque', 'far fa-mosque', 'fal fa-mosque', 'fal fa-church', 'far fa-church', 'fas fa-church',", "+= '\\n'.join(regular_icon_values) light_icons = soup.find(\"section\", {'id': 'light'}).find_all('article') light_icon_values = ['\\t<option>fal fa-' + x.attrs['id']", "+ '</option>' not in blacklist] icon_list += '\\n'.join(brand_icon_values) except TimeoutException: print('timeout exception') icon_list", "regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x in regular_icons if", "fa-democrat', 'fas fa-democrat', 'fal fa-democrat'] blacklist = [make_icon_format_string(string) for string in blacklist] try:", "BeautifulSoup from selenium import webdriver # url = 'https://fontawesome.com/cheatsheet/pro' # req = requests.get(url)", "selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\") delay = 15 # seconds icon_list", "fa-republican', 'fal fa-republican', 'fas fa-republican', 'fab fa-youtube-square', 'fas fa-angle-up', 'fas fa-hand-middle-finger', 'far fa-hand-middle-finger',", "'\\n'.join(solid_icon_values) regular_icons = soup.find(\"section\", {'id': 'regular'}).find_all('article') regular_icon_values = ['\\t<option>far fa-' + x.attrs['id'] +", "format blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican', 'fal fa-republican',", "regular_icons if '\\t<option>far fa-' + x.attrs['id'] + '</option>' not in blacklist] icon_list +=", "'fal fa-hand-middle-finger', 'fas fa-bong', 'fal fa-bong', 'far fa-bong', 'fas fa-cannabis', 'fal fa-cannabis', 'far", "= ['\\t<option>far fa-' + x.attrs['id'] + '</option>' for x in regular_icons if '\\t<option>far", "the following format blacklist = ['far fa-reply', 'fal fa-reply', 'fas fa-reply', 'far fa-republican',", "EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException browser = webdriver.Chrome() browser.get(\"https://fontawesome.com/cheatsheet/pro\")" ]
[]
[]
[ "import requests result = requests.post( \"https://asia-northeast1-mlops-331003.cloudfunctions.net/function-1\", json={\"msg\": \"Hello from cloud functions\"}, ) print(result.json())" ]
[ "users pets hosting services message payment host') system('python3 manage.py migrate') # Server system('python3", "system('python3 manage.py makemigrations users pets hosting services message payment host') system('python3 manage.py migrate')", "from os import system # Database system('python3 manage.py makemigrations users pets hosting services", "Database system('python3 manage.py makemigrations users pets hosting services message payment host') system('python3 manage.py", "pets hosting services message payment host') system('python3 manage.py migrate') # Server system('python3 manage.py", "hosting services message payment host') system('python3 manage.py migrate') # Server system('python3 manage.py runserver", "<filename>utils/start_server.py from os import system # Database system('python3 manage.py makemigrations users pets hosting", "services message payment host') system('python3 manage.py migrate') # Server system('python3 manage.py runserver localhost:8000')", "makemigrations users pets hosting services message payment host') system('python3 manage.py migrate') # Server", "import system # Database system('python3 manage.py makemigrations users pets hosting services message payment", "system # Database system('python3 manage.py makemigrations users pets hosting services message payment host')", "os import system # Database system('python3 manage.py makemigrations users pets hosting services message", "manage.py makemigrations users pets hosting services message payment host') system('python3 manage.py migrate') #", "# Database system('python3 manage.py makemigrations users pets hosting services message payment host') system('python3" ]
[ "configparser import ConfigParser config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration", "def get_config(): \"\"\" Loads the configuration file config.ini and returns a dictionary with", "keys and its values. :return: \"\"\" sections = config.sections() config_dict = {} for", "= ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration file config.ini and returns", "and returns a dictionary with keys and its values. :return: \"\"\" sections =", "= config.sections() config_dict = {} for key in sections: config_dict[key] = dict(config[key]) return", "values. :return: \"\"\" sections = config.sections() config_dict = {} for key in sections:", ":return: \"\"\" sections = config.sections() config_dict = {} for key in sections: config_dict[key]", "<reponame>GraciousGpal/Colony-Server from configparser import ConfigParser config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads", "with keys and its values. :return: \"\"\" sections = config.sections() config_dict = {}", "its values. :return: \"\"\" sections = config.sections() config_dict = {} for key in", "config.read('config.ini') def get_config(): \"\"\" Loads the configuration file config.ini and returns a dictionary", "a dictionary with keys and its values. :return: \"\"\" sections = config.sections() config_dict", "ConfigParser config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration file config.ini", "dictionary with keys and its values. :return: \"\"\" sections = config.sections() config_dict =", "import ConfigParser config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration file", "configuration file config.ini and returns a dictionary with keys and its values. :return:", "file config.ini and returns a dictionary with keys and its values. :return: \"\"\"", "from configparser import ConfigParser config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the", "and its values. :return: \"\"\" sections = config.sections() config_dict = {} for key", "the configuration file config.ini and returns a dictionary with keys and its values.", "config.ini and returns a dictionary with keys and its values. :return: \"\"\" sections", "\"\"\" Loads the configuration file config.ini and returns a dictionary with keys and", "get_config(): \"\"\" Loads the configuration file config.ini and returns a dictionary with keys", "Loads the configuration file config.ini and returns a dictionary with keys and its", "config = ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration file config.ini and", "ConfigParser() config.read('config.ini') def get_config(): \"\"\" Loads the configuration file config.ini and returns a", "\"\"\" sections = config.sections() config_dict = {} for key in sections: config_dict[key] =", "sections = config.sections() config_dict = {} for key in sections: config_dict[key] = dict(config[key])", "config.sections() config_dict = {} for key in sections: config_dict[key] = dict(config[key]) return config_dict", "returns a dictionary with keys and its values. :return: \"\"\" sections = config.sections()" ]
[ "are the same as second set of # columns in all_keypoints (apart from", "the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None, 0.7, sorted_person_keypoints ) assert", "pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting", "Check getting only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints)", "upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape ==", "threshold (and make sure it replaces values by the same values) sorted_person_keypoints2 =", "list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that", "(len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ]", "\"y1\", \"confidence1\", ] # Check that values in person_keypoints are the same as", "sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in", "== ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person", "# Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame", "6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] #", "the same as second set of # columns in all_keypoints (apart from column", "all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS )", "assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering (0 is left-most, 1", "= parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a", "values in person_keypoints are the same as second set of # columns in", "parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people are not", "where the people are not already sorted assert parser.get_person_count() == 3 # Check", "Check that values in person_keypoints are the same as second set of #", "is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test", "person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert", "getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape", "== pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check", "all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only", "values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None, 0.7, sorted_person_keypoints", "= OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people are not already", "Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts),", "] # Check that values in person_keypoints are the same as second set", "3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape", "== pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\",", "1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) ==", "upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test", "parser.COLUMN_NAMES # Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) ==", "people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts),", "= person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints = parser.get_person_keypoints(", "(0 is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] <", "set of # columns in all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:,", "make sure it replaces values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0,", "OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one", "== 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert", "type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not", ") assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering (0 is left-most,", "(apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints)", "left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] )", "test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people are", "person_keypoints are the same as second set of # columns in all_keypoints (apart", "raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser", "== (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\",", "a confidence threshold (and make sure it replaces values by the same values)", "Test person ordering (0 is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert", "person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people", "# Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape ==", "\"confidence1\", ] # Check that values in person_keypoints are the same as second", "second set of # columns in all_keypoints (apart from column names) all_keypoints_person1 =", "# Test person ordering (0 is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints)", "OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people are not already sorted", "= parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert", ") # Test handing in a confidence threshold (and make sure it replaces", "by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None, 0.7, sorted_person_keypoints )", "== [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that values", "( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering", "assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) ==", "( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose", "sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence threshold (and make sure it", "are not already sorted assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints =", "\"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that values in person_keypoints", "all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\",", "replaces values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None, 0.7,", "pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index", ") def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the", "already sorted assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert", "same as second set of # columns in all_keypoints (apart from column names)", "<reponame>alisonrclarke/raga-pose-estimation-1 import pandas as pd from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import (", "from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser():", "from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\"", "sorted assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints)", "it replaces values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None,", "type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES #", "choose one where the people are not already sorted assert parser.get_person_count() == 3", "handing in a confidence threshold (and make sure it replaces values by the", "names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting", "= parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == (", "parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape", "len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering (0", "ordering (0 is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0]", "(and make sure it replaces values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints(", "== parser.COLUMN_NAMES # Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints)", "parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS),", "pandas as pd from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups,", ") # choose one where the people are not already sorted assert parser.get_person_count()", "people are not already sorted assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints", "== pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in", "assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index #", "3, ) assert OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering (0 is", "is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3]", "as pd from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, )", "[ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that values in", "person ordering (0 is left-most, 1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert (", "\"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that values in person_keypoints are", "== (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people all_keypoints", "one where the people are not already sorted assert parser.get_person_count() == 3 #", "type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\",", "not already sorted assert parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1)", "import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) #", "assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES", "column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check", "upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert", ") assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert", "assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS", "( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence threshold (and", "of # columns in all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6]", "from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) #", "in all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns", "parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence", "sure it replaces values by the same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1],", "= all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper", "3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0,", "parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns)", "import pandas as pd from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts,", "all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert", "assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [", "raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" )", "pd from raga_pose_estimation.openpose_json_parser import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def", "Test handing in a confidence threshold (and make sure it replaces values by", "that values in person_keypoints are the same as second set of # columns", "# columns in all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns", "# choose one where the people are not already sorted assert parser.get_person_count() ==", "assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1])", "OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser(", "3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints", "not in upper_keypoints.index # Test person ordering (0 is left-most, 1 is next)", "as second set of # columns in all_keypoints (apart from column names) all_keypoints_person1", "assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\",", "in a confidence threshold (and make sure it replaces values by the same", "(len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people all_keypoints =", "next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing", "list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert", "# Test handing in a confidence threshold (and make sure it replaces values", "def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people", "the people are not already sorted assert parser.get_person_count() == 3 # Check get_person_keypoints", "parser.get_person_count() == 3 # Check get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame", "multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape ==", "assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, ) assert OpenPoseParts.L_ANKLE", "assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check", "sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence threshold (and make", "same values) sorted_person_keypoints2 = parser.get_multiple_keypoints( [0, 1], None, 0.7, sorted_person_keypoints ) assert sorted_person_keypoints.equals(sorted_person_keypoints2)", "OpenPoseParts.L_ANKLE not in upper_keypoints.index # Test person ordering (0 is left-most, 1 is", "1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3,", "\"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where the people are not already sorted assert", "person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints = parser.get_person_keypoints( 1,", "getting only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) ==", "pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6) assert list(all_keypoints.columns) == [ \"x0\", \"y0\", \"confidence0\",", "Check getting multiple people all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert", "\"x1\", \"y1\", \"confidence1\", ] # Check that values in person_keypoints are the same", "# Check that values in person_keypoints are the same as second set of", "parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) ==", "1 is next) sorted_person_keypoints = parser.sort_persons_by_x_position(all_keypoints) assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) #", "all_keypoints = parser.get_multiple_keypoints([0, 1]) assert type(all_keypoints) == pd.DataFrame assert all_keypoints.shape == (len(OpenPoseParts), 6)", "< sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence threshold (and make sure", "assert ( sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[0] < sorted_person_keypoints.loc[OpenPoseParts.MID_HIP.value].iloc[3] ) # Test handing in a confidence threshold", "= parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns)", "only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame", "import OpenPoseJsonParser from raga_pose_estimation.openpose_parts import ( OpenPoseParts, OpenPosePartGroups, ) def test_parser(): parser =", "confidence threshold (and make sure it replaces values by the same values) sorted_person_keypoints2", "in upper_keypoints.index # Test person ordering (0 is left-most, 1 is next) sorted_person_keypoints", "get_person_keypoints person_keypoints = parser.get_person_keypoints(1) assert type(person_keypoints) == pd.DataFrame assert person_keypoints.shape == (len(OpenPoseParts), 3)", "in person_keypoints are the same as second set of # columns in all_keypoints", "\"confidence0\", \"x1\", \"y1\", \"confidence1\", ] # Check that values in person_keypoints are the", "all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts upper_keypoints =", "OpenPosePartGroups.UPPER_BODY_PARTS ) assert type(upper_keypoints) == pd.DataFrame assert upper_keypoints.shape == ( len(OpenPosePartGroups.UPPER_BODY_PARTS), 3, )", "all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns = person_keypoints.columns assert all_keypoints_person1.equals(person_keypoints) # Check getting only upper parts", "# Check getting only upper parts upper_keypoints = parser.get_person_keypoints( 1, OpenPosePartGroups.UPPER_BODY_PARTS ) assert", "upper_keypoints.index # Test person ordering (0 is left-most, 1 is next) sorted_person_keypoints =", "assert person_keypoints.shape == (len(OpenPoseParts), 3) assert list(person_keypoints.columns) == parser.COLUMN_NAMES # Check getting multiple", "OpenPosePartGroups, ) def test_parser(): parser = OpenPoseJsonParser( \"example_files/example_3people/output_json/video_000000000093_keypoints.json\" ) # choose one where", "columns in all_keypoints (apart from column names) all_keypoints_person1 = all_keypoints.iloc[:, 3:6] all_keypoints_person1.columns =" ]
[ "= True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN'", "= socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips] # Heroku", "= 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql',", "'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files", "Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID =", "# ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')", "[ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL =", "== 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS =", "'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC'", "'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [", "STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 #", "False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static", "# https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =", "'HOST': 'db', 'PORT': 5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH", "emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT", "os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1))", "SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY", "= 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS =", "Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django", "'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } }", "whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF", "= 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE", "'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS =", "}, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' #", "= True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/", "{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {", "# Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS =", "#'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',", "Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if USE_S3: # AWS", "validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',", "'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [", "ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True #", "'/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home'", "] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': {", "USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) #", "'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE =", "= os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE =", "{ 'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching", "X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD", "= 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER =", "= int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',", "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>',", "= False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third", "True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True", "# caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware',", "MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST =", "= f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE =", "AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE", "'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = {", "os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY')", "'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig',", "#production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT =", "'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #", "ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL", "} # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS", "{ 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db',", "STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\",", "} } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',", "EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else:", "] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')],", "AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/'", "= os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD =", "# whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ]", "CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe", "'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE =", "5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':", "INTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips] # Heroku import dj_database_url", "# Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig',", "'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } #", "'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = (", "= '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY'", "https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True", "# CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())", "'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default'", "+ \"1\" for ip in ips] # Heroku import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500)", "ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG", "STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS", "# Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if USE_S3: #", "True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)", "'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware',", "= 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static", "EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER", "'' # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1]", "f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #", "= 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK =", "= 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend',", "= os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT ==", "'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms',", "= [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if", "django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\"", "EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD", "SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS", "= { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY')", "None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS", "EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'", "= True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, }", "'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') #", "os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')", "'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise", "SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND =", "os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if", "'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar':", "like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS =", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' #", "# \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/'", "[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },", "Static files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY =", "if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls'", "'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware',", "[ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',", "'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0))", "= '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL =", "'PORT': 5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {", "{ 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432,", "'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #", "= '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", #", "}, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default':", "'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')", "True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files", "STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX", "Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER':", "CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID", "default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic',", "= 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True", "settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL =", "MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND =", "'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS':", "if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT =", "= os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY =", "CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default':", "#'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us'", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES =", "'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS =", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' #", "# Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {", "USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL =", "SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE", "forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if USE_S3: # AWS settings", "'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, }", "True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True", "CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None,", "# Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True", "USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',", "= os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ]", "# whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader',", "True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if USE_S3:", "= Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT',", "}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization #", "'127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3", "= int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [", "X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS", "import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for", "'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching #", "LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER", "= 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE =", "'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor',", "WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':", "ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK", "# CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname,", "] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #", "storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME", "pathlib import Path # Build paths inside the project like this: BASE_DIR /", "= True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED =", "'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD =", "Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':", "\"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,", "int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME =", "True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, } #", "'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages',", "'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4'", "os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS", "= os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition", "BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost',", "# Static files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY", "MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "\"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT", "= ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED =", "'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT':", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "/ 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1']", "1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES", "JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser'", "= os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3',", "Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = ''", "int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "= 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS =", "os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'", "CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname, _,", "True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True", "('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS", "'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES", "AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN =", "socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips] # Heroku import", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {", "os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS", "# django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] +", "'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', #", "os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },", "# CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' #", "\"1\" for ip in ips] # Heroku import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)", "Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL", "TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True #", "'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ {", "}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },", "= True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/'", "SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER", "'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS", "= [ip[:-1] + \"1\" for ip in ips] # Heroku import dj_database_url db_from_env", "Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR", "https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD':", "'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT =", ") ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email'", "inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY =", "'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND", "] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',", "os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read'", "'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE", "] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N =", "= 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import", "project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS", "SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')", "s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else:", "'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS =", "# \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT =", "int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND =", "AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE", "Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY') # Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800", "'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static' STATIC_URL =", "'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local", "= f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')", "#ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True", "files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')", "}, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = {", "ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' #", "ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips] #", "os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False", "= True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF =", "caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware',", "# Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching", "ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 =", "'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', )", "'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', #", "], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES =", "else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER", "'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE =", "STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails", "'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD", "= True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage if", "{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]", "'/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST", "True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO',", "STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'", "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", #", "= True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE =", "from pathlib import Path # Build paths inside the project like this: BASE_DIR", "# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR =", "= 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE =", "USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')", "= 'bootstrap4' # Static files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID =", "# s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'", "'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching", "default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware',", "int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL =", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION =", "'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE", "import os from pathlib import Path # Build paths inside the project like", "= True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static", "'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION =", "= 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static' STATIC_URL", "'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'", "# https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL =", "= 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True,", "# AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN", "'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet',", "https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home'", "= 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION", "# emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS'))", "'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } # Password validation #", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database #", "party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig',", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party", "CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', },", "}, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth',", "SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE", "[os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')):", "'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization", "USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS,", "True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS", "True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL", "= [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL", "Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent", "AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application'", "'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT", "True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND", "whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar',", "# Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID", "ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS", "{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/", "'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ]", "all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1", "else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ #", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "# Caching # CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX =", "caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,", "= '' # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS =", "SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application", "'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND':", "= os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL =", "AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL", "f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'", "= 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ =", "DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 static settings AWS_LOCATION = 'static'", "Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE = [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware',", "AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED", "EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', #", "= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',", "os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production':", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth", "'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },", "LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ", "'<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS", "'db', 'PORT': 5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [", "CACHE_MIDDLEWARE_ALIAS = 'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar", "# https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres',", "'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True", "= 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname, _, ips", "EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>'", "= 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': {", "= os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE =", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites',", "604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname, _, ips =", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles',", "SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE", "ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS':", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise", "# caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE", "EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER =", "socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip", "paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY", "= True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER =", "the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY')", "AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE", "= ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG =", "STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]", "= True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor", "hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip in", "ACCOUNT_UNIQUE_EMAIL = True # Crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files storage", "ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED", "LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend',", "['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG',", "= [ #'django.middleware.cache.UpdateCacheMiddleware', # caching 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True", "DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) # Application definition INSTALLED_APPS =", "SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS =", "= ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow'", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',", "} # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },", "'default' # CACHE_MIDDLEWARE_SECONDS = 604800 # CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket", "SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF", "{ 'default': { 'toolbar': None, 'extraPlugins': 'codesnippet', }, } # Stripe STRIPE_TEST_PUBLISHABLE_KEY=os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY') STRIPE_TEST_SECRET_KEY=os.environ.get('STRIPE_TEST_SECRET_KEY')", "'/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database", "= False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3", "int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT'))", "'<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT", "True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True", "'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True", "= False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL =", "'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600", "'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators", "'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',", "= True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript,", "CACHE_MIDDLEWARE_KEY_PREFIX = '' # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/'", "https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {", "Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT = os.environ.get('ENVIRONMENT', default='development')", "# STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS = [os.path.join(BASE_DIR,", "= 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT", "STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,", "import Path # Build paths inside the project like this: BASE_DIR / 'subdir'.", "= 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD =", "'bootstrap4' # Static files storage if USE_S3: # AWS settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')", "'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } # Password validation", "[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],", "CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #ckEditor X_FRAME_OPTIONS = 'SAMEORIGIN' CKEDITOR_UPLOAD_PATH =", "'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True", "Third party 'crispy_forms', 'allauth', 'allauth.account', #'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig',", "DEFAULT_FROM_EMAIL = '<EMAIL>' #production if ENIVRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS =", "= int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND", "'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST': 'db', 'PORT': 5432, } } # Password", "# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },", "= int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL", "False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True", "os from pathlib import Path # Build paths inside the project like this:", "= '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'", "AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]", "default='development') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) USE_S3 = int(os.environ.get('USE_S3', default=1)) #", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL =", "= os.path.join(BASE_DIR, 'media') # emails if int(os.environ.get('EMAIL')): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST')", "= 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'extraPlugins':", "#'storages', 'ckeditor', 'ckeditor_uploader', 'debug_toolbar', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'articles.apps.ArticlesConfig', 'payments.apps.PaymentsConfig', ] MIDDLEWARE =", "# Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres',", "'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', #", "= os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = '<EMAIL>' #production", "_, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips]", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', #", "= { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>', 'HOST':", "( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False", "False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True # Crispy forms", "this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com',", "'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF = 'news_outlet.urls' TEMPLATES = [", "'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', # caching ] ROOT_URLCONF =", "AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #", "= 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_FINDERS =", "static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL", "[ip[:-1] + \"1\" for ip in ips] # Heroku import dj_database_url db_from_env =", "AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':", "'news_outlet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':", "'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':", "STATIC_URL = '/static/' # Django all-auth AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL", "BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] ENIVRONMENT =", "= True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS =", "'staticfiles') # STATICFILES_FINDERS = [ # \"django.contrib.staticfiles.finders.FileSystemFinder\", # \"django.contrib.staticfiles.finders.AppDirectoriesFinder\", # ] STATICFILES_DIRS =", "'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # whitenoise 'django.contrib.staticfiles', 'django.contrib.sites', # Third party 'crispy_forms', 'allauth', 'allauth.account',", "= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_USE_TLS = int(os.environ.get('EMAIL_USE_TLS')) EMAIL_PORT = int(os.environ.get('EMAIL_PORT')) EMAIL_HOST_USER =" ]
[ "it j for j in range(len(self.elements) - i): # len(elements) - 1 to", "Jul 22 23:53:27 2018 @author: DRB4 Task: complete Difference class - class constructor", "stores it in the maximumDifference instance variable 1 <= N <= 10 1", "again, only call it j for j in range(len(self.elements) - i): # len(elements)", "14 - Scope Created on Sun Jul 22 23:53:27 2018 @author: DRB4 Task:", "a def computeDifference(self): self.maximumDifference = 0 # Need the difference of every element", "TEST CASES # input [1 2 5] output: 4 SUCCESS # input [8", "= a def computeDifference(self): self.maximumDifference = 0 # Need the difference of every", "- 1 \"\"\" ### MY CODE ### class Difference: def __init__(self, a): self.__elements", "2 5] output: 4 SUCCESS # input [8 19 3 2 7] output:", "2 numbers in N and stores it in the maximumDifference instance variable 1", "input() a = [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference()", "<= elements[i] <= 100, where 0 <= i <= N - 1 \"\"\"", "self.__elements = a def computeDifference(self): self.maximumDifference = 0 # Need the difference of", "-*- coding: utf-8 -*- \"\"\" Hacker Rank 30 Days of Code 14 -", "to keep from double counting diff = abs(self.elements[i] - self.elements[j]) if diff >", "numbers in N and stores it in the maximumDifference instance variable 1 <=", "diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass # End of Difference", "count over i again, only call it j for j in range(len(self.elements) -", "Rank 30 Days of Code 14 - Scope Created on Sun Jul 22", "keep from double counting diff = abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference:", "in N and stores it in the maximumDifference instance variable 1 <= N", "complete Difference class - class constructor that takes an array of integers and", "and stores it in the maximumDifference instance variable 1 <= N <= 10", "array of integers and saves it to an instance variable named elements -", "count over i for i in range(len(self.elements)): # count over i again, only", "if diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass # End of", "and saves it to an instance variable named elements - computeDifference method that", "over i again, only call it j for j in range(len(self.elements) - i):", "the difference of every element with each other # count over i for", "diff = abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff return", "each other # count over i for i in range(len(self.elements)): # count over", "element with each other # count over i for i in range(len(self.elements)): #", "on Sun Jul 22 23:53:27 2018 @author: DRB4 Task: complete Difference class -", "Task: complete Difference class - class constructor that takes an array of integers", "CODE ################## _ = input() a = [int(e) for e in input().split(' ')]", "variable 1 <= N <= 10 1 <= elements[i] <= 100, where 0", "range(len(self.elements) - i): # len(elements) - 1 to keep from double counting diff", "saves it to an instance variable named elements - computeDifference method that finds", "Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1 2 5] output: 4", "coding: utf-8 -*- \"\"\" Hacker Rank 30 Days of Code 14 - Scope", "input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1", "100, where 0 <= i <= N - 1 \"\"\" ### MY CODE", "i in range(len(self.elements)): # count over i again, only call it j for", "N <= 10 1 <= elements[i] <= 100, where 0 <= i <=", "# count over i again, only call it j for j in range(len(self.elements)", "__init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference = 0 # Need the", "in the maximumDifference instance variable 1 <= N <= 10 1 <= elements[i]", "elements - computeDifference method that finds the maximum absolute different between any 2", "<reponame>hamil168/Learning-Data-Science<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Hacker Rank 30 Days of Code", "any 2 numbers in N and stores it in the maximumDifference instance variable", "Need the difference of every element with each other # count over i", "<= 100, where 0 <= i <= N - 1 \"\"\" ### MY", "HR CODE ################## _ = input() a = [int(e) for e in input().split('", "Difference: def __init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference = 0 #", "- Scope Created on Sun Jul 22 23:53:27 2018 @author: DRB4 Task: complete", "<= 10 1 <= elements[i] <= 100, where 0 <= i <= N", "an array of integers and saves it to an instance variable named elements", "- computeDifference method that finds the maximum absolute different between any 2 numbers", "self.maximumDifference = 0 # Need the difference of every element with each other", "= Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1 2 5] output:", "[1 2 5] output: 4 SUCCESS # input [8 19 3 2 7]", "of integers and saves it to an instance variable named elements - computeDifference", "for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES", "d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1 2 5] output: 4 SUCCESS", "where 0 <= i <= N - 1 \"\"\" ### MY CODE ###", "### MY CODE ### class Difference: def __init__(self, a): self.__elements = a def", "that takes an array of integers and saves it to an instance variable", "the maximum absolute different between any 2 numbers in N and stores it", "the maximumDifference instance variable 1 <= N <= 10 1 <= elements[i] <=", "<= i <= N - 1 \"\"\" ### MY CODE ### class Difference:", "of Difference class ################# HR CODE ################## _ = input() a = [int(e)", "integers and saves it to an instance variable named elements - computeDifference method", "# -*- coding: utf-8 -*- \"\"\" Hacker Rank 30 Days of Code 14", "################## _ = input() a = [int(e) for e in input().split(' ')] d", "1 <= N <= 10 1 <= elements[i] <= 100, where 0 <=", "CASES # input [1 2 5] output: 4 SUCCESS # input [8 19", "_ = input() a = [int(e) for e in input().split(' ')] d =", "from double counting diff = abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference", "> self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass # End of Difference class", "@author: DRB4 Task: complete Difference class - class constructor that takes an array", "in range(len(self.elements) - i): # len(elements) - 1 to keep from double counting", "between any 2 numbers in N and stores it in the maximumDifference instance", "pass # End of Difference class ################# HR CODE ################## _ = input()", "self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass # End of Difference class #################", "2018 @author: DRB4 Task: complete Difference class - class constructor that takes an", "- i): # len(elements) - 1 to keep from double counting diff =", "# input [1 2 5] output: 4 SUCCESS # input [8 19 3", "<= N - 1 \"\"\" ### MY CODE ### class Difference: def __init__(self,", "i <= N - 1 \"\"\" ### MY CODE ### class Difference: def", "DRB4 Task: complete Difference class - class constructor that takes an array of", "class Difference: def __init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference = 0", "j in range(len(self.elements) - i): # len(elements) - 1 to keep from double", "1 <= elements[i] <= 100, where 0 <= i <= N - 1", "Hacker Rank 30 Days of Code 14 - Scope Created on Sun Jul", "')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1 2", "only call it j for j in range(len(self.elements) - i): # len(elements) -", "N - 1 \"\"\" ### MY CODE ### class Difference: def __init__(self, a):", "<= N <= 10 1 <= elements[i] <= 100, where 0 <= i", "################# HR CODE ################## _ = input() a = [int(e) for e in", "in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input", "End of Difference class ################# HR CODE ################## _ = input() a =", "over i for i in range(len(self.elements)): # count over i again, only call", "def computeDifference(self): self.maximumDifference = 0 # Need the difference of every element with", "0 # Need the difference of every element with each other # count", "computeDifference(self): self.maximumDifference = 0 # Need the difference of every element with each", "= input() a = [int(e) for e in input().split(' ')] d = Difference(a)", "10 1 <= elements[i] <= 100, where 0 <= i <= N -", "d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES # input [1 2 5]", "class - class constructor that takes an array of integers and saves it", "self.maximumDifference pass # End of Difference class ################# HR CODE ################## _ =", "Code 14 - Scope Created on Sun Jul 22 23:53:27 2018 @author: DRB4", "class constructor that takes an array of integers and saves it to an", "1 \"\"\" ### MY CODE ### class Difference: def __init__(self, a): self.__elements =", "of every element with each other # count over i for i in", "different between any 2 numbers in N and stores it in the maximumDifference", "elements[i] <= 100, where 0 <= i <= N - 1 \"\"\" ###", "22 23:53:27 2018 @author: DRB4 Task: complete Difference class - class constructor that", "an instance variable named elements - computeDifference method that finds the maximum absolute", "self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass # End", "constructor that takes an array of integers and saves it to an instance", "- class constructor that takes an array of integers and saves it to", "counting diff = abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff", "a): self.__elements = a def computeDifference(self): self.maximumDifference = 0 # Need the difference", "call it j for j in range(len(self.elements) - i): # len(elements) - 1", "-*- \"\"\" Hacker Rank 30 Days of Code 14 - Scope Created on", "that finds the maximum absolute different between any 2 numbers in N and", "CODE ### class Difference: def __init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference", "= 0 # Need the difference of every element with each other #", "takes an array of integers and saves it to an instance variable named", "with each other # count over i for i in range(len(self.elements)): # count", "of Code 14 - Scope Created on Sun Jul 22 23:53:27 2018 @author:", "# End of Difference class ################# HR CODE ################## _ = input() a", "Sun Jul 22 23:53:27 2018 @author: DRB4 Task: complete Difference class - class", "diff return self.maximumDifference pass # End of Difference class ################# HR CODE ##################", "MY CODE ### class Difference: def __init__(self, a): self.__elements = a def computeDifference(self):", "23:53:27 2018 @author: DRB4 Task: complete Difference class - class constructor that takes", "for j in range(len(self.elements) - i): # len(elements) - 1 to keep from", "# len(elements) - 1 to keep from double counting diff = abs(self.elements[i] -", "N and stores it in the maximumDifference instance variable 1 <= N <=", "= diff return self.maximumDifference pass # End of Difference class ################# HR CODE", "5] output: 4 SUCCESS # input [8 19 3 2 7] output: 17", "i): # len(elements) - 1 to keep from double counting diff = abs(self.elements[i]", "utf-8 -*- \"\"\" Hacker Rank 30 Days of Code 14 - Scope Created", "i for i in range(len(self.elements)): # count over i again, only call it", "e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST CASES #", "0 <= i <= N - 1 \"\"\" ### MY CODE ### class", "other # count over i for i in range(len(self.elements)): # count over i", "Scope Created on Sun Jul 22 23:53:27 2018 @author: DRB4 Task: complete Difference", "abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass", "it in the maximumDifference instance variable 1 <= N <= 10 1 <=", "- self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference pass #", "30 Days of Code 14 - Scope Created on Sun Jul 22 23:53:27", "absolute different between any 2 numbers in N and stores it in the", "Days of Code 14 - Scope Created on Sun Jul 22 23:53:27 2018", "range(len(self.elements)): # count over i again, only call it j for j in", "1 to keep from double counting diff = abs(self.elements[i] - self.elements[j]) if diff", "j for j in range(len(self.elements) - i): # len(elements) - 1 to keep", "finds the maximum absolute different between any 2 numbers in N and stores", "\"\"\" ### MY CODE ### class Difference: def __init__(self, a): self.__elements = a", "def __init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference = 0 # Need", "return self.maximumDifference pass # End of Difference class ################# HR CODE ################## _", "class ################# HR CODE ################## _ = input() a = [int(e) for e", "computeDifference method that finds the maximum absolute different between any 2 numbers in", "Difference class ################# HR CODE ################## _ = input() a = [int(e) for", "maximumDifference instance variable 1 <= N <= 10 1 <= elements[i] <= 100,", "input [1 2 5] output: 4 SUCCESS # input [8 19 3 2", "i again, only call it j for j in range(len(self.elements) - i): #", "difference of every element with each other # count over i for i", "in range(len(self.elements)): # count over i again, only call it j for j", "instance variable 1 <= N <= 10 1 <= elements[i] <= 100, where", "- 1 to keep from double counting diff = abs(self.elements[i] - self.elements[j]) if", "len(elements) - 1 to keep from double counting diff = abs(self.elements[i] - self.elements[j])", "every element with each other # count over i for i in range(len(self.elements)):", "maximum absolute different between any 2 numbers in N and stores it in", "[int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) # TEST", "# TEST CASES # input [1 2 5] output: 4 SUCCESS # input", "= [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference) #", "= abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference = diff return self.maximumDifference", "variable named elements - computeDifference method that finds the maximum absolute different between", "named elements - computeDifference method that finds the maximum absolute different between any", "instance variable named elements - computeDifference method that finds the maximum absolute different", "Created on Sun Jul 22 23:53:27 2018 @author: DRB4 Task: complete Difference class", "### class Difference: def __init__(self, a): self.__elements = a def computeDifference(self): self.maximumDifference =", "\"\"\" Hacker Rank 30 Days of Code 14 - Scope Created on Sun", "Difference class - class constructor that takes an array of integers and saves", "print(d.maximumDifference) # TEST CASES # input [1 2 5] output: 4 SUCCESS #", "method that finds the maximum absolute different between any 2 numbers in N", "it to an instance variable named elements - computeDifference method that finds the", "# count over i for i in range(len(self.elements)): # count over i again,", "double counting diff = abs(self.elements[i] - self.elements[j]) if diff > self.maximumDifference: self.maximumDifference =", "# Need the difference of every element with each other # count over", "to an instance variable named elements - computeDifference method that finds the maximum", "self.maximumDifference = diff return self.maximumDifference pass # End of Difference class ################# HR", "output: 4 SUCCESS # input [8 19 3 2 7] output: 17 SUCCESS", "a = [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference)", "for i in range(len(self.elements)): # count over i again, only call it j" ]
[ "out /=x.size # more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins", "None and n_bins <=0: n_bins = x.shape[0]; The case of uniform bins grid!", "Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO:", "= True) out_y = hist2cdf(out_y, normalize = True) out = (bins,out_x, out_y) return", "cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): ''' Cumulative density function constructed by", "TODO: out /=x.size # more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None,", "not None, joint bins). ''' x = np.array(x) x = np.sort(x) ret2 =True", "correspondingly ''' #FIXME: the results are sligthly differ from ecdf # TODO: the", "hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x =", "* For tests: modes n_bins = 't10' and n_bins = 't5' for obtaining", "= np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size # more simple! return", "#-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The cumulative density function made by", "None, ECDF will be constructed on the joint x and y. * If", "bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins", "returned. * ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins", "argument) will be returned. * ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x", "bins in sort(y))/size(y), where: * bins - bins for cdfs (if y is", "= np.sort(x) ret2 =True if (y is not None): y = np.array(y) y", "take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out = (bins, out_x ) else:", "out /=np.max(out) # TODO: out /=x.size # more simple! return out #-------------------------------------------------------------------- def", "hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize = True) out = (bins,out_x,", "take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins =", "bins for cdfs (if y is not None, joint bins). ''' x =", "bins may be more valid (see tests) if(bins is None and n_bins is", "differ from ecdf # TODO: the case xy is the same as for", "----------- * x,y: 1d ndarrays, if y is None, than ecdf only by", "y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return", "def hist2cdf(hist_x, normalize = True): ''' The cumulative density function made by histogram.", "= np.array(x) x = np.sort(x) ret2 =True if (y is not None): y", "None, bins = None, take_mean=False): ''' Cumulative density function constructed by histogram. Parameters:", "is None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x", "(bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True):", "bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) /", "and n_bins = 't5' for obtaining uniform bins with x shape/10 and /5", "is None and n_bins <=0: n_bins = x.shape[0]; The case of uniform bins", "If bins is None and n_bins <=0: n_bins = x.shape[0]; The case of", "constructed by histogram. Parameters: * x,y: 1d ndarrays; * n_bins: required number of", "1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters ----------- *", "1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x)", "is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None):", "ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf", "make the same result as ecdf! * If bins is None and n_bins", "ECDF). * For tests: modes n_bins = 't10' and n_bins = 't5' for", "Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x)", "else: ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right')", "Notes: * If bins is None and n_bins is None: bins = np.sort(np.concatenate((x,y))).", "''' #FIXME: the results are sligthly differ from ecdf # TODO: the case", "__EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters", "out = (bins, out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins,", "y is None, only bins and cdf(x) (2 argument) will be returned. *", "ecfd, but uniform bins may be more valid (see tests) if(bins is None", "Cumulative Density Function (ECDF). Parameters ----------- * x,y: 1d ndarrays, if y is", "on scipy implementation. * If y is not None, ECDF will be constructed", "bins grid! (Differ from ECDF). * For tests: modes n_bins = 't10' and", "= None, bins = None, take_mean=False): ''' Cumulative density function constructed by histogram.", "out_x = hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize = True) out", "np.sort(x) ret2 =True if (y is not None): y = np.array(y) y =", "y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf) /", "if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): '''", "x will be taken. Returns -------- * if y is not None ->", "''' Cumulative density function constructed by histogram. Parameters: * x,y: 1d ndarrays; *", "by histogram. Parameters: * x,y: 1d ndarrays; * n_bins: required number of uniformly", "None, joint bins). ''' x = np.array(x) x = np.sort(x) ret2 =True if", "n_bins = 't5' for obtaining uniform bins with x shape/10 and /5 correspondingly", "bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None): bins =", "1d ndarrays, if y is None, than ecdf only by x will be", "out_y = hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize", "is not None -> (out_x, out_y,bins) * y is None -> (out_x,bins) Notes:", "= take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None): bins = take_bins(x,y,", "None, only bins and cdf(x) (2 argument) will be returned. * ECDF is", "= x.shape[0]; The case of uniform bins grid! (Differ from ECDF). * For", "Notes ------- * Based on scipy implementation. * If y is not None,", "np.sort(y) else: ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins,", "tests: modes n_bins = 't10' and n_bins = 't5' for obtaining uniform bins", "for ecfd, but uniform bins may be more valid (see tests) if(bins is", "cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out", "= n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y", "None -> (bins,out_x). Notes ------- * Based on scipy implementation. * If y", "y is None -> (out_x,bins) Notes: * If bins is None and n_bins", "For tests: modes n_bins = 't10' and n_bins = 't5' for obtaining uniform", "of uniform bins grid! (Differ from ECDF). * For tests: modes n_bins =", "= ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function", "'t5' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins,", "#FIXME: the results are sligthly differ from ecdf # TODO: the case xy", "only if bins is None. * bins: grid of prepared bins (can be", "only bins and cdf(x) (2 argument) will be returned. * ECDF is calculated", "only by x will be taken. Returns -------- * if y is not", "__all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density", "None, than ecdf only by x will be taken. Returns -------- * if", "out_x = hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize", "Returns -------- * if y is not None -> (bins,out_x, out_y); * if", "sustrauct mean if ture. Returns: * y is not None -> (out_x, out_y,bins)", "ndarrays; * n_bins: required number of uniformly distributed bins, * work only if", "if(normalize): out /=np.max(out) # TODO: out /=x.size # more simple! return out #--------------------------------------------------------------------", "None and n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and", "import numpy as np import scipy from ._hist import take_bins __all__ = ['ecdf']", "= True): ''' The cumulative density function made by histogram. Parameters: * hist_x", "and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins", "take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5)", "function constructed by histogram. Parameters: * x,y: 1d ndarrays; * n_bins: required number", "None -> (out_x,bins) Notes: * If bins is None and n_bins is None:", "=True if (y is not None): y = np.array(y) y = np.sort(y) else:", "TODO: the case xy is the same as for ecfd, but uniform bins", "is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is None):", "(ECDF). Parameters ----------- * x,y: 1d ndarrays, if y is None, than ecdf", "where: * bins - bins for cdfs (if y is not None, joint", "if y is not None -> (bins,out_x, out_y); * if y is None", "n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is", "and cdf(x) (2 argument) will be returned. * ECDF is calculated as: bins", "True): ''' The cumulative density function made by histogram. Parameters: * hist_x 1d", "= 't10' and n_bins = 't5' for obtaining uniform bins with x shape/10", "The cumulative density function made by histogram. Parameters: * hist_x 1d histogram (ndarray).", "(y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #--------------------------------------------------------------------", "* take_mean: sustrauct mean if ture. Returns: * y is not None ->", "result as ecdf! * If bins is None and n_bins <=0: n_bins =", "return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The cumulative density function", "bins is None. * bins: grid of prepared bins (can be ununiform) *", "histogram. Parameters: * hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function).", "= hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize =", "and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x", "x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf)", "histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out", "elif(n_bins == 't5' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is", "= (bins, out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins", "(y is not None): y = np.array(y) y = np.sort(y) else: ret2 =", "bins and cdf(x) (2 argument) will be returned. * ECDF is calculated as:", "more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False):", "-> (out_x, out_y,bins) * y is None -> (out_x,bins) Notes: * If bins", "be taken. Returns -------- * if y is not None -> (bins,out_x, out_y);", "bins (can be ununiform) * take_mean: sustrauct mean if ture. Returns: * y", "distributed bins, * work only if bins is None. * bins: grid of", "* y is not None -> (out_x, out_y,bins) * y is None ->", "n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y", "is None, only bins and cdf(x) (2 argument) will be returned. * ECDF", "return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): ''' Cumulative", "y is None -> (bins,out_x). Notes ------- * Based on scipy implementation. *", "-> (bins,out_x, out_y); * if y is None -> (bins,out_x). Notes ------- *", "valid (see tests) if(bins is None and n_bins is None): bins = take_bins(x,y,", "''' x = np.array(x) x = np.sort(x) ret2 =True if (y is not", "as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y = (serch&past", "None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins =", "y is not None, joint bins). ''' x = np.array(x) x = np.sort(x)", "x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0]", "= take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins", "= None, take_mean=False): ''' Cumulative density function constructed by histogram. Parameters: * x,y:", "Parameters: * x,y: 1d ndarrays; * n_bins: required number of uniformly distributed bins,", "= np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size #", "density function made by histogram. Parameters: * hist_x 1d histogram (ndarray). Returns: *", "#-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters ----------- * x,y:", "function made by histogram. Parameters: * hist_x 1d histogram (ndarray). Returns: * cfd(hist_x)", "is not None, ECDF will be constructed on the joint x and y.", "# more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None,", "and /5 correspondingly ''' #FIXME: the results are sligthly differ from ecdf #", "scipy implementation. * If y is not None, ECDF will be constructed on", "np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf)", "shape/10 and /5 correspondingly ''' #FIXME: the results are sligthly differ from ecdf", "on the joint x and y. * If y is None, only bins", "= (serch&past bins in sort(y))/size(y), where: * bins - bins for cdfs (if", "= np.array(y) y = np.sort(y) else: ret2 = False y=np.array([]) bins = np.concatenate((x,y))", "False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins,", "hist2cdf(out_x, normalize = True) out = (bins, out_x ) else: bins, out_x, out_y", "* If bins is None and n_bins is None: bins = np.sort(np.concatenate((x,y))). This", "* Based on scipy implementation. * If y is not None, ECDF will", "is None, than ecdf only by x will be taken. Returns -------- *", "= hist2cdf(out_x, normalize = True) out = (bins, out_x ) else: bins, out_x,", "out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): ''' Cumulative density", "n_bins = x.shape[0]; The case of uniform bins grid! (Differ from ECDF). *", "out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize", "n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins = bins,", "normalize = True) out_y = hist2cdf(out_y, normalize = True) out = (bins,out_x, out_y)", "Cumulative density function constructed by histogram. Parameters: * x,y: 1d ndarrays; * n_bins:", "np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf =", "if bins is None. * bins: grid of prepared bins (can be ununiform)", "np.array(y) y = np.sort(y) else: ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins)", "Density Function (ECDF). Parameters ----------- * x,y: 1d ndarrays, if y is None,", "None -> (bins,out_x, out_y); * if y is None -> (bins,out_x). Notes -------", "be constructed on the joint x and y. * If y is None,", "bins is None and n_bins <=0: n_bins = x.shape[0]; The case of uniform", "bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize =", "import scipy from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #--------------------------------------------------------------------", "as np import scipy from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__ =", "-> (out_x,bins) Notes: * If bins is None and n_bins is None: bins", "for obtaining uniform bins with x shape/10 and /5 correspondingly ''' #FIXME: the", "- bins for cdfs (if y is not None, joint bins). ''' x", "same as for ecfd, but uniform bins may be more valid (see tests)", "ECDF will be constructed on the joint x and y. * If y", "is calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y", "''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out", "take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize = True)", "and n_bins is None: bins = np.sort(np.concatenate((x,y))). This case make the same result", "is not None, joint bins). ''' x = np.array(x) x = np.sort(x) ret2", "number of uniformly distributed bins, * work only if bins is None. *", "'t5' for obtaining uniform bins with x shape/10 and /5 correspondingly ''' #FIXME:", "np import scipy from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8", "y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right')", "None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is None): bins", "hist2cdf(hist_x, normalize = True): ''' The cumulative density function made by histogram. Parameters:", "(bins, out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins =", "Empirical Cumulative Density Function (ECDF). Parameters ----------- * x,y: 1d ndarrays, if y", "= hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize =", "if (y is not None): y = np.array(y) y = np.sort(y) else: ret2", "(bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The cumulative density", "case of uniform bins grid! (Differ from ECDF). * For tests: modes n_bins", "(x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2):", "out_y); * if y is None -> (bins,out_x). Notes ------- * Based on", "* x,y: 1d ndarrays, if y is None, than ecdf only by x", "y = np.array(y) y = np.sort(y) else: ret2 = False y=np.array([]) bins =", "def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters ----------- * x,y: 1d", "np.array(x) x = np.sort(x) ret2 =True if (y is not None): y =", "None and n_bins is None: bins = np.sort(np.concatenate((x,y))). This case make the same", "* ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in", "if(bins is None and n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins ==", "is None and n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10'", "as ecdf! * If bins is None and n_bins <=0: n_bins = x.shape[0];", "If y is None, only bins and cdf(x) (2 argument) will be returned.", "bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf", "(can be ununiform) * take_mean: sustrauct mean if ture. Returns: * y is", "= np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0]", "* hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x", "ture. Returns: * y is not None -> (out_x, out_y,bins) * y is", "and n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins", "* If y is None, only bins and cdf(x) (2 argument) will be", "the case xy is the same as for ecfd, but uniform bins may", "x = np.sort(x) ret2 =True if (y is not None): y = np.array(y)", "None, take_mean=False): ''' Cumulative density function constructed by histogram. Parameters: * x,y: 1d", "density function constructed by histogram. Parameters: * x,y: 1d ndarrays; * n_bins: required", "but uniform bins may be more valid (see tests) if(bins is None and", "ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x),", "None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is None): bins", "n_bins <=0: n_bins = x.shape[0]; The case of uniform bins grid! (Differ from", "hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True)", "ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters ----------- * x,y: 1d ndarrays,", "1d ndarrays; * n_bins: required number of uniformly distributed bins, * work only", "in sort(y))/size(y), where: * bins - bins for cdfs (if y is not", "is None -> (bins,out_x). Notes ------- * Based on scipy implementation. * If", "(Differ from ECDF). * For tests: modes n_bins = 't10' and n_bins =", "'t10' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and", "and n_bins <=0: n_bins = x.shape[0]; The case of uniform bins grid! (Differ", "bins in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where: * bins -", "== 't10' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5'", "(if y is not None, joint bins). ''' x = np.array(x) x =", "(ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The", "take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10)", "= True) out = (bins, out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins", "/ x.shape[0] y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2): out=", "If bins is None and n_bins is None: bins = np.sort(np.concatenate((x,y))). This case", "#-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): ''' Cumulative density function", "and y. * If y is None, only bins and cdf(x) (2 argument)", "/=x.size # more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins =", "uniformly distributed bins, * work only if bins is None. * bins: grid", "* work only if bins is None. * bins: grid of prepared bins", "joint x and y. * If y is None, only bins and cdf(x)", "scipy from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def", "hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size", "(bins,out_x, out_y); * if y is None -> (bins,out_x). Notes ------- * Based", "* if y is not None -> (bins,out_x, out_y); * if y is", "modes n_bins = 't10' and n_bins = 't5' for obtaining uniform bins with", "# TODO: out /=x.size # more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins =", "of prepared bins (can be ununiform) * take_mean: sustrauct mean if ture. Returns:", "normalize = True) out = (bins, out_x ) else: bins, out_x, out_y =", "* x,y: 1d ndarrays; * n_bins: required number of uniformly distributed bins, *", "-> (bins,out_x). Notes ------- * Based on scipy implementation. * If y is", "np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0] out", "is the same as for ecfd, but uniform bins may be more valid", "is not None -> (bins,out_x, out_y); * if y is None -> (bins,out_x).", "x and y. * If y is None, only bins and cdf(x) (2", "n_bins = 't10' and n_bins = 't5' for obtaining uniform bins with x", "take_mean: sustrauct mean if ture. Returns: * y is not None -> (out_x,", "x,y: 1d ndarrays, if y is None, than ecdf only by x will", "n_bins='xy') elif(n_bins == 't10' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins", "bins is None and n_bins is None: bins = np.sort(np.concatenate((x,y))). This case make", "will be taken. Returns -------- * if y is not None -> (bins,out_x,", "None. * bins: grid of prepared bins (can be ununiform) * take_mean: sustrauct", "= bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize", "'t10' and n_bins = 't5' for obtaining uniform bins with x shape/10 and", "np.sort(np.concatenate((x,y))). This case make the same result as ecdf! * If bins is", "y is not None -> (out_x, out_y,bins) * y is None -> (out_x,bins)", "be returned. * ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past", "x = np.array(x) x = np.sort(x) ret2 =True if (y is not None):", "'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf)", "out_y,bins) * y is None -> (out_x,bins) Notes: * If bins is None", "= n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out", "cdf_y = (serch&past bins in sort(y))/size(y), where: * bins - bins for cdfs", "= (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize =", "x.shape[0]; The case of uniform bins grid! (Differ from ECDF). * For tests:", "cdf(x) (2 argument) will be returned. * ECDF is calculated as: bins =", "= np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf =", "tests) if(bins is None and n_bins is None): bins = take_bins(x,y, n_bins='xy') elif(n_bins", "# TODO: the case xy is the same as for ecfd, but uniform", "will be returned. * ECDF is calculated as: bins = sort(concatenate(x,y)), cdf_x =", "calculated as: bins = sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y =", "(bins,out_x). Notes ------- * Based on scipy implementation. * If y is not", "take_mean=False): ''' Cumulative density function constructed by histogram. Parameters: * x,y: 1d ndarrays;", "y is None, than ecdf only by x will be taken. Returns --------", "implementation. * If y is not None, ECDF will be constructed on the", "bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y,", "not None -> (out_x, out_y,bins) * y is None -> (out_x,bins) Notes: *", "import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical", "* bins: grid of prepared bins (can be ununiform) * take_mean: sustrauct mean", "may be more valid (see tests) if(bins is None and n_bins is None):", "work only if bins is None. * bins: grid of prepared bins (can", "Parameters ----------- * x,y: 1d ndarrays, if y is None, than ecdf only", "= 't5' for obtaining uniform bins with x shape/10 and /5 correspondingly '''", "(ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out =", "bins with x shape/10 and /5 correspondingly ''' #FIXME: the results are sligthly", "['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF).", "is not None): y = np.array(y) y = np.sort(y) else: ret2 = False", "histogram. Parameters: * x,y: 1d ndarrays; * n_bins: required number of uniformly distributed", "constructed on the joint x and y. * If y is None, only", "If y is not None, ECDF will be constructed on the joint x", "The case of uniform bins grid! (Differ from ECDF). * For tests: modes", "will be constructed on the joint x and y. * If y is", "out_x = hist2cdf(out_x, normalize = True) out = (bins, out_x ) else: bins,", "case xy is the same as for ecfd, but uniform bins may be", "(Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out)", "out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins = bins,", "by x will be taken. Returns -------- * if y is not None", "True) out = (bins, out_x ) else: bins, out_x, out_y = hist(x,y=y,n_bins =", "x.shape[0] y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf)", "not None -> (bins,out_x, out_y); * if y is None -> (bins,out_x). Notes", "* If y is not None, ECDF will be constructed on the joint", "._hist import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): '''", "= (x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0] out = (bins,x_cdf) if", "* If bins is None and n_bins <=0: n_bins = x.shape[0]; The case", "xy is the same as for ecfd, but uniform bins may be more", "is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins", "uniform bins grid! (Differ from ECDF). * For tests: modes n_bins = 't10'", "results are sligthly differ from ecdf # TODO: the case xy is the", "* cfd(hist_x) (Cumulative Density Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize):", "(out_x,bins) Notes: * If bins is None and n_bins is None: bins =", "grid! (Differ from ECDF). * For tests: modes n_bins = 't10' and n_bins", "uniform bins may be more valid (see tests) if(bins is None and n_bins", "elif(n_bins == 't10' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins ==", "(see tests) if(bins is None and n_bins is None): bins = take_bins(x,y, n_bins='xy')", "bins = None, take_mean=False): ''' Cumulative density function constructed by histogram. Parameters: *", "joint bins). ''' x = np.array(x) x = np.sort(x) ret2 =True if (y", "-------- * if y is not None -> (bins,out_x, out_y); * if y", "mean if ture. Returns: * y is not None -> (out_x, out_y,bins) *", "taken. Returns -------- * if y is not None -> (bins,out_x, out_y); *", "n_bins: required number of uniformly distributed bins, * work only if bins is", "/=np.max(out) # TODO: out /=x.size # more simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins", "sligthly differ from ecdf # TODO: the case xy is the same as", "Returns: * y is not None -> (out_x, out_y,bins) * y is None", "in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where: * bins - bins", "bins - bins for cdfs (if y is not None, joint bins). '''", "np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size # more", "cdf_x = (serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where:", "Density Function). ''' hist_x = np.asarray(hist_x) out = np.cumsum(hist_x) if(normalize): out /=np.max(out) #", "not None, ECDF will be constructed on the joint x and y. *", "from ecdf # TODO: the case xy is the same as for ecfd,", "numpy as np import scipy from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__", "as for ecfd, but uniform bins may be more valid (see tests) if(bins", "= (serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where: *", "are sligthly differ from ecdf # TODO: the case xy is the same", "bins: grid of prepared bins (can be ununiform) * take_mean: sustrauct mean if", "the same result as ecdf! * If bins is None and n_bins <=0:", "x,y: 1d ndarrays; * n_bins: required number of uniformly distributed bins, * work", "y is not None -> (bins,out_x, out_y); * if y is None ->", "be ununiform) * take_mean: sustrauct mean if ture. Returns: * y is not", "bins = take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is None): bins =", "by histogram. Parameters: * hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density", "ununiform) * take_mean: sustrauct mean if ture. Returns: * y is not None", "= np.sort(np.concatenate((x,y))). This case make the same result as ecdf! * If bins", "the joint x and y. * If y is None, only bins and", "------- * Based on scipy implementation. * If y is not None, ECDF", "if(y is None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean)", "sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where: * bins - bins for", "'right') x_cdf = (x_cdf) / x.shape[0] y_cdf = (y_cdf) / y.shape[0] out =", "bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//10) elif(n_bins == 't5' and bins is", "n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out_y =", "y. * If y is None, only bins and cdf(x) (2 argument) will", "out_x, out_y = hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x,", "ecdf # TODO: the case xy is the same as for ecfd, but", "* if y is None -> (bins,out_x). Notes ------- * Based on scipy", "made by histogram. Parameters: * hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative", "y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x,", "grid of prepared bins (can be ununiform) * take_mean: sustrauct mean if ture.", "case make the same result as ecdf! * If bins is None and", "np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size # more simple! return out", "* bins - bins for cdfs (if y is not None, joint bins).", "= hist2cdf(out_x, normalize = True) out_y = hist2cdf(out_y, normalize = True) out =", "bins, out_x = hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x,", "(2 argument) will be returned. * ECDF is calculated as: bins = sort(concatenate(x,y)),", "x shape/10 and /5 correspondingly ''' #FIXME: the results are sligthly differ from", "bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x =", "ecdf only by x will be taken. Returns -------- * if y is", "(serch&past bins in sort(y))/size(y), where: * bins - bins for cdfs (if y", "if y is None -> (bins,out_x). Notes ------- * Based on scipy implementation.", "This case make the same result as ecdf! * If bins is None", "''' Empirical Cumulative Density Function (ECDF). Parameters ----------- * x,y: 1d ndarrays, if", "simple! return out #-------------------------------------------------------------------- def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): '''", "= sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins in", "bins). ''' x = np.array(x) x = np.sort(x) ret2 =True if (y is", "of uniformly distributed bins, * work only if bins is None. * bins:", "out = np.cumsum(hist_x) if(normalize): out /=np.max(out) # TODO: out /=x.size # more simple!", "Based on scipy implementation. * If y is not None, ECDF will be", "ret2 =True if (y is not None): y = np.array(y) y = np.sort(y)", "bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out = (bins,", "<=0: n_bins = x.shape[0]; The case of uniform bins grid! (Differ from ECDF).", "(serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y), where: * bins", "else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x", "= 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative Density Function (ECDF). Parameters -----------", "None: bins = np.sort(np.concatenate((x,y))). This case make the same result as ecdf! *", "None): y = np.array(y) y = np.sort(y) else: ret2 = False y=np.array([]) bins", "is None. * bins: grid of prepared bins (can be ununiform) * take_mean:", "= np.searchsorted(x,bins, 'right') y_cdf = np.searchsorted(y,bins, 'right') x_cdf = (x_cdf) / x.shape[0] y_cdf", "sort(y))/size(y), where: * bins - bins for cdfs (if y is not None,", "same result as ecdf! * If bins is None and n_bins <=0: n_bins", "out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The cumulative", "the results are sligthly differ from ecdf # TODO: the case xy is", "n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out =", "def cdf_by_hist(x,y=None,n_bins = None, bins = None, take_mean=False): ''' Cumulative density function constructed", "Function (ECDF). Parameters ----------- * x,y: 1d ndarrays, if y is None, than", "ecdf! * If bins is None and n_bins <=0: n_bins = x.shape[0]; The", "from ._hist import take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None):", "prepared bins (can be ununiform) * take_mean: sustrauct mean if ture. Returns: *", "is None -> (out_x,bins) Notes: * If bins is None and n_bins is", "cdfs (if y is not None, joint bins). ''' x = np.array(x) x", "out #-------------------------------------------------------------------- def hist2cdf(hist_x, normalize = True): ''' The cumulative density function made", "is None: bins = np.sort(np.concatenate((x,y))). This case make the same result as ecdf!", "obtaining uniform bins with x shape/10 and /5 correspondingly ''' #FIXME: the results", "required number of uniformly distributed bins, * work only if bins is None.", "bins, * work only if bins is None. * bins: grid of prepared", "= np.sort(y) else: ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf =", "more valid (see tests) if(bins is None and n_bins is None): bins =", "(out_x, out_y,bins) * y is None -> (out_x,bins) Notes: * If bins is", "== 't5' and bins is None): bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None):", "be more valid (see tests) if(bins is None and n_bins is None): bins", "/ y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out #-------------------------------------------------------------------- def", "normalize = True): ''' The cumulative density function made by histogram. Parameters: *", "for cdfs (if y is not None, joint bins). ''' x = np.array(x)", "y = np.sort(y) else: ret2 = False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf", "sort(concatenate(x,y)), cdf_x = (serch&past bins in sort(x))/size(x), cdf_y = (serch&past bins in sort(y))/size(y),", "cumulative density function made by histogram. Parameters: * hist_x 1d histogram (ndarray). Returns:", "= (y_cdf) / y.shape[0] out = (bins,x_cdf) if (ret2): out= (bins,x_cdf,y_cdf) return out", "not None): y = np.array(y) y = np.sort(y) else: ret2 = False y=np.array([])", "is None and n_bins is None: bins = np.sort(np.concatenate((x,y))). This case make the", "* n_bins: required number of uniformly distributed bins, * work only if bins", "= bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out = (bins, out_x", "bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True) out = (bins, out_x )", "y is not None, ECDF will be constructed on the joint x and", "bins = take_bins(x,y, n_bins=x.shape[0]//5) if(y is None): bins, out_x = hist(x,y=None,n_bins = n_bins,", "n_bins is None: bins = np.sort(np.concatenate((x,y))). This case make the same result as", "* y is None -> (out_x,bins) Notes: * If bins is None and", "uniform bins with x shape/10 and /5 correspondingly ''' #FIXME: the results are", ") else: bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean)", "with x shape/10 and /5 correspondingly ''' #FIXME: the results are sligthly differ", "None): bins, out_x = hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x =", "/5 correspondingly ''' #FIXME: the results are sligthly differ from ecdf # TODO:", "bins = np.sort(np.concatenate((x,y))). This case make the same result as ecdf! * If", "if ture. Returns: * y is not None -> (out_x, out_y,bins) * y", "True) out_y = hist2cdf(out_y, normalize = True) out = (bins,out_x, out_y) return out", "''' The cumulative density function made by histogram. Parameters: * hist_x 1d histogram", "hist(x,y=None,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x = hist2cdf(out_x, normalize = True)", "from ECDF). * For tests: modes n_bins = 't10' and n_bins = 't5'", "if y is None, than ecdf only by x will be taken. Returns", "= False y=np.array([]) bins = np.concatenate((x,y)) bins=np.sort(bins) x_cdf = np.searchsorted(x,bins, 'right') y_cdf =", "None -> (out_x, out_y,bins) * y is None -> (out_x,bins) Notes: * If", "= take_bins(x,y, n_bins='xy') elif(n_bins == 't10' and bins is None): bins = take_bins(x,y,", "than ecdf only by x will be taken. Returns -------- * if y", "bins, out_x, out_y = hist(x,y=y,n_bins = n_bins, bins = bins, take_mean=take_mean) out_x =", "the same as for ecfd, but uniform bins may be more valid (see", "ndarrays, if y is None, than ecdf only by x will be taken.", "take_bins __all__ = ['ecdf'] __EPSILON__ = 1e-8 #-------------------------------------------------------------------- def ecdf(x,y=None): ''' Empirical Cumulative", "Parameters: * hist_x 1d histogram (ndarray). Returns: * cfd(hist_x) (Cumulative Density Function). '''" ]
[ "else: return 250 * .4663 + 150 * .4463 + (x - 400)", "x * .4463 elif x <= 400: return (x - 150) * .4663", "150: return x * .4463 elif x <= 400: return (x - 150)", "if x <= 150: return x * .4463 elif x <= 400: return", ".4663 + 150 * .4463 else: return 250 * .4663 + 150 *", "* .4663 + 150 * .4463 + (x - 400) * .5663 print(\"{0:.2f}\".format(main(int(input()))))", "<= 150: return x * .4463 elif x <= 400: return (x -", "return 250 * .4663 + 150 * .4463 + (x - 400) *", "<= 400: return (x - 150) * .4663 + 150 * .4463 else:", "(x - 150) * .4663 + 150 * .4463 else: return 250 *", "- 150) * .4663 + 150 * .4463 else: return 250 * .4663", "x <= 400: return (x - 150) * .4663 + 150 * .4463", "400: return (x - 150) * .4663 + 150 * .4463 else: return", "* .4663 + 150 * .4463 else: return 250 * .4663 + 150", "main(x): if x <= 150: return x * .4463 elif x <= 400:", "250 * .4663 + 150 * .4463 + (x - 400) * .5663", "150) * .4663 + 150 * .4463 else: return 250 * .4663 +", "+ 150 * .4463 else: return 250 * .4663 + 150 * .4463", "return (x - 150) * .4663 + 150 * .4463 else: return 250", "x <= 150: return x * .4463 elif x <= 400: return (x", "150 * .4463 else: return 250 * .4663 + 150 * .4463 +", "return x * .4463 elif x <= 400: return (x - 150) *", ".4463 elif x <= 400: return (x - 150) * .4663 + 150", ".4463 else: return 250 * .4663 + 150 * .4463 + (x -", "* .4463 elif x <= 400: return (x - 150) * .4663 +", "elif x <= 400: return (x - 150) * .4663 + 150 *", "def main(x): if x <= 150: return x * .4463 elif x <=", "* .4463 else: return 250 * .4663 + 150 * .4463 + (x" ]
[ "<filename>Directory-observer/test/__init__.py #!/usr/bin/env python # -*- coding: utf-8 -*- import test_engine __author__ = 'Shishou'" ]
[ "created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create(", "membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic']", "apps.utils.test_util import TestMixin from ..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase):", "= False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] =", "user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 =", "from django.test import TestCase from django.urls import reverse from django.utils import timezone from", "import timezone from rest_framework import status from apps.physicaldevice.models import Device from apps.streamfilter.models import", "self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp = self.client.get(map_url)", "import datetime import json import dateutil.parser from django.contrib.auth import get_user_model from django.test import", "resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp", "\"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations']", "= self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations']", "= get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1,", "TestCase from django.urls import reverse from django.utils import timezone from rest_framework import status", "self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location)", "location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\"", "no permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership", "from rest_framework import status from apps.physicaldevice.models import Device from apps.streamfilter.models import * from", "self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def", "django.urls import reverse from django.utils import timezone from rest_framework import status from apps.physicaldevice.models", "django.utils import timezone from rest_framework import status from apps.physicaldevice.models import Device from apps.streamfilter.models", "template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location =", "self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id,", "def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def", "with no permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>')", "import * from apps.utils.test_util import TestMixin from ..models import * user_model = get_user_model()", "reverse from django.utils import timezone from rest_framework import status from apps.physicaldevice.models import Device", ") self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with no permissions", "class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1,", "def testMemberPermissions(self): \"\"\" Test that people with no permissions cannot access \"\"\" map_url", "dateutil.parser from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse", "= Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def", "setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2,", "import dateutil.parser from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import", "from apps.utils.test_util import TestMixin from ..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin,", "self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1,", "self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code,", "Test that people with no permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug':", "label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete()", "json import dateutil.parser from django.contrib.auth import get_user_model from django.test import TestCase from django.urls", "= DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test", "kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp", "timezone from rest_framework import status from apps.physicaldevice.models import Device from apps.streamfilter.models import *", "cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3,", "self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url)", "from django.utils import timezone from rest_framework import status from apps.physicaldevice.models import Device from", "def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 =", "from apps.streamfilter.models import * from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from", "DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2", "access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1')", "rest_framework import status from apps.physicaldevice.models import Device from apps.streamfilter.models import * from apps.utils.gid.convert", "template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown()", "self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with no permissions cannot access \"\"\"", "django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from django.utils", "self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3)", "from apps.physicaldevice.models import Device from apps.streamfilter.models import * from apps.utils.gid.convert import * from", "Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self):", "self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with no permissions cannot", "from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from ..models import * user_model", "reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save()", "self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with no permissions cannot access", "from django.urls import reverse from django.utils import timezone from rest_framework import status from", "membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save()", "django.test import TestCase from django.urls import reverse from django.utils import timezone from rest_framework", "False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False", "= reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False", "apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from ..models import * user_model =", "import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup()", "testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self):", "* from apps.utils.test_util import TestMixin from ..models import * user_model = get_user_model() class", "import json import dateutil.parser from django.contrib.auth import get_user_model from django.test import TestCase from", "from ..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup()", "DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that", "import TestMixin from ..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def", "self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] =", "password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code,", "that people with no permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug})", "testMemberPermissions(self): \"\"\" Test that people with no permissions cannot access \"\"\" map_url =", "\"\"\" Test that people with no permissions cannot access \"\"\" map_url = reverse('devicelocation:map',", "TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2", "import status from apps.physicaldevice.models import Device from apps.streamfilter.models import * from apps.utils.gid.convert import", "timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people", "self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp =", "Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 )", "self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown()", "* user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1", "membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) self.client.logout()", "Device from apps.streamfilter.models import * from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin", "self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id)", "import reverse from django.utils import timezone from rest_framework import status from apps.physicaldevice.models import", "TestMixin from ..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self):", "target_slug=self.pd1.slug, user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with", "user=self.u2 ) self.assertIsNotNone(location) self.assertEqual(location.target.id, self.pd1.id) def testMemberPermissions(self): \"\"\" Test that people with no", "get_user_model from django.test import TestCase from django.urls import reverse from django.utils import timezone", "apps.streamfilter.models import * from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from ..models", "* from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from ..models import *", "status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)", "from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from", "import get_user_model from django.test import TestCase from django.urls import reverse from django.utils import", "..models import * user_model = get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup()", "datetime import json import dateutil.parser from django.contrib.auth import get_user_model from django.test import TestCase", "import Device from apps.streamfilter.models import * from apps.utils.gid.convert import * from apps.utils.test_util import", "status from apps.physicaldevice.models import Device from apps.streamfilter.models import * from apps.utils.gid.convert import *", "tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(), target_slug=self.pd1.slug,", "created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown()", "get_user_model() class DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1',", "DeviceLocationTestCase(TestMixin, TestCase): def setUp(self): self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2)", "label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location", "= Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self):", "import * from apps.utils.gid.convert import * from apps.utils.test_util import TestMixin from ..models import", "apps.physicaldevice.models import Device from apps.streamfilter.models import * from apps.utils.gid.convert import * from apps.utils.test_util", "= self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True membership.permissions['can_access_classic'] = False membership.save() resp =", "Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3) def tearDown(self): DeviceLocation.objects.all().delete()", "people with no permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>',", "membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)", "map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership = self.p1.org.register_user(self.u3, role='m1') membership.permissions['can_read_device_locations'] =", "self.usersTestSetup() self.orgTestSetup() self.deviceTemplateTestSetup() self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2) self.pd2 = Device.objects.create_device(project=self.p2, label='d2',", "permissions cannot access \"\"\" map_url = reverse('devicelocation:map', kwargs={'slug': self.pd1.slug}) self.client.login(email='<EMAIL>', password='<PASSWORD>') membership =", "def tearDown(self): DeviceLocation.objects.all().delete() Device.objects.all().delete() self.deviceTemplateTestTearDown() self.orgTestTearDown() self.userTestTearDown() def testLocation(self): location = DeviceLocation.objects.create( timestamp=timezone.now(),", "import TestCase from django.urls import reverse from django.utils import timezone from rest_framework import", "role='m1') membership.permissions['can_read_device_locations'] = False membership.save() resp = self.client.get(map_url) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) membership.permissions['can_read_device_locations'] = True" ]
[ "try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save() except NicknameArchive.DoesNotExist:", "1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun =", "'emoji') noun = choice(noun_list) emoji = noun[1] nickname = adj + noun[0] try:", "Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1] nickname = adj + noun[0]", "count = archive.count archive.count += 1 archive.save() except NicknameArchive.DoesNotExist: NicknameArchive.objects.create(nickname=nickname) return emoji, nickname+str(count)", "Nickname, NicknameArchive def get_nickname(): nickname = \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content')", "noun = choice(noun_list) emoji = noun[1] nickname = adj + noun[0] try: archive", "= NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save() except NicknameArchive.DoesNotExist: NicknameArchive.objects.create(nickname=nickname) return", "emoji = noun[1] nickname = adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count", "adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1]", "= Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1] nickname = adj +", "NicknameArchive def get_nickname(): nickname = \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj", "from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname = \"\" count = 1", "NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save() except NicknameArchive.DoesNotExist: NicknameArchive.objects.create(nickname=nickname) return emoji,", "= adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count +=", "adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list)", "random import choice from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname = \"\"", "= choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1] nickname", "from random import choice from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname =", "choice from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname = \"\" count =", "noun[1] nickname = adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count", "import Nickname, NicknameArchive def get_nickname(): nickname = \"\" count = 1 adj_list =", "nickname = adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count", "= noun[1] nickname = adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count =", "adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1", "archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save() except NicknameArchive.DoesNotExist: NicknameArchive.objects.create(nickname=nickname)", "\"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content',", "= 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun", "choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1] nickname =", "= choice(noun_list) emoji = noun[1] nickname = adj + noun[0] try: archive =", "= \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list =", "nickname = \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list", "get_nickname(): nickname = \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0]", "noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save() except", "choice(noun_list) emoji = noun[1] nickname = adj + noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname)", "= Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji", "import choice from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname = \"\" count", "<filename>accounts/utils.py from random import choice from accounts.models import Nickname, NicknameArchive def get_nickname(): nickname", "noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji = noun[1] nickname = adj", "+ noun[0] try: archive = NicknameArchive.objects.get(nickname=nickname) count = archive.count archive.count += 1 archive.save()", "accounts.models import Nickname, NicknameArchive def get_nickname(): nickname = \"\" count = 1 adj_list", "def get_nickname(): nickname = \"\" count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj =", "Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji') noun = choice(noun_list) emoji =", "count = 1 adj_list = Nickname.objects.filter(part='a').values_list('content') adj = choice(adj_list)[0] noun_list = Nickname.objects.filter(part='n').values_list('content', 'emoji')" ]
[ "import Setup class Command(BaseCommand): help = \"start the setup\" def handle(self, *args, **options):", "_setup.models import Setup class Command(BaseCommand): help = \"start the setup\" def handle(self, *args,", "from django.core.management.base import BaseCommand from _setup.models import Setup class Command(BaseCommand): help = \"start", "Setup class Command(BaseCommand): help = \"start the setup\" def handle(self, *args, **options): Setup()._menu()", "BaseCommand from _setup.models import Setup class Command(BaseCommand): help = \"start the setup\" def", "import BaseCommand from _setup.models import Setup class Command(BaseCommand): help = \"start the setup\"", "<reponame>marcoEDU/HackerspaceWebsiteTemplate<filename>_setup/management/commands/setup.py<gh_stars>1-10 from django.core.management.base import BaseCommand from _setup.models import Setup class Command(BaseCommand): help =", "django.core.management.base import BaseCommand from _setup.models import Setup class Command(BaseCommand): help = \"start the", "from _setup.models import Setup class Command(BaseCommand): help = \"start the setup\" def handle(self," ]
[ "msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject']", "original hdfs and the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time", "+ tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath", "frostFiles.append(fname) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print", "print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert", "%s file not found\" % inLst ) print(\"Or Error: %s file not found\"", "the maps except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def", "as e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_'", "print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+ _time +\".tif\")", "< 60: if len(str(_min)) == 1: minStr = \"0\" + str(_min) else: minStr=str(_min)", "else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not", "-oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+'", "global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay = \"0\" +", "print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ):", "for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\",", "maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else: print", "addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply", "lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1:", "-kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "#\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle =", "#(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG print \"Exporting maps\" mappingMxd =", "file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e:", "lstfname except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global", "one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2)", "smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText", "elm.name == \"day\": elm.text=\"Map Reference no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath)", "#from email import Encoders #import shutil import config one_day = datetime.timedelta(days=1) #_today =", "os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to,", "try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname=", "recp, \"Frost Map for \" + str(_today + one_day), \"Please find the attached", "outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR,", "in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"'", "tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath", "print lstfname except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time):", "%s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as", "-if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0", "smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def", "+_year + _yrDay + \".\"+ _time +\".tif\") print lstfname except IOError as e:", "os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences", "lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+ _time +\".tif\") print lstfname", "[\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\",", "\"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print _thhr", "MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp", "+ _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG", "= _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir,", "= os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \" + str(_today", "and determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname,", "lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay", "#smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try:", "the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\",", "#Email the maps except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #.......................................................................................................................................................................", "e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1:", "targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated", "and the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime", "#from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate", "This email was automatically send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\",", "os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf'", "lstfname +_year + _yrDay + \".\"+ _time +\".tif\") print lstfname except IOError as", "e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath,", "found\" % inLst ) print(\"Or Error: %s file not found\" % inGeoloc) else:", "+_year + _yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname except IOError as", "inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0", "os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources,", "= arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map document print \"Adding frost", "_min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\" + str(_hr) while _min", "os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\"", "outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not", "the attached Frost map for \" + str(_today + one_day) + \". You", "= \"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay", "Occurrences on \" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today +", "text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from", "except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try:", "= MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] =", "#from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from", "= os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost", "print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer,", "dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for the TIF file", "= os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\"", "not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print", "filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013')", "_getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay", "try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime)", "\"Please find the attached Frost map for \" + str(_today + one_day) +", "where you can get the original hdfs and the resulting tif files #", "\"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print", "_yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR,", "tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" +", "MacOSX Pat Cappelaere - Vightel Corporation # # Here is the link where", "hrStr = \"0\" + str(_hr) while _min < 60: if len(str(_min)) == 1:", "\"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map", "-osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0", "BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir)", "lryIndx=lryIndx+1 #Add new Map title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"):", "+ one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day)) print", "2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year", "if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath", "f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment;", "print elm.text if elm.name == \"day\": elm.text=\"Map Reference no :- \" + _yrDay", "+ _yrDay + \".\"+ _time +\".tif\") print lstfname except IOError as e: print", "not found\" % inLst ) print(\"Or Error: %s file not found\" % inGeoloc)", "for \" + str(_today + one_day) + \". You can also find the", "\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject,", "_mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd,", "< 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\" + str(_hr)", "email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate #from email import Encoders #import", "_min < 60: if len(str(_min)) == 1: minStr = \"0\" + str(_min) else:", "2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year", "elm.text if elm.name == \"day\": elm.text=\"Map Reference no :- \" + _yrDay print", "= [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"", "the same map on http://172.16.17.32/frostmaps/ This email was automatically send by Frost Monitoring", "+ _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster", "_yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\" +", "_time +\".005.NRT.hdf\") print lstfname except IOError as e: print e return lstfname #.......................................................................................................................................................................", "to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"]", "\"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today", "one_day # PGC Debug _today = datetime.date(2014,10,2) _month = _today.month _day = _today.day", "if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\"", "layers print \"Applying symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df):", "if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling map\"", "Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\",", "): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile", "lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2:", "mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG print \"Exporting maps\" mappingMxd", "#maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay", "map on http://172.16.17.32/frostmaps/ This email was automatically send by Frost Monitoring System.\" ,", "datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2) _month =", "0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid", "'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle", "0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except", "-olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno,", "inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir,", "find the attached Frost map for \" + str(_today + one_day) + \".", "Raster Properties and determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\"", "smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[]", "Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" +", "\"Frost_\" + str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text,", "\"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer =", "'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for", "0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1", "\"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for", "df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling", "ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\",", "_month = _today.month _day = _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if", "e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname =", "smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname", "formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part =", "len(str(_min)) == 1: minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr", "fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else:", "frostMapTitle = \"Estimated Frost Occurrences on \" + str(_today + one_day) #ouputMapFileName =", "_yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year +", "\"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 =", "= arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay +", "subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today +", "\"output\", lstfname +_year + _yrDay + \".\"+ _time +\".tif\") print lstfname except IOError", "tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\"", "_yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR", "\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to,", "= arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the", "{1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname", "config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath =", "IOError as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc):", ") print(\"Or Error: %s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc)", "os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR,", "0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+", "str(_hr) while _min < 60: if len(str(_min)) == 1: minStr = \"0\" +", "0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+'", "Frost map for \" + str(_today + one_day) + \". You can also", "recp2, \"Frost Map for \" + str(_today + one_day), \"Please find the attached", "elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name", "From <NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor teaks for MacOSX Pat", "hdfs and the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import", "\".jpg\") #Email the maps except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror)", "lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as", "print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno,", "found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print \"I/O", "#recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\",", "_yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname except IOError as e: print", "= config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath", "1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling map\" for elm in", "+ \".\" + _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e", "_thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products", "= _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\"", "no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to", "type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date']", "_yrDay + \".\"+ _time +\".tif\") print lstfname except IOError as e: print e", "inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0", "\"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today + one_day), \"Please find", "Get Raster Properties and determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath +", "the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst", "Reference no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot", "#cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0", "#Process: Get Raster Properties and determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath", "def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'):", "in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath +", "else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr =", "_getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\")", "part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server)", "'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile =", "the original hdfs and the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import", "_yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year +", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0", "0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError", "if len(str(_min)) == 1: minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr =", "import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from email.Utils import", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\"", "as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def", "<NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor teaks for MacOSX Pat Cappelaere", "send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart()", "new Map title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name", "\"day\": elm.text=\"Map Reference no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del", "_year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd')", "+ \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e: print", "+\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the layers print", "arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title", "e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath", "% inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print \"I/O error({0}):", "except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay,", "+ str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[],", "15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print \"I/O error({0}):", "msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files:", "0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8'", "0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST", "_year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not", "# http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch #import arcpy", "_hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr =", "Frost Occurrences on \" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today", "send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for", "result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print", "\"Applying symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx", "\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map", "config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug _today =", "<EMAIL> # RCMRD Nairobi, Kenya # Minor teaks for MacOSX Pat Cappelaere -", "return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) ==", "not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD", "files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To']", "#....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay", "+\".tif\") print lstfname except IOError as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def", "print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if", "os.system(cmd) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime):", "str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR,", "os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except", "== 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname", "tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch", "str(_min) else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr", "'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir',", "\"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine", "\"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay +", ", filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today + one_day),", "60: if len(str(_min)) == 1: minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr", "+ \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and", "-osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO", "0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8'", "_yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e", "_yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir):", "+ _yrDay + \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay +", "+ \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue)", "# # Here is the link where you can get the original hdfs", "layers to the map document print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath", "# From <NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor teaks for MacOSX", "if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\" +", "\"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay,", "arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue) ==", "arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map document", "-13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror)", "server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] =", "os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname", "http://172.16.17.32/frostmaps/ This email was automatically send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\")", "the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import", "JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName", "fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue =", "hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD,", "print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\" + _time", "#cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0", "for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add", "print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle", "lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new", "_theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif =", "users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp", "lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname", "print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\")", "title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\":", "not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst ) print(\"Or Error: %s", "lstfname +_year + _yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname except IOError", "+ one_day), \"Please find the attached Frost map for \" + str(_today +", "\" + str(_today + one_day), \"Please find the attached Frost map for \"", "0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as", "#...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg", "assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to)", "df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map document print \"Adding", "#Send frost products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp =", "arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name == \"day\":", "inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0", "Debug _today = datetime.date(2014,10,2) _month = _today.month _day = _today.day _year = str(_today.year)", "subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] =", "server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today + one_day), \"Please find", "> 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling map\" for elm", "srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD", "== \"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except", "return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) ==", "\"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp =", "os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s", "for MacOSX Pat Cappelaere - Vightel Corporation # # Here is the link", "import datetime import glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart", "== 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname", "Here is the link where you can get the original hdfs and the", "str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"):", "+ _yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR =", "+ one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year,", "outPutFileName + \".jpg\") #Email the maps except IOError as e: print \"I/O error({0}):", "symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0]", "in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for the TIF", "MIMEBase #from email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate #from email import", "smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath)", "inGeoloc) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while", "str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2:", "time import datetime import glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import", "os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+ _time +\".tif\") print lstfname except", "-olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST", "same map on http://172.16.17.32/frostmaps/ This email was automatically send by Frost Monitoring System.\"", "text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today + one_day),", "while _min < 60: if len(str(_min)) == 1: minStr = \"0\" + str(_min)", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\"", "subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload(", "msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string())", "_yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay", "str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day))", "def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg =", "os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources,", "Encoders #import shutil import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day #", "file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process:", "#Add frost layers to the map document print \"Adding frost layers\" for tifFile", "layers\" for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile result", "cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0", "if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\"", "System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today +", "elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG print \"Exporting maps\"", "+ \".jpg\") #Email the maps except IOError as e: print \"I/O error({0}): {1}\".format(e.errno,", "error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay)", "_outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif'", "resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import glob,os,", "Map for \" + str(_today + one_day), \"Please find the attached Frost map", "frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile", "symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx >", "-osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0", "os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from,", "except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay,", "#_today = datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2) _month = _today.month", "#from email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate #from email import Encoders", "+ _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output')", "for f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition',", "_getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process:", "+ fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue", "outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except IOError as", "= formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part", "+ one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert", "as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir =", "by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \"", "\"geo\", lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError", "print lstfname except IOError as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird(", "one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay,", "maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email", "+ _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as e: print", "automatically send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map", "e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay)", "= \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year,", "COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in", "Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today", "map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text", "as e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A'", "_lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname)", "#import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from", "1: hrStr = \"0\" + str(_hr) while _min < 60: if len(str(_min)) ==", "Corporation # # Here is the link where you can get the original", "email was automatically send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2,", "= str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay =", "= result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost", "OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0", "\"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine the maxmum cell value #maxCellValue", "( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst ) print(\"Or Error:", "-osp=8' os.system(cmd) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def", "+ \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except IOError as e:", "#Process: Build Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay +", "e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try:", "os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD =", "python # # From <NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor teaks", "_year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print", "= \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay", "_lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if", "or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst ) print(\"Or", "arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer", "send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in", "== \"map\": elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map Reference no :-", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5", "0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd)", "print str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as", "{1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) ==", "= [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\",", "in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name ==", "\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from,", "e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try:", "IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #.....................................................................................................................................................................", "os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if", "-oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print \"I/O", "_yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\" + _time +\".005.NRT.hdf\")", "_getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc =", "arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the layers", "print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile +", "part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo()", "else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e: print \"I/O error({0}):", "_year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print", "\"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname)", "e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid", "_day = _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay =", "\"NONE\") #Process: Get Raster Properties and determine the maxmum cell value #maxCellValue =", "_yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay", "lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling map\" for", "print(\"Error: %s file not found\" % inLst ) print(\"Or Error: %s file not", "#_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch = [ouputMapFileName", "Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" +", "_hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\" +", "= os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst))", "try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0", "= os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname)", "#!/usr/bin/env python # # From <NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor", "#print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath)", "in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map", "except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0]", "Nairobi, Kenya # Minor teaks for MacOSX Pat Cappelaere - Vightel Corporation #", "if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources", "+ \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" +", "\" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and", "#..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df", "_min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to", "_mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO", "on \" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day)", "\"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile,", "fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine the maxmum", "+\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\",", "str(_today + one_day), \"Please find the attached Frost map for \" + str(_today", "Cappelaere - Vightel Corporation # # Here is the link where you can", "http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch #import arcpy #import", "+ \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer", "arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except IOError", "\"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if", "arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText", "_yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+ _time +\".tif\") print", "== 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname", "Error: %s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError", "lstfname except IOError as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST,", "+ \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e return", "IOError as e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year", "datetime.date(2014,10,2) _month = _today.month _day = _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7])", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG", "map for \" + str(_today + one_day) + \". You can also find", "can also find the same map on http://172.16.17.32/frostmaps/ This email was automatically send", "maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst =", "\"Adding frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print", "mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the", "#.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname,", "arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get", "len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir =", "# Minor teaks for MacOSX Pat Cappelaere - Vightel Corporation # # Here", "#import shutil import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC", "=[] try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids", "' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0", "+ \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" +", "print lstfname except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time):", "e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif", "= os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day)) print (_today) #...................................................................................................................................................................... def", "RCMRD Nairobi, Kenya # Minor teaks for MacOSX Pat Cappelaere - Vightel Corporation", "try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And", "while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\"", "fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath +", "if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay,", "_yrDay + \"\\\\output\\\\\" ): print tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\"", "#ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\"", "'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath)", "return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd", "= _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc", "file not found\" % inLst ) print(\"Or Error: %s file not found\" %", "Pat Cappelaere - Vightel Corporation # # Here is the link where you", "-osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO", "\".\" + _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e return", "print(\"Or Error: %s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except", "= \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" +", "type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True)", "= send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text)", "#addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to", "e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay)", "teaks for MacOSX Pat Cappelaere - Vightel Corporation # # Here is the", "-osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid", "\"0\" + str(_hr) while _min < 60: if len(str(_min)) == 1: minStr =", "+ str(_today + one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today +", "str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname)", "PGC Debug _today = datetime.date(2014,10,2) _month = _today.month _day = _today.day _year =", "#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime)", "\"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum", "TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\")", "and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd,", "-if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0", "os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst ) print(\"Or Error: %s file", "if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\"", "error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle,", "elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir", "\"F\" frostFiles.append(fname) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles", "_yrDay else: _yrDay=_yrDay BASE_DIR = config.FROST_DIR outPtDir = os.path.join(BASE_DIR, _year, _yrDay, 'output') if", "= arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0)", "0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + '", "inLst ) print(\"Or Error: %s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst, outTif,", "+ str(_min) else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5", "as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24:", "import glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase", "msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for", "global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay = \"0\" +", "arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\"", "'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on", "minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr)", "len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\",", "+\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\",", "lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst", "# Here is the link where you can get the original hdfs and", "email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate #from", "+ \". You can also find the same map on http://172.16.17.32/frostmaps/ This email", "to the map document print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath +", "+ _yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\":", "5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT", "\". You can also find the same map on http://172.16.17.32/frostmaps/ This email was", "#send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today + one_day), \"Please find the", "def _theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif", "#\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \"", "_yrDay + \"\\\\output\\\\\" + fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties", "str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e:", "_yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+ _time", "-sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "+ \".\"+ _time +\".tif\") print lstfname except IOError as e: print e return", "frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd =", "files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today + one_day), \"Please", "0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + '", "_getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay = \"0\"", "% inLst ) print(\"Or Error: %s file not found\" % inGeoloc) else: _mrtSwath2Gird(inLst,", "+ str(_today + one_day), \"Please find the attached Frost map for \" +", "len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\",", "_yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print", "outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers", "\"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine the maxmum cell", "#'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not", "Vightel Corporation # # Here is the link where you can get the", "del mxd #Exprot to pdf and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath)", "send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" + str(_today", "_yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "ouputMapFileName) #Send frost products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp", "#\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \" + str(_today + one_day) #ouputMapFileName", "email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from email.Utils", "arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map document print \"Adding frost layers\"", "#Exprot to pdf and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName", "inGeoloc) else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno,", "\"Layers\")[0] #Add frost layers to the map document print \"Adding frost layers\" for", "+ one_day) + \". You can also find the same map on http://172.16.17.32/frostmaps/", "os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or", "+ _yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname except IOError as e:", "one_day), \"Please find the attached Frost map for \" + str(_today + one_day)", "mxd #Exprot to pdf and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd,", "+ _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+", "= [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp,", "_geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif =", "MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject", "def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay =", "MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import MIMEText #from email.Utils import COMMASPACE,", "\"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError", "str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror)", "def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay =", "2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year", "lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT", "0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e:", "targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName", "\"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\")", "if len(str(_hr)) == 1: hrStr = \"0\" + str(_hr) while _min < 60:", "Map title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name ==", "os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \" + str(_today +", "== 1: hrStr = \"0\" + str(_hr) while _min < 60: if len(str(_min))", "os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources')", "print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if", "_today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" +", "as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year", "result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\")", "#Apply Frost symbology to the layers print \"Applying symbology\" lryIndx = 0 for", "0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+", "len(str(_hr)) == 1: hrStr = \"0\" + str(_hr) while _min < 60: if", "frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build", "_getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif)", "print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG print \"Exporting", "#....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay", "attached Frost map for \" + str(_today + one_day) + \". You can", "+ fname, \"INCLUDE_SUBDIRECTORIES\", \"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine the", "datetime import glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from", "_thhr = hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD,", "lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay", "_getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay = \"0\"", "e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2:", "-of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0", "srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir,", "_year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print", "arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd,", "0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST +", "#recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\",", "tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the layers print \"Applying symbology\"", "tifFile result = arcpy.MakeRasterLayer_management(srcPath + _yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\")", "IOError as e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global _yrDay, _year", "+\".005.NRT.hdf\") print lstfname except IOError as e: print e return lstfname #....................................................................................................................................................................... def", "#Add new Map title print \"Titling map\" for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if", "= hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile,", "'*.tif'): #Process: Build Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay", "{1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName):", "= os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources = os.path.join(BASE_DIR, 'resources') templateMXD =", "= \"0\" + str(_hr) while _min < 60: if len(str(_min)) == 1: minStr", "[\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ]", "+ str(_today + one_day) + \". You can also find the same map", "#send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \" +", "def _getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay =", "import Encoders #import shutil import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day", "] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"):", "+ ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0", "# RCMRD Nairobi, Kenya # Minor teaks for MacOSX Pat Cappelaere - Vightel", "else: _mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror)", "_today.month _day = _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay", "dirList=os.listdir(tifPath) for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics", "\"Estimated Frost Occurrences on \" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" +", "#....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay", "arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the layers print \"Applying symbology\" lryIndx", "#'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not", "+ str(_hr) while _min < 60: if len(str(_min)) == 1: minStr = \"0\"", "you can get the original hdfs and the resulting tif files # http://172.16.17.32/frostmaps/", "for fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for", "-oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug _today", "IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir", "except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global", "msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(", "elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map Reference no :- \" +", "symbologyLayerFile = os.path.join(resources, 'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \" +", "find the same map on http://172.16.17.32/frostmaps/ This email was automatically send by Frost", "[\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost", "+ minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle,", "str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\"", "\".\"+ _time +\".tif\") print lstfname except IOError as e: print e return lstfname", "frost layers to the map document print \"Adding frost layers\" for tifFile in", "\".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df,", "+ \"F\" frostFiles.append(fname) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return", "= datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2) _month = _today.month _day", "to the layers print \"Applying symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd,", "= os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error:", "= datetime.date(2014,10,2) _month = _today.month _day = _today.day _year = str(_today.year) _yrDay =", "print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr)", "assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] =", "e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A'", "elm.text=\"Map Reference no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd", "the link where you can get the original hdfs and the resulting tif", "\"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text,", "-gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr", "( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" %", "_year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay", "#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr", "(_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list", "_yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf and JPG print", "24: _min=0 hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\" + str(_hr) while", "map document print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay +", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0", "msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read()", "msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application',", "\"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay +", "# PGC Debug _today = datetime.date(2014,10,2) _month = _today.month _day = _today.day _year", "smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList: if", "-oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+'", "+ _yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer =", "elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map Reference no", "_mrtSwath2Gird(inLst, outTif, inGeoloc) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch = [ouputMapFileName +\".pdf\",", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG", "0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+'", "-gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "print \"Applying symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if", "glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import", "global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) == 2: _yrDay = \"0\" +", "\"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else: _yrDay=_yrDay BASE_DIR", "#'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif = os.path.join(lstDir, _outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if (", "+ _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay + \".\"+", "+_year + _yrDay + \".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as e:", "_yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year +", "not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst", "lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\" + _time +\".005.NRT.hdf\") print", "0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST", "len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\",", "on http://172.16.17.32/frostmaps/ This email was automatically send by Frost Monitoring System.\" , filesToAttch,", "formatdate #from email import Encoders #import shutil import config one_day = datetime.timedelta(days=1) #_today", "send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From']", "Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls()", "_yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print", "open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1)", "products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\",", "+ fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\"", "maps except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time):", "+ _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e return lstfname", "_getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf' outTif", "_yrDay + \"\\\\output\\\\\" + tifFile, tifFile + \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0)", "error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if len(str(_hr))", "ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day)) print (_today) #......................................................................................................................................................................", "= arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue)", "_geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file", "0.0\" -oul=\"14.5 15.5\" -olr=\"51.5 -13.5\" -osst=LAT_LONG -osp=8' os.system(cmd) except IOError as e: print", "And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\" + fname,", "result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology", "\"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0 hrStr=str(_hr) if", "arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except IOError as e: print \"I/O", "MIMEText #from email.Utils import COMMASPACE, formatdate #from email import Encoders #import shutil import", "#from email.Utils import COMMASPACE, formatdate #from email import Encoders #import shutil import config", "import MIMEBase #from email.MIMEText import MIMEText #from email.Utils import COMMASPACE, formatdate #from email", "_year, _yrDay, \"Frost_\" + str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to,", "for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\" ): print tifFile result =", "IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay,", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\"", "_outPuttif) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\output\\\\output1.tif' inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or (", "= COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f", "if elm.name == \"day\": elm.text=\"Map Reference no :- \" + _yrDay print elm.text", "shutil import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug", "= MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part)", "os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)): print(\"Error: %s file not found\" % inLst )", "outTif, inGeoloc) except IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0", "== 1: minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr +", "\"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): #send_mail(\"<EMAIL>\", recp, \"Frost Map for \"", "\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"]", "smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles", "def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST -kk=NN", "smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath):", "print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf", "arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except", "= datetime.timedelta(days=1) #_today = datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2) _month", "\"Frost Map for \" + str(_today + one_day), \"Please find the attached Frost", "len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay", "Properties and determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" +", "= [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\",", "def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df =", "as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try:", "http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch #import arcpy #import smtplib #from", "email.Utils import COMMASPACE, formatdate #from email import Encoders #import shutil import config one_day", "-olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST", "error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname = _getLSTFile(theTime)", "\"lst\", lstfname +_year + _yrDay + \".\" + _time +\".005.NRT.hdf\") print lstfname except", "_yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay", "inGeoloc = os.path.join(lstDir, _geoLocFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf' if ( not os.path.isfile(inLst)) or ( not os.path.isfile(inGeoloc)):", "_yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay + \".\"+ _time", "resources = os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd')", "= srcPath _lstFname = _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst =", "#send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today + one_day), \"Please find the", "Kenya # Minor teaks for MacOSX Pat Cappelaere - Vightel Corporation # #", "fname in dirList: if fnmatch.fnmatch(fname, '*.tif'): #Process: Build Pyramids And Statistics for the", "== \"day\": elm.text=\"Map Reference no :- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\")", "_yrDay = \"00\" + _yrDay elif len(_yrDay)==2: _yrDay = \"0\" + _yrDay else:", "get the original hdfs and the resulting tif files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/", "#---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf -off=GEOTIFF_FMT -sds=LST", "os.path.join(BASE_DIR, 'resources') templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile", "target_mxdPath, MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add", "Frost symbology to the layers print \"Applying symbology\" lryIndx = 0 for lyr", "\"<EMAIL>\" ] #recp2 = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #send_mail(send_from, send_to, subject, text, files=[],", "-off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "datetime.date.today()- one_day # PGC Debug _today = datetime.date(2014,10,2) _month = _today.month _day =", "= _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch", "= \"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print", "email import Encoders #import shutil import config one_day = datetime.timedelta(days=1) #_today = datetime.date.today()-", "lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try: if len(_yrDay) == 2:", "addLayer, \"BOTTOM\") #Apply Frost symbology to the layers print \"Applying symbology\" lryIndx =", "if elm.name == \"map\": elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map Reference", "-5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN", "import COMMASPACE, formatdate #from email import Encoders #import shutil import config one_day =", "_today = datetime.date(2014,10,2) _month = _today.month _day = _today.day _year = str(_today.year) _yrDay", "print \"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer,", "\"map\": elm.text=MapTitle print elm.text if elm.name == \"day\": elm.text=\"Map Reference no :- \"", ":- \" + _yrDay print elm.text mxd.saveACopy(target_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost3.mxd\") del mxd #Exprot to pdf", "\"I/O error({0}): {1}\".format(e.errno, e.strerror) return frostFiles #print _getFrostFiles(srcPath)[0] #..................................................................................................................................................................... def _mapping(tmp_mxdPath, symbologyLayer, target_mxdPath,", "print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try:", "\"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\" ] #recp2", "one_day) + \". You can also find the same map on http://172.16.17.32/frostmaps/ This", "frost products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\",", "= os.path.join(BASE_DIR, _year, _yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year)", "= arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps", "# # From <NAME>, <EMAIL> # RCMRD Nairobi, Kenya # Minor teaks for", "lstfname='MYD03.A' try: if len(_yrDay) == 2: _yrDay = \"0\" + _yrDay print _yrDay", "\".\"+ _time +\".005.NRT.hdf\") print lstfname except IOError as e: print e return lstfname", ") for f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part)", "= \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay", "\"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) +", "_hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch =", "{1}\".format(e.errno, e.strerror) #....................................................................................................................................................................... def _getLSTFile(_time): global _yrDay, _year lstfname='MYD11_L2.A' try: if len(_yrDay) ==", "also find the same map on http://172.16.17.32/frostmaps/ This email was automatically send by", "rst = arcpy.Raster(srcPath + _yrDay + \"\\\\output\\\\\" + fname) maxCellValue = rst.maximum if", "to pdf and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName +", "\"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname =", "e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr < 24: _min=0", "frostMapTitle, ouputMapFileName) #Send frost products to users #filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"]", "determine the maxmum cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\")", "the map document print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay", "try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to", "_theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send", "msg.as_string()) smtp.close() #.............................................................................................................................. def _getFrostFiles(tifPath): frostFiles =[] try: dirList=os.listdir(tifPath) for fname in dirList:", "document print \"Adding frost layers\" for tifFile in _getFrostFiles(srcPath + _yrDay + \"\\\\output\\\\\"", "= \"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"output\", lstfname +_year + _yrDay", "+ str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName =", "= os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources, 'LST2.lyr')", "send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) )", "= arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map", "e: print e return lstfname #....................................................................................................................................................................... def _getGeolocationFile(_time): global _yrDay, _year lstfname='MYD03.A' try:", "\"BOTTOM\") #Apply Frost symbology to the layers print \"Applying symbology\" lryIndx = 0", "\"T\" else: print str(maxCellValue) + \"F\" frostFiles.append(fname) except IOError as e: print \"I/O", "% os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from,", "_getOutputFile(_time): global _yrDay, _year lstfname='Frost_' try: if len(_yrDay) == 2: _yrDay = \"0\"", "link where you can get the original hdfs and the resulting tif files", ") Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo()", "= _getLSTFile(theTime) _geoLocFname = _getGeolocationFile(theTime) _outPuttif = _getOutputFile(theTime) inLst = os.path.join(lstDir, _lstFname) #'D:\\\\Modis_LST\\\\2013\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf'", "except IOError as e: print e return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF,", "MapTitle, outPutFileName): try: mxd = arcpy.mapping.MapDocument(tmp_mxdPath) #(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost", "= rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue)", "is the link where you can get the original hdfs and the resulting", "-of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN -oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0", "not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath): os.makedirs(srcPath) resources =", "= subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', \"octet-stream\")", "print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName +", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"14.5", "_hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost products to users", "#recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\",", "\" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\" + str(_today + one_day) ouputMapFileName", "smtp = smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()", "= \"Estimated Frost Occurrences on \" + str(_today + one_day) #ouputMapFileName = \"H:\\\\Frost\\\\_workingDir\\\\maps\\\\Frost_\"", "rst.maximum if str(maxCellValue) == \"0.0\": print str(maxCellValue) + \"T\" else: print str(maxCellValue) +", "one_day) ouputMapFileName = os.path.join(BASE_DIR, _year, _yrDay, \"Frost_\" + str(_today + one_day)) print (_today)", "#filesToAttch = [ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp =", "lstfname except IOError as e: print e return lstfname #....................................................................................................................................................................... def _getOutputFile(_time): global", "files # http://172.16.17.32/frostmaps/ # http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch #import", "'LST2.lyr') #\"H:\\\\Frost\\\\_resources\\\\LST2.lyr\" frostMapTitle = \"Estimated Frost Occurrences on \" + str(_today + one_day)", "\"BUILD_PYRAMIDS\", \"CALCULATE_STATISTICS\", \"NONE\") #Process: Get Raster Properties and determine the maxmum cell value", "= _today.month _day = _today.day _year = str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1:", "= str(_today.year) _yrDay = str(_today.timetuple()[7]) if len(_yrDay)==1: _yrDay = \"00\" + _yrDay elif", "IOError as e: print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- _hr=0 while _hr <", "fnmatch #import arcpy #import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase", "minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName)", "files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' %", "+ \".lyr\") print result.getOutput(0) addLayer = result.getOutput(0) #addLayer = arcpy.mapping.Layer(srcPath +\"\\\\\" + tifFile)", "# http://172.16.17.32/frostmaps/ import time import datetime import glob,os, fnmatch #import arcpy #import smtplib", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\"", "-oproj=GEO -oprm=\"0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0", "0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\"", "can get the original hdfs and the resulting tif files # http://172.16.17.32/frostmaps/ #", "0.0 0.0 0.0\" -oul=\"33.0 5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST +", "#(\"D:\\\\Modis_LST\\\\Frost\\\\Frost2.mxd\") df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] #Add frost layers to the map document print", "import time import datetime import glob,os, fnmatch #import arcpy #import smtplib #from email.MIMEMultipart", "_time +\".tif\") print lstfname except IOError as e: print e return lstfname #----------------------------------------------------------------------------------------------------------------------------------------------------------------------", "- Vightel Corporation # # Here is the link where you can get", "hrStr=str(_hr) if len(str(_hr)) == 1: hrStr = \"0\" + str(_hr) while _min <", "You can also find the same map on http://172.16.17.32/frostmaps/ This email was automatically", "1: minStr = \"0\" + str(_min) else: minStr=str(_min) _thhr = hrStr + minStr", "value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath +", "cell value #maxCellValue = arcpy.GetRasterProperties_management(srcPath + \"\\\\\" + fname, \"MAXIMUM\") rst = arcpy.Raster(srcPath", "+ tifFile) arcpy.mapping.AddLayer(df, addLayer, \"BOTTOM\") #Apply Frost symbology to the layers print \"Applying", "for \" + str(_today + one_day), \"Please find the attached Frost map for", "-5.5\" -osst=LAT_LONG -osp=8' #cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT -sds=LST -kk=NN", "was automatically send by Frost Monitoring System.\" , filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost", "symbology to the layers print \"Applying symbology\" lryIndx = 0 for lyr in", "= smtplib.SMTP(server) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() #smtp.ehlo() smtp.login('servir', 'servir2013') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() #..............................................................................................................................", "the layers print \"Applying symbology\" lryIndx = 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\",", "pdf and JPG print \"Exporting maps\" mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\")", "one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject, text, files=[], server=\"192.168.0.243\"): assert type(send_to)==list", "part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f))", "\".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the maps except IOError as e: print", "minStr=str(_min) _thhr = hrStr + minStr _theMain(_thhr) #print _thhr _min=_min+5 _hr = _hr+1", "#print _thhr _min=_min+5 _hr = _hr+1 #_mapping(templateMXD, symbologyLayerFile, targetMXD, frostMapTitle, ouputMapFileName) #Send frost", "\" + str(_today + one_day) + \". You can also find the same", "5.5\" -olr=\"42.0 -5.5\" -osst=LAT_LONG -osp=8' cmd='swath2grid -if='+ inPutLST + ' -of='+OutPuTIF+' -gf='+inPutGeoloc+' -off=GEOTIFF_FMT", "print \"I/O error({0}): {1}\".format(e.errno, e.strerror) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _theMain(theTime): try: lstDir = srcPath _lstFname", "MIMEText(text) ) for f in files: part = MIMEBase('application', \"octet-stream\") part.set_payload( open(f,\"rb\").read() )", "+ _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"lst\", lstfname +_year + _yrDay + \".\"", "filesToAttch, \"192.168.0.243:25\") #send_mail(\"<EMAIL>\", recp2, \"Frost Map for \" + str(_today + one_day), \"Please", "COMMASPACE, formatdate #from email import Encoders #import shutil import config one_day = datetime.timedelta(days=1)", "_yrDay, 'output') if not os.path.exists(outPtDir): os.makedirs(outPtDir) srcPath = os.path.join(BASE_DIR, _year) if not os.path.exists(srcPath):", "\"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer) lryIndx=lryIndx+1 #Add new Map title print", "mappingMxd = arcpy.mapping.MapDocument(target_mxdPath) arcpy.mapping.ExportToPDF(mappingMxd, outPutFileName + \".pdf\") arcpy.mapping.ExportToJPEG(mappingMxd, outPutFileName + \".jpg\") #Email the", "_yrDay, \"Frost_\" + str(_today + one_day)) print (_today) #...................................................................................................................................................................... def send_mail(send_from, send_to, subject,", "Build Pyramids And Statistics for the TIF file arcpy.BuildPyramidsandStatistics_management(srcPath + _yrDay + \"\\\\output\\\\\"", "\"0\" + _yrDay print _yrDay lstfname= os.path.join(_yrDay, \"geo\", lstfname +_year + _yrDay +", "return lstfname #---------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _mrtSwath2Gird( inPutLST, OutPuTIF, inPutGeoloc): try: #cmd1='swath2grid -if=D:\\\\Modis_LST\\\\2014\\\\027\\\\lst\\\\MYD11_L2.A2013027.0030.005.NRT.hdf -of=D:\\\\Modis_LST\\\\2014\\\\027\\\\output\\\\output1.tif -gf=D:\\\\Modis_LST\\\\2014\\\\027\\\\geo\\\\MYD03.A2013027.0030.005.NRT.hdf", "#import smtplib #from email.MIMEMultipart import MIMEMultipart #from email.MIMEBase import MIMEBase #from email.MIMEText import", "templateMXD = os.path.join(resources, 'Frost2.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost2.mxd\" targetMXD = os.path.join(resources, 'Frost3.mxd') #\"H:\\\\Frost\\\\_resources\\\\Frost3.mxd\" symbologyLayerFile = os.path.join(resources,", "= 0 for lyr in arcpy.mapping.ListLayers(mxd, \"\", df): if lryIndx > 1: arcpy.ApplySymbologyFromLayer_management(lyr,symbologyLayer)", "[ouputMapFileName +\".pdf\", ouputMapFileName +\".jpg\"] #recp = [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"] #recp = [\"<EMAIL>\", \"<EMAIL>\",", "import MIMEText #from email.Utils import COMMASPACE, formatdate #from email import Encoders #import shutil", "str(_today + one_day) + \". You can also find the same map on", "for elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): if elm.name == \"map\": elm.text=MapTitle print elm.text if", "Minor teaks for MacOSX Pat Cappelaere - Vightel Corporation # # Here is" ]
[ "try: index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2 return PSD", "freqs = np.linspace(start = start_freq, stop = stop_freq, num = self.resolution) # Samples", "window # Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log", "= self.sample() # Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq =", "Receiver class. This needs receiving parameters and will receive data from the SDR", "receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD = self.sample() # Observed", "= np.linspace(start = start_freq, stop = stop_freq, num = self.resolution) # Samples a", "# Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz", "For some reason the SDR doesn't want to set the offset PPM to", "self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For some reason the SDR doesn't", "num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000", "self.sample() # Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq", "PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD =", "samples each...') data_PSD = self.sample() # Observed frequency range start_freq = self.sdr.center_freq -", "np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter", "estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor =", "samples * window # Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked =", "for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if samples", "freqs, SNR_median # Returns numpy array with PSD values averaged from \"num_FFT\" datasets", "from SDR, processes and writes it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution}", "PSD): try: index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2 return", "self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum # Close the SDR self.sdr.close() return", "data from the SDR class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med):", "= self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop = stop_freq, num", "ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate", "# Returns numpy array with PSD values averaged from \"num_FFT\" datasets def sample(self):", "noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median", "Calculates SNR from spectrum and H-line SNR def estimate_SNR(self, data, blank): SNR =", "250000Hz ''' # Receiver class. This needs receiving parameters and will receive data", "sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter for rfi-removal def median(self,", "self.num_med != 0 else SNR_spectrum # Close the SDR self.sdr.close() return freqs, SNR_median", "# Samples a blank spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq +", "index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2 return PSD except:", "self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med = num_med # Reads data from", "num_FFT, num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq =", "num = self.resolution) # Samples a blank spectrum to callibrate spectrum with. self.sdr.center_freq", "1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class. This needs receiving parameters and", "= start_freq, stop = stop_freq, num = self.resolution) # Samples a blank spectrum", "num_med # Reads data from SDR, processes and writes it def receive(self): print(f'Receiving", "filter for rfi-removal def median(self, data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med])", "reason the SDR doesn't want to set the offset PPM to 0 so", "numpy array with PSD values averaged from \"num_FFT\" datasets def sample(self): counter =", "SDR class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr()", "= stop_freq, num = self.resolution) # Samples a blank spectrum to callibrate spectrum", "__init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate", "blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum # Close the", "Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz", "self.num_FFT = num_FFT self.num_med = num_med # Reads data from SDR, processes and", "datasets def sample(self): counter = 0.0 PSD_summed = (0, )* self.resolution while (counter", "self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq,", "self.sdr.center_freq = 1420405000 # For some reason the SDR doesn't want to set", "samples = self.sdr.read_samples(self.resolution) # Applies window to samples in time domain before performing", "Returns numpy array with PSD values averaged from \"num_FFT\" datasets def sample(self): counter", "= sample_rate self.sdr.center_freq = 1420405000 # For some reason the SDR doesn't want", "= 1420405000 # For some reason the SDR doesn't want to set the", "def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD = self.sample() #", "1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed) return averaged_PSD # Calculates SNR", "self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med", "= self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum # Close the SDR self.sdr.close()", "for rfi-removal def median(self, data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return", "sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate =", "ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT", "Applies window to samples in time domain before performing FFT window = np.hanning(self.resolution)", "SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR =", "Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR #", "!= 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT =", "median(self, data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks", "PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter +=", "= tuple(sample/counter for sample in PSD_summed) return averaged_PSD # Calculates SNR from spectrum", "= (0, )* self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies", "0.0 PSD_summed = (0, )* self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution)", "def sample(self): counter = 0.0 PSD_summed = (0, )* self.resolution while (counter <", "and will receive data from the SDR class Receiver: def __init__(self, sample_rate, ppm,", "class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() #", "writes it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD =", "return data # Checks if samples have been dropped and replaces 0.0 with", "= data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else", "= list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2 return PSD except: return", "the SDR class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr =", "self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD,", "in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if samples have been", "Samples a blank spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000", "configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For some reason the", "SDR self.sdr.close() return freqs, SNR_median # Returns numpy array with PSD values averaged", "shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter for rfi-removal def median(self, data):", "SDR doesn't want to set the offset PPM to 0 so we avoid", "data_PSD = self.sample() # Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq", "= SNR-noise_floor return shifted_SNR # Median filter for rfi-removal def median(self, data): for", "= np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor", "list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2 return PSD except: return PSD", "from spectrum and H-line SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) #", "been dropped and replaces 0.0 with next value def check_for_zero(self, PSD): try: index", "import numpy as np from rtlsdr import RtlSdr import matplotlib.pyplot as plt #", "= 0.0 PSD_summed = (0, )* self.resolution while (counter < self.num_FFT): samples =", "= num_med # Reads data from SDR, processes and writes it def receive(self):", "self.sdr.read_samples(self.resolution) # Applies window to samples in time domain before performing FFT window", "\"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed = (0, )* self.resolution while", "def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure SDR", "num_FFT self.num_med = num_med # Reads data from SDR, processes and writes it", "sample_rate self.sdr.center_freq = 1420405000 # For some reason the SDR doesn't want to", "= self.sdr.read_samples(self.resolution) # Applies window to samples in time domain before performing FFT", "self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to samples in time domain before", "numpy as np from rtlsdr import RtlSdr import matplotlib.pyplot as plt # Available", "= np.mean(data[i:i+self.num_med]) return data # Checks if samples have been dropped and replaces", "self.sdr.close() return freqs, SNR_median # Returns numpy array with PSD values averaged from", "before performing FFT window = np.hanning(self.resolution) windowed_samples = samples * window # Perform", "Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked)", "self.num_med = num_med # Reads data from SDR, processes and writes it def", "stop_freq, num = self.resolution) # Samples a blank spectrum to callibrate spectrum with.", "to samples in time domain before performing FFT window = np.hanning(self.resolution) windowed_samples =", "SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum # Close the SDR", "1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class. This needs receiving", "return averaged_PSD # Calculates SNR from spectrum and H-line SNR def estimate_SNR(self, data,", "= tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for sample in", "= self.resolution) # Samples a blank spectrum to callibrate spectrum with. self.sdr.center_freq =", "np.mean(data[i:i+self.num_med]) return data # Checks if samples have been dropped and replaces 0.0", "as np from rtlsdr import RtlSdr import matplotlib.pyplot as plt # Available sample", "replaces 0.0 with next value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped", "* window # Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD)", "np.linspace(start = start_freq, stop = stop_freq, num = self.resolution) # Samples a blank", "we avoid that if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto'", "< self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to samples in time domain", "values averaged from \"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed = (0,", "that if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution =", "SDR, processes and writes it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples", "= self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum)", "H-line SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor", "if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution = 2**resolution", "import operator import math import numpy as np from rtlsdr import RtlSdr import", "SNR from spectrum and H-line SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank)", "check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] = (PSD[index+1]+PSD[index-1])/2", "window = np.hanning(self.resolution) windowed_samples = samples * window # Perform FFT and PSD-analysis", "self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med = num_med #", "want to set the offset PPM to 0 so we avoid that if", "noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter for rfi-removal", "FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed", "# For some reason the SDR doesn't want to set the offset PPM", "self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop =", "blank spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD =", "0 else SNR_spectrum # Close the SDR self.sdr.close() return freqs, SNR_median # Returns", "callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum =", "np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed) return averaged_PSD", "Reads data from SDR, processes and writes it def receive(self): print(f'Receiving {self.num_FFT} bins", "PPM to 0 so we avoid that if ppm != 0: self.sdr.freq_correction =", "the offset PPM to 0 so we avoid that if ppm != 0:", "return freqs, SNR_median # Returns numpy array with PSD values averaged from \"num_FFT\"", "# Calculates SNR from spectrum and H-line SNR def estimate_SNR(self, data, blank): SNR", "sample in PSD_summed) return averaged_PSD # Calculates SNR from spectrum and H-line SNR", "= self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start =", "Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2", "and writes it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD", "self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop = stop_freq, num = self.resolution) #", "2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class.", "# Checks if samples have been dropped and replaces 0.0 with next value", "self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD", "dropped and replaces 0.0 with next value def check_for_zero(self, PSD): try: index =", "stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop = stop_freq,", "matplotlib.pyplot as plt # Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz", "frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs", "0.0 with next value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample", "self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank =", "bins of {self.resolution} samples each...') data_PSD = self.sample() # Observed frequency range start_freq", "2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class. This needs", "PSD_summed) return averaged_PSD # Calculates SNR from spectrum and H-line SNR def estimate_SNR(self,", "estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter for", "(0, )* self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window", "# Applies window to samples in time domain before performing FFT window =", "to set the offset PPM to 0 so we avoid that if ppm", "spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data", "# Median filter for rfi-removal def median(self, data): for i in range(len(data)): data[i]", "# Close the SDR self.sdr.close() return freqs, SNR_median # Returns numpy array with", "RtlSdr import matplotlib.pyplot as plt # Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz", "rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz", "if self.num_med != 0 else SNR_spectrum # Close the SDR self.sdr.close() return freqs,", "Checks if samples have been dropped and replaces 0.0 with next value def", "10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for", "+ self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop = stop_freq, num = self.resolution)", "will receive data from the SDR class Receiver: def __init__(self, sample_rate, ppm, resolution,", "counter = 0.0 PSD_summed = (0, )* self.resolution while (counter < self.num_FFT): samples", "so we avoid that if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain =", "avoid that if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution", "2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class. This", "else SNR_spectrum # Close the SDR self.sdr.close() return freqs, SNR_median # Returns numpy", "sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz", "Median filter for rfi-removal def median(self, data): for i in range(len(data)): data[i] =", "1024000Hz 900001Hz 250000Hz ''' # Receiver class. This needs receiving parameters and will", "the SDR self.sdr.close() return freqs, SNR_median # Returns numpy array with PSD values", "PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed,", "+ 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD)", "def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor", "averaged_PSD # Calculates SNR from spectrum and H-line SNR def estimate_SNR(self, data, blank):", "{self.resolution} samples each...') data_PSD = self.sample() # Observed frequency range start_freq = self.sdr.center_freq", "with PSD values averaged from \"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed", "if samples have been dropped and replaces 0.0 with next value def check_for_zero(self,", "array with PSD values averaged from \"num_FFT\" datasets def sample(self): counter = 0.0", "1420405000 # For some reason the SDR doesn't want to set the offset", "PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add,", "= ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med =", "math import numpy as np from rtlsdr import RtlSdr import matplotlib.pyplot as plt", "''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz '''", "= 2**resolution self.num_FFT = num_FFT self.num_med = num_med # Reads data from SDR,", "in PSD_summed) return averaged_PSD # Calculates SNR from spectrum and H-line SNR def", "start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start", "processes and writes it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...')", "window to samples in time domain before performing FFT window = np.hanning(self.resolution) windowed_samples", "doesn't want to set the offset PPM to 0 so we avoid that", "This needs receiving parameters and will receive data from the SDR class Receiver:", "# Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR", "import math import numpy as np from rtlsdr import RtlSdr import matplotlib.pyplot as", "self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if", "+= 1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed) return averaged_PSD # Calculates", "and replaces 0.0 with next value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0)", "= self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0", "data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if samples have been dropped and", "time domain before performing FFT window = np.hanning(self.resolution) windowed_samples = samples * window", "0: self.sdr.freq_correction = ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT", "SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate:", "= num_FFT self.num_med = num_med # Reads data from SDR, processes and writes", "= blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum # Close", "spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample()", "{self.num_FFT} bins of {self.resolution} samples each...') data_PSD = self.sample() # Observed frequency range", "resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq", "np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return", "offset PPM to 0 so we avoid that if ppm != 0: self.sdr.freq_correction", "from rtlsdr import RtlSdr import matplotlib.pyplot as plt # Available sample rates '''", "SNR_spectrum # Close the SDR self.sdr.close() return freqs, SNR_median # Returns numpy array", "while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to samples in", "Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr = RtlSdr() # configure", "'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med = num_med # Reads data", "2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver", "0 so we avoid that if ppm != 0: self.sdr.freq_correction = ppm self.sdr.gain", "set the offset PPM to 0 so we avoid that if ppm !=", "= RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For", "PSD values averaged from \"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed =", ")* self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to", "= samples * window # Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked", "with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data =", "self.sdr = RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 #", "stop = stop_freq, num = self.resolution) # Samples a blank spectrum to callibrate", "SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For some reason the SDR", "def median(self, data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data #", "self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0", "blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR", "!= 0 else SNR_spectrum # Close the SDR self.sdr.close() return freqs, SNR_median #", "SNR_median # Returns numpy array with PSD values averaged from \"num_FFT\" datasets def", "it def receive(self): print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD = self.sample()", "= np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log)))", "domain before performing FFT window = np.hanning(self.resolution) windowed_samples = samples * window #", "receiving parameters and will receive data from the SDR class Receiver: def __init__(self,", "data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum", "= sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter for rfi-removal def", "the SDR doesn't want to set the offset PPM to 0 so we", "SNR-noise_floor return shifted_SNR # Median filter for rfi-removal def median(self, data): for i", "import RtlSdr import matplotlib.pyplot as plt # Available sample rates ''' 3200000Hz 2800000Hz", "# Receiver class. This needs receiving parameters and will receive data from the", "PSD_summed = (0, )* self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) #", "900001Hz 250000Hz ''' # Receiver class. This needs receiving parameters and will receive", "tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed)", "# Reads data from SDR, processes and writes it def receive(self): print(f'Receiving {self.num_FFT}", "spectrum and H-line SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto", "needs receiving parameters and will receive data from the SDR class Receiver: def", "floor estimate: noise_floor = sum(SNR[0:10])/10 shifted_SNR = SNR-noise_floor return shifted_SNR # Median filter", "return shifted_SNR # Median filter for rfi-removal def median(self, data): for i in", "blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med != 0 else SNR_spectrum #", "samples have been dropped and replaces 0.0 with next value def check_for_zero(self, PSD):", "PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed) return", "windowed_samples = samples * window # Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2", "self.resolution) # Samples a blank spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq", "''' # Receiver class. This needs receiving parameters and will receive data from", "range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if samples have been dropped", "class. This needs receiving parameters and will receive data from the SDR class", "from the SDR class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT, num_med): self.sdr", "# Perform FFT and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log =", "self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop = stop_freq, num =", "operator import math import numpy as np from rtlsdr import RtlSdr import matplotlib.pyplot", "blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median =", "start_freq, stop = stop_freq, num = self.resolution) # Samples a blank spectrum to", "# Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq +", "data # Checks if samples have been dropped and replaces 0.0 with next", "= self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank", "a blank spectrum to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD", "averaged from \"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed = (0, )*", "rtlsdr import RtlSdr import matplotlib.pyplot as plt # Available sample rates ''' 3200000Hz", "each...') data_PSD = self.sample() # Observed frequency range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2", "ppm self.sdr.gain = 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med = num_med", "= np.hanning(self.resolution) windowed_samples = samples * window # Perform FFT and PSD-analysis PSD", "print(f'Receiving {self.num_FFT} bins of {self.resolution} samples each...') data_PSD = self.sample() # Observed frequency", "(counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to samples in time", "= 'auto' self.resolution = 2**resolution self.num_FFT = num_FFT self.num_med = num_med # Reads", "for sample in PSD_summed) return averaged_PSD # Calculates SNR from spectrum and H-line", "# configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For some reason", "shifted_SNR # Median filter for rfi-removal def median(self, data): for i in range(len(data)):", "SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med", "= self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median = self.median(SNR_spectrum) if self.num_med !=", "to 0 so we avoid that if ppm != 0: self.sdr.freq_correction = ppm", "samples in time domain before performing FFT window = np.hanning(self.resolution) windowed_samples = samples", "to callibrate spectrum with. self.sdr.center_freq = self.sdr.center_freq + 3000000 blank_PSD = self.sample() SNR_spectrum", "3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' #", "Close the SDR self.sdr.close() return freqs, SNR_median # Returns numpy array with PSD", "- self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs = np.linspace(start = start_freq, stop", "RtlSdr() # configure SDR self.sdr.sample_rate = sample_rate self.sdr.center_freq = 1420405000 # For some", "np.hanning(self.resolution) windowed_samples = samples * window # Perform FFT and PSD-analysis PSD =", "from \"num_FFT\" datasets def sample(self): counter = 0.0 PSD_summed = (0, )* self.resolution", "data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if", "range start_freq = self.sdr.center_freq - self.sdr.sample_rate/2 stop_freq = self.sdr.center_freq + self.sdr.sample_rate/2 freqs =", "3000000 blank_PSD = self.sample() SNR_spectrum = self.estimate_SNR(data = data_PSD, blank = blank_PSD) SNR_median", "of {self.resolution} samples each...') data_PSD = self.sample() # Observed frequency range start_freq =", "value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index]", "have been dropped and replaces 0.0 with next value def check_for_zero(self, PSD): try:", "PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter for sample", "parameters and will receive data from the SDR class Receiver: def __init__(self, sample_rate,", "self.resolution while (counter < self.num_FFT): samples = self.sdr.read_samples(self.resolution) # Applies window to samples", "tuple(sample/counter for sample in PSD_summed) return averaged_PSD # Calculates SNR from spectrum and", "np from rtlsdr import RtlSdr import matplotlib.pyplot as plt # Available sample rates", "in time domain before performing FFT window = np.hanning(self.resolution) windowed_samples = samples *", "and H-line SNR def estimate_SNR(self, data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise", "some reason the SDR doesn't want to set the offset PPM to 0", "FFT window = np.hanning(self.resolution) windowed_samples = samples * window # Perform FFT and", "rfi-removal def median(self, data): for i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data", "i in range(len(data)): data[i] = np.mean(data[i:i+self.num_med]) return data # Checks if samples have", "2**resolution self.num_FFT = num_FFT self.num_med = num_med # Reads data from SDR, processes", "data, blank): SNR = np.array(data)-np.array(blank) # Ghetto noise floor estimate: noise_floor = sum(SNR[0:10])/10", "1800000Hz 1400000Hz 1024000Hz 900001Hz 250000Hz ''' # Receiver class. This needs receiving parameters", "next value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample was recovered!')", "and PSD-analysis PSD = np.abs(np.fft.fft(windowed_samples)/self.sdr.sample_rate)**2 PSD_checked = self.check_for_zero(PSD) PSD_log = 10*np.log10(PSD_checked) PSD_summed =", "averaged_PSD = tuple(sample/counter for sample in PSD_summed) return averaged_PSD # Calculates SNR from", "= 10*np.log10(PSD_checked) PSD_summed = tuple(map(operator.add, PSD_summed, np.fft.fftshift(PSD_log))) counter += 1.0 averaged_PSD = tuple(sample/counter", "counter += 1.0 averaged_PSD = tuple(sample/counter for sample in PSD_summed) return averaged_PSD #", "receive data from the SDR class Receiver: def __init__(self, sample_rate, ppm, resolution, num_FFT,", "sample(self): counter = 0.0 PSD_summed = (0, )* self.resolution while (counter < self.num_FFT):", "performing FFT window = np.hanning(self.resolution) windowed_samples = samples * window # Perform FFT", "as plt # Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz", "with next value def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample was", "data from SDR, processes and writes it def receive(self): print(f'Receiving {self.num_FFT} bins of", "plt # Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz 2048000Hz 1920000Hz 1800000Hz", "def check_for_zero(self, PSD): try: index = list(PSD).index(0.0) print('Dropped sample was recovered!') PSD[index] =", "import matplotlib.pyplot as plt # Available sample rates ''' 3200000Hz 2800000Hz 2560000Hz 2400000Hz" ]
[ "Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection( source=source_layer, target=target_layer, update_rule=PostPre, nu=(1e-4,", "Connection from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True)", "import Connection from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000,", "from bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer", "from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection", "bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection =", "from bindsnet.network.nodes import Input, LIFNodes from bindsnet.network.topology import Connection from bindsnet.learning import PostPre", "Input, LIFNodes from bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer = Input(n=100,", "PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection( source=source_layer,", "= Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection( source=source_layer, target=target_layer, update_rule=PostPre,", "bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True) target_layer =", "import PostPre source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection(", "traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection( source=source_layer, target=target_layer, update_rule=PostPre, nu=(1e-4, 1e-2))", "bindsnet.network.nodes import Input, LIFNodes from bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer", "source_layer = Input(n=100, traces=True) target_layer = LIFNodes(n=1000, traces=True) connection = Connection( source=source_layer, target=target_layer,", "LIFNodes from bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer = Input(n=100, traces=True)", "import Input, LIFNodes from bindsnet.network.topology import Connection from bindsnet.learning import PostPre source_layer =" ]
[ "non-commercial use licence. # See LICENCE.txt for the full text of the licence.", "a non-commercial use licence. # See LICENCE.txt for the full text of the", "load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg", "= parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|'))", "by a non-commercial use licence. # See LICENCE.txt for the full text of", "C&C NLP tools # Copyright (c) Universities of Edinburgh, Oxford and Sydney #", "io import model import tagger import ccg def load(super, parser, load_model = True):", "# If LICENCE.txt is not included in this distribution # please email <EMAIL>", "is not included in this distribution # please email <EMAIL> to obtain a", "LICENCE.txt is not included in this distribution # please email <EMAIL> to obtain", "the licence. # # If LICENCE.txt is not included in this distribution #", "software is covered by a non-commercial use licence. # See LICENCE.txt for the", "copy. from base import * import config import io import model import tagger", "Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for x in s.split()] sent.words =", "= [t[0] for t in tokens] sent.pos = [t[1] for t in tokens]", "covered by a non-commercial use licence. # See LICENCE.txt for the full text", "email <EMAIL> to obtain a copy. from base import * import config import", "= tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg,", "in this distribution # please email <EMAIL> to obtain a copy. from base", "config import io import model import tagger import ccg def load(super, parser, load_model", "ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser", "of Edinburgh, Oxford and Sydney # Copyright (c) <NAME> # # This software", "(c) <NAME> # # This software is covered by a non-commercial use licence.", "# Copyright (c) <NAME> # # This software is covered by a non-commercial", "a copy. from base import * import config import io import model import", "= ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s):", "t in tokens] sent.pos = [t[1] for t in tokens] sent.msuper = [[t[2]]", "Sydney # Copyright (c) <NAME> # # This software is covered by a", "int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value", "# This software is covered by a non-commercial use licence. # See LICENCE.txt", "Edinburgh, Oxford and Sydney # Copyright (c) <NAME> # # This software is", "super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg,", "<NAME> # # This software is covered by a non-commercial use licence. #", "parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens =", "included in this distribution # please email <EMAIL> to obtain a copy. from", "tokens = [tuple(x.split('|')) for x in s.split()] sent.words = [t[0] for t in", "= [tuple(x.split('|')) for x in s.split()] sent.words = [t[0] for t in tokens]", "return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for x", "s.split()] sent.words = [t[0] for t in tokens] sent.pos = [t[1] for t", "tokens] sent.pos = [t[1] for t in tokens] sent.msuper = [[t[2]] for t", "If LICENCE.txt is not included in this distribution # please email <EMAIL> to", "s): tokens = [tuple(x.split('|')) for x in s.split()] sent.words = [t[0] for t", "# # If LICENCE.txt is not included in this distribution # please email", "super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for x in s.split()]", "Universities of Edinburgh, Oxford and Sydney # Copyright (c) <NAME> # # This", "this distribution # please email <EMAIL> to obtain a copy. from base import", "model import tagger import ccg def load(super, parser, load_model = True): int_cfg =", "[t[0] for t in tokens] sent.pos = [t[1] for t in tokens] sent.msuper", "def read(sent, s): tokens = [tuple(x.split('|')) for x in s.split()] sent.words = [t[0]", "ccg def load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig()", "Oxford and Sydney # Copyright (c) <NAME> # # This software is covered", "parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for x in s.split()] sent.words", "= super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence())", "# C&C NLP tools # Copyright (c) Universities of Edinburgh, Oxford and Sydney", "# please email <EMAIL> to obtain a copy. from base import * import", "super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return", "parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent,", "for x in s.split()] sent.words = [t[0] for t in tokens] sent.pos =", "for the full text of the licence. # # If LICENCE.txt is not", "tools # Copyright (c) Universities of Edinburgh, Oxford and Sydney # Copyright (c)", "import ccg def load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg =", "in tokens] sent.pos = [t[1] for t in tokens] sent.msuper = [[t[2]] for", "ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens", "read(sent, s): tokens = [tuple(x.split('|')) for x in s.split()] sent.words = [t[0] for", "super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def", "True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig()", "import tagger import ccg def load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig()", "parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super", "Copyright (c) <NAME> # # This software is covered by a non-commercial use", "the full text of the licence. # # If LICENCE.txt is not included", "and Sydney # Copyright (c) <NAME> # # This software is covered by", "tagger import ccg def load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg", "= [t[1] for t in tokens] sent.msuper = [[t[2]] for t in tokens]", "[tuple(x.split('|')) for x in s.split()] sent.words = [t[0] for t in tokens] sent.pos", "obtain a copy. from base import * import config import io import model", "import io import model import tagger import ccg def load(super, parser, load_model =", "for t in tokens] sent.pos = [t[1] for t in tokens] sent.msuper =", "is covered by a non-commercial use licence. # See LICENCE.txt for the full", "to obtain a copy. from base import * import config import io import", "# Copyright (c) Universities of Edinburgh, Oxford and Sydney # Copyright (c) <NAME>", "licence. # # If LICENCE.txt is not included in this distribution # please", "LICENCE.txt for the full text of the licence. # # If LICENCE.txt is", "* import config import io import model import tagger import ccg def load(super,", "full text of the licence. # # If LICENCE.txt is not included in", "not included in this distribution # please email <EMAIL> to obtain a copy.", "<EMAIL> to obtain a copy. from base import * import config import io", "of the licence. # # If LICENCE.txt is not included in this distribution", "import * import config import io import model import tagger import ccg def", "in s.split()] sent.words = [t[0] for t in tokens] sent.pos = [t[1] for", "please email <EMAIL> to obtain a copy. from base import * import config", "Copyright (c) Universities of Edinburgh, Oxford and Sydney # Copyright (c) <NAME> #", "tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value = parser return ccg.Integration(int_cfg, super_cfg,", "NLP tools # Copyright (c) Universities of Edinburgh, Oxford and Sydney # Copyright", "parser return ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for", "= ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg = ccg.ParserConfig() parser_cfg.path.value =", "base import * import config import io import model import tagger import ccg", "def load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value", "import config import io import model import tagger import ccg def load(super, parser,", "# # This software is covered by a non-commercial use licence. # See", "distribution # please email <EMAIL> to obtain a copy. from base import *", "# See LICENCE.txt for the full text of the licence. # # If", "use licence. # See LICENCE.txt for the full text of the licence. #", "sent.pos = [t[1] for t in tokens] sent.msuper = [[t[2]] for t in", "from base import * import config import io import model import tagger import", "(c) Universities of Edinburgh, Oxford and Sydney # Copyright (c) <NAME> # #", "import model import tagger import ccg def load(super, parser, load_model = True): int_cfg", "text of the licence. # # If LICENCE.txt is not included in this", "= True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value = super parser_cfg =", "x in s.split()] sent.words = [t[0] for t in tokens] sent.pos = [t[1]", "See LICENCE.txt for the full text of the licence. # # If LICENCE.txt", "load(super, parser, load_model = True): int_cfg = ccg.IntegrationConfig() super_cfg = tagger.SuperConfig() super_cfg.path.value =", "This software is covered by a non-commercial use licence. # See LICENCE.txt for", "licence. # See LICENCE.txt for the full text of the licence. # #", "sent.words = [t[0] for t in tokens] sent.pos = [t[1] for t in", "ccg.Integration(int_cfg, super_cfg, parser_cfg, Sentence()) def read(sent, s): tokens = [tuple(x.split('|')) for x in" ]
[ "django.db import models # Create your models here. class Blog(models.Model): \"\"\" Represents a", "\"\"\" Represents a project model in home page. \"\"\" title = models.CharField(max_length=50) description", "Blog(models.Model): \"\"\" Represents a project model in home page. \"\"\" title = models.CharField(max_length=50)", "\"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date = models.DateField() def __str__(self): return", "Represents a project model in home page. \"\"\" title = models.CharField(max_length=50) description =", "your models here. class Blog(models.Model): \"\"\" Represents a project model in home page.", "model in home page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date =", "title = models.CharField(max_length=50) description = models.CharField(max_length=150) date = models.DateField() def __str__(self): return self.title", "here. class Blog(models.Model): \"\"\" Represents a project model in home page. \"\"\" title", "from django.db import models # Create your models here. class Blog(models.Model): \"\"\" Represents", "import models # Create your models here. class Blog(models.Model): \"\"\" Represents a project", "models here. class Blog(models.Model): \"\"\" Represents a project model in home page. \"\"\"", "in home page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date = models.DateField()", "home page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date = models.DateField() def", "models # Create your models here. class Blog(models.Model): \"\"\" Represents a project model", "# Create your models here. class Blog(models.Model): \"\"\" Represents a project model in", "Create your models here. class Blog(models.Model): \"\"\" Represents a project model in home", "page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date = models.DateField() def __str__(self):", "a project model in home page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150)", "project model in home page. \"\"\" title = models.CharField(max_length=50) description = models.CharField(max_length=150) date", "class Blog(models.Model): \"\"\" Represents a project model in home page. \"\"\" title =" ]
[ "tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received:", "{status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing", "tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received:", "status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\")", "#tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\")", "tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received:", "writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\")", "?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2", "print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\")", "status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\")", "telnetlib import time tn = telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5):", "writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\")", "status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\")", "print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\")", "print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\")", "for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received:", "tn = telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing ?Q102\")", "?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2", "telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status", "time.sleep(1) for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data", "received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now", "print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\")", "= tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data", "{status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing", "received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now", "5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status =", "import telnetlib import time tn = telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in", "= tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data", "= telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\")", "received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") tn.close()", "in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now", "= tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data", "time tn = telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now writing", "print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\")", "import time tn = telnetlib.Telnet('192.168.137.226', 5051) #tn.write(b\"Client\") time.sleep(1) for i in range(5): print(\"Now", "tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2 =", "?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\") status2", "print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\")", "tn.write(b\"?Q200\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q500\") tn.write(b\"?Q500\\n\") status2 =", "range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing", "writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\") print(\"Now writing ?Q104\") tn.write(b\"?Q104\\n\")", "i in range(5): print(\"Now writing ?Q102\") tn.write(b\"?Q102\\n\") status = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status}\")", "tn.write(b\"?Q104\\n\") status2 = tn.read_until(b\"\\n\",timeout=1).decode(\"utf-8\") print(f\"Data received: {status2}\") print(\"Now writing ?Q200\") tn.write(b\"?Q200\\n\") status2 =" ]
[ "argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may use", "After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console <<", "the hook # After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[]", "{pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information \"\"\" uname = platform.uname()", "be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\")", "Output below from the hook # After hook cli = console print(\"builtins_hook here\")", "return message def cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test error message\")", "uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def", "error message\") def cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill", "# Or you may use # cli.run_while(lambda: <some code>) if __name__ == '__main__':", "logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to be output like", "- %(message)s\") def cli_print(): \"\"\" How can I write text to the console?", "\\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s", "%(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can I write text to the", "log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want", "raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid()", "\"\"\" I use logging and want its output to be in the console!", "def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname)", "output like cli.log \"\"\" # Output below without hook print(\"No builtins_hook here\") cli.builtins_hook()", "message def cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test error message\") def", "log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to be output like cli.log", "%(message)s\") def cli_print(): \"\"\" How can I write text to the console? Read", "import getpass import logging import os import platform from console import Console, ConsoleIO", "cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may use #", "os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information \"\"\" uname = platform.uname() user", "print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to be output like cli.log \"\"\"", "def builtins_preview(): \"\"\" I want print to be output like cli.log \"\"\" #", "getpass import logging import os import platform from console import Console, ConsoleIO #", "be in the console! \"\"\" cli.logger_hook() # All calls below will be implemented", "console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def", "f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\",", "console! \"\"\" cli.logger_hook() # All calls below will be implemented via Console logging.debug(\"Debug", "kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information \"\"\" uname =", "cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may use # cli.run_while(lambda: <some", "\"\"\" I want print to be output like cli.log \"\"\" # Output below", "message\") def cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\")", "cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and want its output to", "found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\")", "log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\"", "console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here \"\"\" message = f\"argv: {argv}\"", "from the hook # After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\")", "logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print", "= f\"argv: {argv}\" return message def cli_error(): \"\"\" Print error message \"\"\" raise", "\"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here", "implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def", "prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s", "log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here \"\"\"", "help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or", "without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below from the hook #", "Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s -", "import platform from console import Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\",", "cli.run() # Or you may use # cli.run_while(lambda: <some code>) if __name__ ==", "def cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill", "\"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def", "console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv:", "format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can I", "ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here \"\"\" message", "the console! \"\"\" cli.logger_hook() # All calls below will be implemented via Console", "Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\"", "process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\"", "like cli.log \"\"\" # Output below without hook print(\"No builtins_hook here\") cli.builtins_hook() #", "here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\")", "\"\"\" # Output below without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below", "\"\"\" Help message here \"\"\" message = f\"argv: {argv}\" return message def cli_error():", "({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\",", "file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\"", "Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here \"\"\" message = f\"argv:", "output to be in the console! \"\"\" cli.logger_hook() # All calls below will", "print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and want its output to be", "below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and want", "can I write text to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\")", "def cli_print(): \"\"\" How can I write text to the console? Read below!", "\"\"\" Print uname information \"\"\" uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node}", "import Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not", "{uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit)", "in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def", "\"\"\" How can I write text to the console? Read below! \"\"\" cli.log(\"cli.og\")", "\"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and want its", "text to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\"", "in the console! \"\"\" cli.logger_hook() # All calls below will be implemented via", "via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview():", "cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may use # cli.run_while(lambda: <some code>)", "cli.log \"\"\" # Output below without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output", "cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET,", "= Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s", "want print to be output like cli.log \"\"\" # Output below without hook", "ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in", "Or you may use # cli.run_while(lambda: <some code>) if __name__ == '__main__': cli_print()", "cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run()", "os import platform from console import Console, ConsoleIO # Init modules cli =", "Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$", "{pid}\") def cli_uname(): \"\"\" Print uname information \"\"\" uname = platform.uname() user =", "- %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can I write text to", "its output to be in the console! \"\"\" cli.logger_hook() # All calls below", "cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and want its output", "builtins_hook here\") cli.builtins_hook() # Output below from the hook # After hook cli", "here\") cli.builtins_hook() # Output below from the hook # After hook cli =", "-> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error)", "# After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console", "getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo,", "console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list):", "to be in the console! \"\"\" cli.logger_hook() # All calls below will be", "I want print to be output like cli.log \"\"\" # Output below without", "and want its output to be in the console! \"\"\" cli.logger_hook() # All", "%(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can I write text", "will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\")", "to be output like cli.log \"\"\" # Output below without hook print(\"No builtins_hook", "print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or", "logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to be", "uname information \"\"\" uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system}", "I use logging and want its output to be in the console! \"\"\"", "cli_exit(): \"\"\" Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\")", "information \"\"\" uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release}", "print to be output like cli.log \"\"\" # Output below without hook print(\"No", "Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found", "the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use", "= os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information", "Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging and", "cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\"", "console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\") #", "# Output below from the hook # After hook cli = console print(\"builtins_hook", "error message \"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process \"\"\"", "Print error message \"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process", "use # cli.run_while(lambda: <some code>) if __name__ == '__main__': cli_print() logger_preview() builtins_preview() cli_mode()", "return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True)", "Print uname information \"\"\" uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} ->", "import logging import os import platform from console import Console, ConsoleIO # Init", "f\"argv: {argv}\" return message def cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test", "to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I", "logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I", "# Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\",", "= platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode():", "All calls below will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error", "builtins_preview(): \"\"\" I want print to be output like cli.log \"\"\" # Output", "cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may", "cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\"", "{uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\",", "platform from console import Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\",", "message = f\"argv: {argv}\" return message def cli_error(): \"\"\" Print error message \"\"\"", "debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How", "cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you", "cli_uname(): \"\"\" Print uname information \"\"\" uname = platform.uname() user = getpass.getuser() return", "\"\"\" Print error message \"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill", "\"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process \"\"\" pid =", "below without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below from the hook", "be output like cli.log \"\"\" # Output below without hook print(\"No builtins_hook here\")", "# Output below without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below from", "log') logging.error(\"Error log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to", "Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO,", "use logging and want its output to be in the console! \"\"\" cli.logger_hook()", "logging import os import platform from console import Console, ConsoleIO # Init modules", "write text to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview():", "How can I write text to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\")", "log\") logging.info(\"Info log\") print(end=\"\\n\\n\\n\") def builtins_preview(): \"\"\" I want print to be output", "hook # After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log']", "def cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test error message\") def cli_exit():", "console import Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\"", "want its output to be in the console! \"\"\" cli.logger_hook() # All calls", "cli_echo(argv: list): \"\"\" Help message here \"\"\" message = f\"argv: {argv}\" return message", "modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False)", "ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\", cli_echo, argv=True) cli.add(\"error\", cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() #", "= getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\") cli.add(\"echo\",", "print(\"No builtins_hook here\") cli.builtins_hook() # Output below from the hook # After hook", "message \"\"\" raise Exception(\"Test error message\") def cli_exit(): \"\"\" Kill process \"\"\" pid", "calls below will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\")", "list): \"\"\" Help message here \"\"\" message = f\"argv: {argv}\" return message def", "hook cli = console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<<", "Help message here \"\"\" message = f\"argv: {argv}\" return message def cli_error(): \"\"\"", "cli_uname) cli.run() # Or you may use # cli.run_while(lambda: <some code>) if __name__", "console << \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help", "message here \"\"\" message = f\"argv: {argv}\" return message def cli_error(): \"\"\" Print", "here \"\"\" message = f\"argv: {argv}\" return message def cli_error(): \"\"\" Print error", "logger_preview(): \"\"\" I use logging and want its output to be in the", "import os import platform from console import Console, ConsoleIO # Init modules cli", "I write text to the console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def", "cli.add(\"uname\", cli_uname) cli.run() # Or you may use # cli.run_while(lambda: <some code>) if", "not_found=\"Command \\\"%s\\\" not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s -", "= console print(\"builtins_hook here\") console.write(\"console.write\") console.log(\"console.log\") console['[] log'] console << \"<< log\" ConsoleIO.write(\"\\n\\n\")", "hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below from the hook # After", "from console import Console, ConsoleIO # Init modules cli = Console(prompt_in=\">\", prompt_out=\"]:\", not_found=\"Command", "logging and want its output to be in the console! \"\"\" cli.logger_hook() #", "Kill process \"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname():", "{argv}\" return message def cli_error(): \"\"\" Print error message \"\"\" raise Exception(\"Test error", "print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information \"\"\" uname", "<filename>src/main.py import getpass import logging import os import platform from console import Console,", "logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can", "below will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log') logging.error(\"Error log\") logging.info(\"Info", "Output below without hook print(\"No builtins_hook here\") cli.builtins_hook() # Output below from the", "# Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message here \"\"\" message =", "<< \"<< log\" ConsoleIO.write(\"\\n\\n\") # Or console.get_IO.write(\"\\n\\n\") def cli_echo(argv: list): \"\"\" Help message", "user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype help\\n\")", "# All calls below will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning log')", "cli_print(): \"\"\" How can I write text to the console? Read below! \"\"\"", "\"\"\" message = f\"argv: {argv}\" return message def cli_error(): \"\"\" Print error message", "below from the hook # After hook cli = console print(\"builtins_hook here\") console.write(\"console.write\")", "\"\"\" cli.logger_hook() # All calls below will be implemented via Console logging.debug(\"Debug log\")", "def cli_uname(): \"\"\" Print uname information \"\"\" uname = platform.uname() user = getpass.getuser()", "may use # cli.run_while(lambda: <some code>) if __name__ == '__main__': cli_print() logger_preview() builtins_preview()", "console? Read below! \"\"\" cli.log(\"cli.og\") cli.write(\"cli.write\") print(end=\"\\n\\n\\n\") def logger_preview(): \"\"\" I use logging", "alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print():", "def logger_preview(): \"\"\" I use logging and want its output to be in", "os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname information \"\"\"", "you may use # cli.run_while(lambda: <some code>) if __name__ == '__main__': cli_print() logger_preview()", "cli.builtins_hook() # Output below from the hook # After hook cli = console", "cli_error) cli.add(\"exit\", cli_exit) cli.add(\"uname\", cli_uname) cli.run() # Or you may use # cli.run_while(lambda:", "not found in alias.\", file=ConsoleIO, debug=False) logging.basicConfig(level=logging.NOTSET, format=\"%(asctime)s - %(name)-5s - %(levelname)-7s -", "\"\"\" pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print", "pid = os.getpid() print(f\"\\r$ kill {pid}\") os.system(f\"kill {pid}\") def cli_uname(): \"\"\" Print uname", "- %(name)-5s - %(levelname)-7s - %(message)s\") def cli_print(): \"\"\" How can I write", "\"\"\" uname = platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\"", "cli.logger_hook() # All calls below will be implemented via Console logging.debug(\"Debug log\") logging.warning('Warning", "platform.uname() user = getpass.getuser() return f\"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})\" def cli_mode(): ConsoleIO.write(\"\\rtype", "def cli_echo(argv: list): \"\"\" Help message here \"\"\" message = f\"argv: {argv}\" return" ]
[]
[ "{ 42: b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ),", "( [ [ \"hand\", ], b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\",", "== 0 def is_positive(n): return n > 0 # basic sequences (tuple, list,", "[ \"hand\", ], b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (1.414,), {", "}, b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), { (\"15\",): bytearray(b\"pick\"),", "SEQUENCES = ( [ [ \"hand\", ], b\"pick\", ( 42, b\"hand\", ), ],", "return n > 0 # basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES", "# similar to above, modified to contain dictionaries SEQS_DICTS = ( [ [", "is_even(n): return n % 2 == 0 def is_positive(n): return n > 0", "\"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) # similar to above, modified", "SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\", { 42: b\"hand\", }, ],", "], b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"),", "), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) # similar", "above, modified to contain dictionaries SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\",", "{ 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), { (\"15\",): bytearray(b\"pick\"), }, ),", "list, str, bytes, bytearray) SEQUENCES = ( [ [ \"hand\", ], b\"pick\", (", "{ (\"15\",): bytearray(b\"pick\"), }, ), ) # similar to above, modified to contain", "\"15\", bytearray(b\"pick\"), ], ), ) # similar to above, modified to contain dictionaries", "dictionaries SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\", { 42: b\"hand\", },", "}, ), ) # similar to above, modified to contain set and frozenset", "[ [ \"hand\", ], b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (1.414,),", "set and frozenset COLLECTIONS = ( [ { \"hand\", }, b\"pick\", { 42:", "n > 0 # basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES =", "similar to above, modified to contain set and frozenset COLLECTIONS = ( [", "contain set and frozenset COLLECTIONS = ( [ { \"hand\", }, b\"pick\", {", "), ) # similar to above, modified to contain set and frozenset COLLECTIONS", "<filename>tests/__init__.py def is_even(n): return n % 2 == 0 def is_positive(n): return n", ") # similar to above, modified to contain set and frozenset COLLECTIONS =", "to contain dictionaries SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\", { 42:", "= ( [ { \"hand\", }, b\"pick\", { 42: b\"hand\", }, ], (", "# basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES = ( [ [", "0 # basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES = ( [", "basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES = ( [ [ \"hand\",", "[ { \"hand\", }, b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),),", "{ \"hand\", }, b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), {", "= ( [ [ \"hand\", ], b\"pick\", ( 42, b\"hand\", ), ], (", "to contain set and frozenset COLLECTIONS = ( [ { \"hand\", }, b\"pick\",", "b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) #", "[ [ \"hand\", ], b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\", (1.414,),", "( 42, b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ),", "bytearray) SEQUENCES = ( [ [ \"hand\", ], b\"pick\", ( 42, b\"hand\", ),", "modified to contain set and frozenset COLLECTIONS = ( [ { \"hand\", },", "sequences (tuple, list, str, bytes, bytearray) SEQUENCES = ( [ [ \"hand\", ],", "}, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) # similar", "def is_even(n): return n % 2 == 0 def is_positive(n): return n >", "], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) # similar to", "2 == 0 def is_positive(n): return n > 0 # basic sequences (tuple,", "\"hand\", ], b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",):", "\"hand\", ], b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\",", "to above, modified to contain set and frozenset COLLECTIONS = ( [ {", "bytes, bytearray) SEQUENCES = ( [ [ \"hand\", ], b\"pick\", ( 42, b\"hand\",", "[ \"15\", bytearray(b\"pick\"), ], ), ) # similar to above, modified to contain", "42, b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), )", "b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) #", "], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) # similar to", "> 0 # basic sequences (tuple, list, str, bytes, bytearray) SEQUENCES = (", "], ), ) # similar to above, modified to contain dictionaries SEQS_DICTS =", "( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) # similar to above,", "], b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"),", "and frozenset COLLECTIONS = ( [ { \"hand\", }, b\"pick\", { 42: b\"hand\",", "= ( [ [ \"hand\", ], b\"pick\", { 42: b\"hand\", }, ], (", "bytearray(b\"pick\"), ], ), ) # similar to above, modified to contain dictionaries SEQS_DICTS", "above, modified to contain set and frozenset COLLECTIONS = ( [ { \"hand\",", "# similar to above, modified to contain set and frozenset COLLECTIONS = (", "), ) # similar to above, modified to contain dictionaries SEQS_DICTS = (", "b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ],", "def is_positive(n): return n > 0 # basic sequences (tuple, list, str, bytes,", "(1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) # similar to above, modified to", "\"3.14\", (1.414,), [ \"15\", bytearray(b\"pick\"), ], ), ) # similar to above, modified", "modified to contain dictionaries SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\", {", "n % 2 == 0 def is_positive(n): return n > 0 # basic", "b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), { (\"15\",): bytearray(b\"pick\"), },", "(\"15\",): bytearray(b\"pick\"), }, ), ) # similar to above, modified to contain set", "to above, modified to contain dictionaries SEQS_DICTS = ( [ [ \"hand\", ],", "COLLECTIONS = ( [ { \"hand\", }, b\"pick\", { 42: b\"hand\", }, ],", "similar to above, modified to contain dictionaries SEQS_DICTS = ( [ [ \"hand\",", "42: b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), )", "( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) # similar to above,", "bytearray(b\"pick\"), }, ), ) # similar to above, modified to contain set and", "% 2 == 0 def is_positive(n): return n > 0 # basic sequences", "( [ { \"hand\", }, b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\",", "\"hand\", }, b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), { (\"15\",):", "0 def is_positive(n): return n > 0 # basic sequences (tuple, list, str,", "frozenset COLLECTIONS = ( [ { \"hand\", }, b\"pick\", { 42: b\"hand\", },", "str, bytes, bytearray) SEQUENCES = ( [ [ \"hand\", ], b\"pick\", ( 42,", "42: b\"hand\", }, ], ( \"3.14\", (frozenset({1.414}),), { (\"15\",): bytearray(b\"pick\"), }, ), )", ") # similar to above, modified to contain dictionaries SEQS_DICTS = ( [", "return n % 2 == 0 def is_positive(n): return n > 0 #", "contain dictionaries SEQS_DICTS = ( [ [ \"hand\", ], b\"pick\", { 42: b\"hand\",", "is_positive(n): return n > 0 # basic sequences (tuple, list, str, bytes, bytearray)", "( [ [ \"hand\", ], b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\",", "(tuple, list, str, bytes, bytearray) SEQUENCES = ( [ [ \"hand\", ], b\"pick\",", "[ \"hand\", ], b\"pick\", ( 42, b\"hand\", ), ], ( \"3.14\", (1.414,), [", "b\"pick\", { 42: b\"hand\", }, ], ( \"3.14\", (1.414,), { (\"15\",): bytearray(b\"pick\"), },", "(1.414,), { (\"15\",): bytearray(b\"pick\"), }, ), ) # similar to above, modified to" ]
[ "this off to get rid of warning messages. In future versions of SQLAlchemy,", "can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME',", "parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS',", "'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) #", "'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY = 'My Secret' #", "for local development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True')", "messages. In future versions of SQLAlchemy, False will be the default and #", "SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD =", "'') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms':", "= False TESTING = False class DevConfig(Config): DEBUG = True TESTING = True", "os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT',", "import dotenv dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config',", "os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies without", "PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST =", "'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak", "= [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak", "non-TLS HTTP server. Set this to non-\"True\" for local development, and use the", "port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False class DevConfig(Config): DEBUG =", "= False class DevConfig(Config): DEBUG = True TESTING = True # SQLALCHEMY_ECHO =", "of SQLAlchemy, False will be the default and # this can be removed.", "flag, which we need for the local # non-TLS HTTP server. Set this", "name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False class DevConfig(Config): DEBUG = True", "server. Set this to non-\"True\" for local development, and use the default everywhere", "host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST =", "class Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS',", "= 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD =", "OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending", "Undocumented Keycloak parameter: allows sending cookies without the secure flag, which we need", "Keycloak parameter: allows sending cookies without the secure flag, which we need for", "everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off to", "SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS", "allows sending cookies without the secure flag, which we need for the local", "'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY = 'My", "Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json')", "SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT", "os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = {", "os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) }", "sending cookies without the secure flag, which we need for the local #", "os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off to get rid of warning", "password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST", "= os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER =", "for the local # non-TLS HTTP server. Set this to non-\"True\" for local", "default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection", "OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')]", "DEBUG = False TESTING = False class DevConfig(Config): DEBUG = True TESTING =", "os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>,", "= os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME =", "and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' #", "= 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES =", "removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD", "= { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False", "os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI =", "'config.Config' } class Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS", "= ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\"", "versions of SQLAlchemy, False will be the default and # this can be", "'default': 'config.Config' } class Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak parameters.", "of warning messages. In future versions of SQLAlchemy, False will be the default", "SQLAlchemy, False will be the default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS", "os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format(", "os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME',", "user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False class", "Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email',", "== 'True' # Turn this off to get rid of warning messages. In", "'') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432')", "'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING =", "Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST',", "we need for the local # non-TLS HTTP server. Set this to non-\"True\"", "+ OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies without the secure flag,", "'5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME)", "os import dotenv dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production':", "OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented", "to non-\"True\" for local development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE =", "SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format(", "} class Config(object): SECRET_KEY = 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS =", "= { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object):", "non-\"True\" for local development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE',", "True TESTING = True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG = True", "'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows", "<filename>solr-admin-app/config.py import os import dotenv dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing':", "use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn", "off to get rid of warning messages. In future versions of SQLAlchemy, False", "warning messages. In future versions of SQLAlchemy, False will be the default and", "= os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT =", "False class DevConfig(Config): DEBUG = True TESTING = True # SQLALCHEMY_ECHO = True", "TESTING = True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG = True TESTING", "= os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI", "override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' }", "be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '')", "be the default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False #", "os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME',", "HTTP server. Set this to non-\"True\" for local development, and use the default", "'') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '')", "= os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME =", "= os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS =", "'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY =", "os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME',", "cookies without the secure flag, which we need for the local # non-TLS", "= os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME)", "host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False class DevConfig(Config): DEBUG", "to get rid of warning messages. In future versions of SQLAlchemy, False will", "SECRET_KEY = 'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES", "DEBUG = True TESTING = True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG", "{ 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY", "False TESTING = False class DevConfig(Config): DEBUG = True TESTING = True #", "{ 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING", "the secure flag, which we need for the local # non-TLS HTTP server.", "DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI", "class DevConfig(Config): DEBUG = True TESTING = True # SQLALCHEMY_ECHO = True class", "get rid of warning messages. In future versions of SQLAlchemy, False will be", "DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER", "and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information.", "= os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST,", "will be the default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False", "= os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI =", "'') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '')", "OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off to get rid", "the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this", "Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS =", "OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies without the secure flag, which", "without the secure flag, which we need for the local # non-TLS HTTP", "Turn this off to get rid of warning messages. In future versions of", "SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME", "local # non-TLS HTTP server. Set this to non-\"True\" for local development, and", "default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off", "} DEBUG = False TESTING = False class DevConfig(Config): DEBUG = True TESTING", "['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" +", "True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG = True TESTING = True", "else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off to get", "In future versions of SQLAlchemy, False will be the default and # this", "# this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER", "os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT',", "= os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies", "print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies without the secure", "'') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432')", "False will be the default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS =", "SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG =", "password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False class DevConfig(Config):", "'5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST,", "DevConfig(Config): DEBUG = True TESTING = True # SQLALCHEMY_ECHO = True class TestConfig(Config):", "DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME", "# Turn this off to get rid of warning messages. In future versions", "os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT),", "TESTING = False class DevConfig(Config): DEBUG = True TESTING = True # SQLALCHEMY_ECHO", "= True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG = True TESTING =", "'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS)", "name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '')", "# non-TLS HTTP server. Set this to non-\"True\" for local development, and use", "'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY = 'My Secret' # Normal", "= False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD',", "= os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT =", "SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD", "DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>,", "'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI',", "'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG = False TESTING = False", "Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS", "local development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') ==", "= os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True' # Turn this off to get rid of", "# Undocumented Keycloak parameter: allows sending cookies without the secure flag, which we", "Set this to non-\"True\" for local development, and use the default everywhere else.", "'My Secret' # Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid',", "rid of warning messages. In future versions of SQLAlchemy, False will be the", "'True') == 'True' # Turn this off to get rid of warning messages.", "which we need for the local # non-TLS HTTP server. Set this to", "future versions of SQLAlchemy, False will be the default and # this can", "'True' # Turn this off to get rid of warning messages. In future", "this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL Connection information. DATABASE_USER =", "= os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER,", "import os import dotenv dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig',", "= True TESTING = True # SQLALCHEMY_ECHO = True class TestConfig(Config): DEBUG =", "dotenv dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default':", "OIDC_SCOPES = ['openid', 'email', 'profile'] OIDC_VALID_ISSUERS = [os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '')", "'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class Config(object): SECRET_KEY = 'My Secret'", "'') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter: allows sending cookies without the", "the local # non-TLS HTTP server. Set this to non-\"True\" for local development,", "development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE = os.getenv('SOLR_ADMIN_APP_OIDC_ID_TOKEN_COOKIE_SECURE', 'True') == 'True'", "'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT), name=SYNONYMS_DATABASE_NAME) } DEBUG", "'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD',", "[os.getenv('SOLR_ADMIN_APP_OIDC_VALID_ISSUERS', 'http://localhost:8081/auth/realms/master')] OVERWRITE_REDIRECT_URI = os.getenv('SOLR_ADMIN_APP_OVERWRITE_REDIRECT_URI', '') print(\"OIDC\" + OIDC_CLIENT_SECRETS) # Undocumented Keycloak parameter:", "CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config' } class", "# Normal Keycloak parameters. OIDC_CLIENT_SECRETS = os.getenv('SOLR_ADMIN_APP_OIDC_CLIENT_SECRETS', 'solr-admin-app/keycloak_client_secrets/secrets.json') OIDC_SCOPES = ['openid', 'email', 'profile']", "# PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST", "information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '')", "DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '') DATABASE_HOST = os.getenv('NAMES_ADMIN_DATABASE_HOST', '') DATABASE_PORT", "'') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST', '') SYNONYMS_DATABASE_PORT = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PORT', '5432') SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms')", "dotenv.load_dotenv(dotenv.find_dotenv(), override=True) CONFIGURATION = { 'development': 'config.DevConfig', 'testing': 'config.TestConfig', 'production': 'config.Config', 'default': 'config.Config'", "parameter: allows sending cookies without the secure flag, which we need for the", "secure flag, which we need for the local # non-TLS HTTP server. Set", "the default and # this can be removed. SQLALCHEMY_TRACK_MODIFICATIONS = False # PostgreSQL", "'') DATABASE_PORT = os.getenv('NAMES_ADMIN_DATABASE_PORT', '5432') DATABASE_NAME = os.getenv('NAMES_ADMIN_DATABASE_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=DATABASE_USER,", "False # PostgreSQL Connection information. DATABASE_USER = os.getenv('NAMES_ADMIN_DATABASE_USERNAME', '') DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_DATABASE_PASSWORD', '')", "need for the local # non-TLS HTTP server. Set this to non-\"True\" for", "this to non-\"True\" for local development, and use the default everywhere else. OIDC_ID_TOKEN_COOKIE_SECURE", "SYNONYMS_DATABASE_NAME = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_NAME', 'synonyms') SQLALCHEMY_BINDS = { 'synonyms': 'postgresql://{user}:{password}@{host}:{port}/{name}'.format( user=SYNONYMS_DATABASE_USER, password=<PASSWORD>, host=SYNONYMS_DATABASE_HOST, port=int(SYNONYMS_DATABASE_PORT),", "port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '') SYNONYMS_DATABASE_HOST = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_HOST',", "user=DATABASE_USER, password=<PASSWORD>, host=DATABASE_HOST, port=int(DATABASE_PORT), name=DATABASE_NAME) SYNONYMS_DATABASE_USER = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_USERNAME', '') SYNONYMS_DATABASE_PASSWORD = os.getenv('NAMES_ADMIN_SYNONYMS_DATABASE_PASSWORD', '')" ]
[ "666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains", "key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys key\">key</warning>=4) dict([('key', 666), ('ky',", "3} dict = {'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2,", "keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> :", "random.random() {foo(): 1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys", "1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict =", "duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a", "'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' : 1, 'key_2': 2} import random", "<warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1' : 1,", "keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys key\">key</warning>=4) dict([('key', 666),", "duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict =", "keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning", "dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate", "<warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>", ": 3} a = {} {'key_1' : 1, 'key_2': 2} import random def", "descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> :", "1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666),", "123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains", "'key_2': 2} import random def foo(): return random.random() {foo(): 1, foo():2} # PY-2511", "a = {} {'key_1' : 1, 'key_2': 2} import random def foo(): return", "PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains", "random def foo(): return random.random() {foo(): 1, foo():2} # PY-2511 dict = dict([(<warning", "dict = {<warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning", "descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1' : 1, <warning", ": 1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict", "duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666),", "666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains", "contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' : 1, 'key_2':", "{'key_1' : 1, 'key_2': 2} import random def foo(): return random.random() {foo(): 1,", "= dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains", "{'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains", "duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict =", "dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate", "import random def foo(): return random.random() {foo(): 1, foo():2} # PY-2511 dict =", "descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains duplicate", "1, 'key_2': 2} import random def foo(): return random.random() {foo(): 1, foo():2} #", "dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>,", "def foo(): return random.random() {foo(): 1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary", "key_1\">key_1</warning> : 3} dict = {'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys", "'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {}", "descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys", "= dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys", "keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k',", "(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate", ": 3} dict = {'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>:", ": 1, 'key_2': 2} import random def foo(): return random.random() {foo(): 1, foo():2}", "contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>,", "dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>,", "key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary", "<warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' :", "duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666),", ": 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate", "= {<warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary", "123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning", "duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning>", "keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' : 1, 'key_2': 2} import", "{foo(): 1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>,", "666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys key\">key</warning>=4) dict([('key', 666), ('ky', 123)])", "dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate", "<filename>python/testData/inspections/PyDictDuplicateKeysInspection/test.py<gh_stars>1-10 dict = {<warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2,", "1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys", "contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3}", "key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3}", "descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)])", "{} {'key_1' : 1, 'key_2': 2} import random def foo(): return random.random() {foo():", "= {} {'key_1' : 1, 'key_2': 2} import random def foo(): return random.random()", "return random.random() {foo(): 1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate", "contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains duplicate keys", "descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' : 1,", "contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys key\">key</warning>=4)", "= dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys", "keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning", "keys key_1\">key_1</warning> : 3} dict = {'key_1' : 1, <warning descr=\"Dictionary contains duplicate", "descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys", "contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>,", "2} import random def foo(): return random.random() {foo(): 1, foo():2} # PY-2511 dict", "# PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary", "duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1' : 1, <warning descr=\"Dictionary contains", "contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict", "foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning", "3} a = {} {'key_1' : 1, 'key_2': 2} import random def foo():", "duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary contains duplicate keys key\">key</warning>=4) dict([('key',", "keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a =", "2, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1'", "dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)), <warning descr=\"Dictionary", "{<warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 1, key_2: 2, <warning descr=\"Dictionary contains", "(<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate", "keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning", "descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys", "key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary", "duplicate keys 'key_2'\">'key_2'</warning> : 3} a = {} {'key_1' : 1, 'key_2': 2}", "contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123))) dict", "2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1' :", "key\">'key'</warning>, 123)]) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary", "key_2: 2, <warning descr=\"Dictionary contains duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1'", "dict = {'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning", "= {'key_1' : 1, <warning descr=\"Dictionary contains duplicate keys 'key_2'\">'key_2'</warning>: 2, <warning descr=\"Dictionary", "key\">'key'</warning>, 123))) dict = dict(((<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), ('k', 123)),", "contains duplicate keys key_1\">key_1</warning> : 3} dict = {'key_1' : 1, <warning descr=\"Dictionary", "descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 666), (<warning descr=\"Dictionary contains duplicate keys key\">'key'</warning>, 123)))", "foo(): return random.random() {foo(): 1, foo():2} # PY-2511 dict = dict([(<warning descr=\"Dictionary contains" ]
[ "= Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict,", ".set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\":", "set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n =", "float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be compared to itself", "parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int,", "enumerate(expect_value) ] assert n.children == expect_children # singletons def test_None(self): n = Node.build(None)", "n = Node.build([[]]) assert n.name == \"\" assert n.kind is list assert n.value", "\"[0]\" assert n2.kind is list assert n2.value == [] assert not n2.is_leaf assert", "Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1,", "expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in enumerate(expect_value) ]", "expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind assert n.value", "def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\",", "8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str))", "Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\":", ".nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors())", "int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n", "= Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678)", "test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123,", "foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo,", "test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n,", "Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a,", "test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\",", "list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1,", "== textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3", ".list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1", "0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n =", "self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self):", "[[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert n2.name", "len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def", "123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert", "Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789,", "strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n =", "n2.name == \"[0]\" assert n2.kind is list assert n2.value == [] assert not", "True, False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n = Node.build([123, -456,", "expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.kind in {list,", "Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int,", "set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\",", "n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None, True, False])", "\"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo = Node( \".foo\", dict,", ".list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1", "self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set,", "n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) #", "to itself assert n.name == \"\" assert n.kind is float assert str(n.value) ==", "self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple,", "789]) self.verify_collection(n, list, [123, -456, 789]) # nested lists def test_list_of_empty_list(self): n =", "False]) def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789])", "test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n", "2, 3], \"tuple\": (4, 5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],),", "= Node.build(float(\"nan\")) # NaN cannot be compared to itself assert n.name == \"\"", "n.is_leaf assert len(n.children) == len(expect_value) if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\",", "int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n", "= Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n),", "456, \"bar\", 123}) # dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {})", "Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list,", "[123]) def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False])", "nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\" assert n.kind", "len(n.children) == 1 n2 = n.children[0] assert n2.name == \"[0]\" assert n2.kind is", "assert n.kind in {list, tuple, set, dict} assert not n.is_leaf assert len(n.children) ==", "assert n2.value == [] assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list,", "\"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors()) == [n] bar", "-456, 789]) # nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name ==", "n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is list assert n.value", "{\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\")", "= Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6},", "yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/*", "verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind", "tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n", "\"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def test_set_empty(self): n =", "\"\" assert n.kind is float assert str(n.value) == \"nan\" assert n.is_leaf # strings", "n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self):", "= Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False)", "== expect_children # singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def", "expect_children # singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self):", "n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool,", "foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list,", "test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be compared to itself assert n.name", "123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n),", "bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0,", "] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\":", "Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def", "= Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1])", ".nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) ==", "assert n.kind is list assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children)", "[ n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ] def", "int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n", "n.kind is expect_kind assert n.value == expect_value assert n.is_leaf def verify_collection(self, n, expect_kind,", "parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3,", "Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self):", "int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b])", "= Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234)", "bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5,", "list, [123]) def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list, [None, True,", "\"tuple\": (4, 5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } )", "list assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1 n3", "n2.value == [] assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [],", "== [] foo = n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0] assert", "assert n.children == expect_children # singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None),", "4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\",", "parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def", "= Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is list assert n.value ==", "is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v", ".dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3", "assert n.name == \"\" assert n.kind is list assert n.value == [[[\"foo\"]]] assert", "= Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",))", "Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v in expect_value.items() ] else: expect_children", "Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a =", "[[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list,", "bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int,", "Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\":", "assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert", "\"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self):", "= Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n =", "Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def", "# nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\" assert", "{\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456,", "5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node):", "itself assert n.name == \"\" assert n.kind is float assert str(n.value) == \"nan\"", "children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int,", "is list assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1", "test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None, True,", "self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self):", "\"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self):", "test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n,", "not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n", "parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\":", "singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n =", "= Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\"))", "assert n.name == \"\" assert n.kind is list assert n.value == [[]] assert", "assert len(n.children) == 1 n2 = n.children[0] assert n2.name == \"[0]\" assert n2.kind", "n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind", "self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self):", "\"foo\") # lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self):", "[], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind", "test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo =", "key=k) for k, v in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c),", "assert n2.name == \"[0]\" assert n2.kind is list assert n2.value == [] assert", "Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be", "n2.name == \"[0]\" assert n2.kind is list assert n2.value == [[\"foo\"]] assert not", "def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None,", "assert n.value == [[]] assert not n.is_leaf assert len(n.children) == 1 n2 =", "2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\",", "list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n", "TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def", "test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) #", "Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def", "len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert", "([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\", ") foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2,", "in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i,", "789, key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2},", "lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\" assert n.kind is", "2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo = Node( \".foo\", dict, {\"a\":", "n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") #", "def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n", "Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors())", "test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self): n =", "1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n =", "def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\",", "self.verify_collection(n, list, [123, -456, 789]) # nested lists def test_list_of_empty_list(self): n = Node.build([[]])", "c in enumerate(expect_value) ] assert n.children == expect_children # singletons def test_None(self): n", "/dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/*", "321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4, 5, 6),", "{\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n,", "== [[]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert", "not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert n2.name == \"[0]\"", "self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n", "self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self):", "\"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class", "assert n.value == expect_value assert n.kind in {list, tuple, set, dict} assert not", "Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list,", "def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False},", "verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind", ".nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\":", "{}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self):", "1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar", "def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789]) #", "Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz)", "n = Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self): n = Node.build(0)", "set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n", "= Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts", "== expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name ==", "for i, c in enumerate(expect_value) ] assert n.children == expect_children # singletons def", "assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True])", "def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\" assert n.kind is list", "def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self): n", "class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")]", "False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n = Node.build([123, -456, 789])", "n.kind is list assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) ==", "True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123,", "== \"nan\" assert n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str,", "expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind assert n.value == expect_value", "def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678)", "browson.node import Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name", "sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n =", "def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0)", "list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert", "parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [", "float assert str(n.value) == \"nan\" assert n.is_leaf # strings def test_empty_string(self): n =", "n2 = n.children[0] assert n2.name == \"[0]\" assert n2.kind is list assert n2.value", "-321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def test_set_empty(self): n = Node.build(set())", "Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") #", "Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in enumerate(expect_value) ] assert n.children ==", "= Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789]) # nested lists def", "3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\",", "dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789})", "Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n =", "n = Node.build(float(\"nan\")) # NaN cannot be compared to itself assert n.name ==", "[]) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n =", "foo = n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors()) ==", "bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\",", "tuple, set, dict} assert not n.is_leaf assert len(n.children) == len(expect_value) if n.kind is", "()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n =", "{\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict,", "n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int,", "if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for", "n2.kind is list assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) ==", "\"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\",", ".tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\"", "n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int,", "list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\",", "n = Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1,", "n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n =", "n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set,", "= Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot", "foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 =", "n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert n2.name == \"[0]\" assert", "= foo.children[0] assert list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert list(baz.ancestors()) ==", "= Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\",", "\"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4, 5, 6), \"set\":", "[None, True, False]) def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123,", "assert str(n.value) == \"nan\" assert n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\")", "[ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in enumerate(expect_value) ] assert n.children", "assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1 n2 =", "foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n", "Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n,", "n.value == [[]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0]", "list, [123, -456, 789]) # nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert", "self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None,", "test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is list assert", "n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n,", "assert n.kind is expect_kind assert n.value == expect_value assert n.kind in {list, tuple,", "v in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for", "self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self):", "[ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v in expect_value.items() ] else:", "6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar,", "<filename>tests/test_node.py<gh_stars>0 import textwrap from browson.node import Node class TestNode_build: def verify_scalar(self, n, expect_kind,", "n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0]", "str(n.value) == \"nan\" assert n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n,", "def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\":", "n.name == \"\" assert n.kind is list assert n.value == [[]] assert not", "set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1", "baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321,", "test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n,", "parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0", "\"bar\": [3, 4], \"baz\": {5, 6}}) foo = Node( \".foo\", dict, {\"a\": 1,", "n.name == \"\" assert n.kind is float assert str(n.value) == \"nan\" assert n.is_leaf", "{ \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\":", "self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self):", "i, c in enumerate(expect_value) ] assert n.children == expect_children # singletons def test_None(self):", "parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar, bar_0,", "children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz)", "== \"[0]\" assert n2.kind is list assert n2.value == [] assert not n2.is_leaf", "123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict,", "n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0]", "bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\":", "self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\"", "= n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors()) == [foo,", "Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a,", "assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self):", "is expect_kind assert n.value == expect_value assert n.kind in {list, tuple, set, dict}", ".list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1", "Node.build([[]]) assert n.name == \"\" assert n.kind is list assert n.value == [[]]", "== expect_value assert n.kind in {list, tuple, set, dict} assert not n.is_leaf assert", "n.kind in {list, tuple, set, dict} assert not n.is_leaf assert len(n.children) == len(expect_value)", "is list assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1", "n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}})", "self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list, [None,", "test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n,", "import Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name ==", "n.name == expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.is_leaf", "key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ]", "True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self):", ".tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" )", "= Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\")", "\"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\",", "Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3],", "# sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n", "} ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3", "baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321, \"other_key\": None,", "None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n =", "def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\")", "key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0", "assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456,", "import textwrap from browson.node import Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value,", "test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123})", "expect_kind assert n.value == expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"):", "123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self): n =", ".nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}})", "{\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4, 5,", "int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n", "Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def", "assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]])", ".tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def", "{7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node) assert", "] assert n.children == expect_children # singletons def test_None(self): n = Node.build(None) self.verify_scalar(n,", "assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert n2.name ==", "= Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n,", "bar = foo.children[0] assert list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert list(baz.ancestors())", "\"[0]\" assert n2.kind is list assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert", "int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\",", "lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n =", "self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self):", "list assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1 n2", "\"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self): n", "n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [ n,", "-5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n =", "def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is", "assert n.name == \"\" assert n.kind is float assert str(n.value) == \"nan\" assert", "parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set,", "foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build(", "[n] bar = foo.children[0] assert list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert", "Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4],", "bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) # numbers def", "{5, 6}}) foo = Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\",", "bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 =", "parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[])", "self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self):", "n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool,", "assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples", "\"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n,", ".dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/*", "baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int,", "list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors()) == [foo, n] baz =", "[ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\",", "foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\",", "class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert", "in enumerate(expect_value) ] assert n.children == expect_children # singletons def test_None(self): n =", "Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ]", "self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n,", "def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be compared to itself assert", "int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz =", "456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self):", "key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\":", "\"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self):", "not n.is_leaf assert len(n.children) == len(expect_value) if n.kind is dict: expect_children = [", "test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123})", "n.children[0] assert n2.name == \"[0]\" assert n2.kind is list assert n2.value == []", "n.value == expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name", "def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self):", "def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is", "# numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n", "[3, 4], \"baz\": {5, 6}}) foo = Node( \".foo\", dict, {\"a\": 1, \"b\":", "bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\":", "== 1 n2 = n.children[0] assert n2.name == \"[0]\" assert n2.kind is list", "list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0]", "1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n =", "key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6,", "float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n", "= Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234)", "\"list\": [1, 2, 3], \"tuple\": (4, 5, 6), \"set\": {7, 8, 9}, \"nested\":", "== [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n),", "is float assert str(n.value) == \"nan\" assert n.is_leaf # strings def test_empty_string(self): n", "n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\",", "children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar)", "n.name == \"\" assert n.kind is list assert n.value == [[[\"foo\"]]] assert not", "dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n =", "n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\", parent=n), Node(\".baz\", int,", "else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in enumerate(expect_value)", "9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) ==", "123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456,", "123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789})", "== [n] bar = foo.children[0] assert list(bar.ancestors()) == [foo, n] baz = bar.children[0]", "assert not n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"],", "= Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo,", "assert n.value == expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert", "expect_value assert n.kind in {list, tuple, set, dict} assert not n.is_leaf assert len(n.children)", "baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n,", "Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple,", "# tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n", "int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3, 4], parent=n,", "n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str,", "list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1", ".set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n", "parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\":", "\"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4,", "6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\",", "int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\",", "# NaN cannot be compared to itself assert n.name == \"\" assert n.kind", "2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b", "== [] assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\")", "baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0,", "dict} assert not n.is_leaf assert len(n.children) == len(expect_value) if n.kind is dict: expect_children", "789]) # nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\"", "456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk:", "4], \"baz\": {5, 6}}) foo = Node( \".foo\", dict, {\"a\": 1, \"b\": 2},", "== \"\" assert n.kind is float assert str(n.value) == \"nan\" assert n.is_leaf #", "assert list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors()) == [n] bar =", "== \"\" assert n.kind is list assert n.value == [[]] assert not n.is_leaf", "parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int,", "n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list,", "789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self):", "list assert n.value == [[]] assert not n.is_leaf assert len(n.children) == 1 n2", "def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"})", "{\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors()) ==", "== [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3,", "-321)) # sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self):", "[ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True,", "456, \"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n),", ".tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors():", "def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/*", "] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in", "True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789})", ".dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/*", "= n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(())", "\"bar\", 123}) # dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def", "n.kind is expect_kind assert n.value == expect_value assert n.kind in {list, tuple, set,", "] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk())", "\"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent(", "Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n,", "tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n =", "# strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def test_short_string(self): n", "== [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert", "bar, bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( {", ".set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n =", "= Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a", "\"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is", "\"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\",", "n = Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float,", "assert n2.kind is list assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children)", "textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/*", "test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets", "expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c", "n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789]) # nested lists", "== len(expect_value) if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n,", "set, dict} assert not n.is_leaf assert len(n.children) == len(expect_value) if n.kind is dict:", "= Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n,", "assert list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert list(baz.ancestors()) == [bar, foo,", "list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ())", "{\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo = Node(", "== expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.kind in", "is list assert n.value == [[]] assert not n.is_leaf assert len(n.children) == 1", "def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234)", "assert n.kind is float assert str(n.value) == \"nan\" assert n.is_leaf # strings def", "assert n2.kind is list assert n2.value == [] assert not n2.is_leaf assert len(n2.children)", "def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) #", "4, parent=bar) bar.children.extend([bar_0, bar_1]) baz = Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[])", "self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self): n = Node.build({})", "set, {\"foo\", 456, \"bar\", 123}) # dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n,", "= Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\": [1, 2,", "n.children == expect_children # singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None)", "= Node.build(False) self.verify_scalar(n, bool, False) # numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n,", "k, v in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n)", "1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo = Node( \".foo\",", "float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n", "= Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n,", "def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def test_list_of_singletons(self): n = Node.build([None,", "list assert n2.value == [] assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2,", "parent=n, key=k) for k, v in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\",", ") def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == []", "list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert list(baz.ancestors()) == [bar, foo, n]", "def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",))", "assert n.kind is expect_kind assert n.value == expect_value assert n.is_leaf def verify_collection(self, n,", "assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/*", "v, parent=n, key=k) for k, v in expect_value.items() ] else: expect_children = [", "n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float,", "int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\":", "Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def", "[123, -456, 789]) # nested lists def test_list_of_empty_list(self): n = Node.build([[]]) assert n.name", "n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n),", "[1, 2, 3], \"tuple\": (4, 5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\":", "TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind", "parent=n) for i, c in enumerate(expect_value) ] assert n.children == expect_children # singletons", "n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n =", "= Node(\".baz\", set, {5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5,", ".dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/*", "n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\",", "[] foo = n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors())", "= Node.build([[]]) assert n.name == \"\" assert n.kind is list assert n.value ==", "== \"[0]\" assert n2.kind is list assert n2.value == [[\"foo\"]] assert not n2.is_leaf", "numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n =", "== [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool,", "bool, True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\":", "int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\":", "dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int,", "= Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0] assert", "int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk())", "3], \"tuple\": (4, 5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), }", "n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n =", "test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n,", "yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3", "= Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456,", "assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0,", "= [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v in expect_value.items() ]", "parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar =", "def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\":", "cannot be compared to itself assert n.name == \"\" assert n.kind is float", "expect_kind assert n.value == expect_value assert n.kind in {list, tuple, set, dict} assert", "expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v in expect_value.items()", ".nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert", "Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar)", "assert n.name == expect_name assert n.kind is expect_kind assert n.value == expect_value assert", "[\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n = Node.build(()) self.verify_collection(n, tuple, ()) def", "6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield", "Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo =", "type(v), v, parent=n, key=k) for k, v in expect_value.items() ] else: expect_children =", "is list assert n2.value == [] assert not n2.is_leaf assert len(n2.children) == 0", "n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\":", "foo.children[0] assert list(bar.ancestors()) == [foo, n] baz = bar.children[0] assert list(baz.ancestors()) == [bar,", "Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1]) baz", "test_list_of_empty_list(self): n = Node.build([[]]) assert n.name == \"\" assert n.kind is list assert", "str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [", "= Node.build(-5678) self.verify_scalar(n, int, -5678) def test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0)", "key=\"baz\", parent=n), ] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\":", "expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name", "Node(\".baz[0]\", int, 5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert", "n.kind is list assert n.value == [[]] assert not n.is_leaf assert len(n.children) ==", "Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def", "= Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\", list, [3,", "assert n2.value == [[\"foo\"]] assert not n2.is_leaf assert len(n2.children) == 1 n3 =", "n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def", "test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456,", "n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\":", "def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False)", "test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321, \"other_key\": None, \"last_key\": False}, \"list\":", "expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.is_leaf def verify_collection(self,", "list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int, 456, key=\"bar\",", "789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123, key=\"foo\", parent=n), Node(\".bar\", int,", "0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n =", "n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float,", "= Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5, 6}}) foo", "\"baz\": 789}) self.verify_collection(n, dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def", ".set[1]/int/* .set[2]/int/* .nested/tuple/1 .nested[0]/list/1 .nested[0][0]/dict/1 .nested[0][0].key/set/1 .nested[0][0].key[0]/str/*\"\"\" ) def test_node_ancestors(): n = Node.build({\"foo\":", "foo = Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] )", "[[]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0] assert n2.name", "n.children[0] assert n2.name == \"[0]\" assert n2.kind is list assert n2.value == [[\"foo\"]]", "parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n", "list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert", "from browson.node import Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert", "\"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\")", "Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\",", "tuple, (None, \"foo\", -321)) # sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set,", "self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, [])", "True, False]) def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456,", "Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def", "456, key=\"bar\", parent=n), Node(\".baz\", int, 789, key=\"baz\", parent=n), ] def test_nested_dict(self): n =", "Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name", "n = Node.build((\"foo\",)) self.verify_collection(n, tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321))", "type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n", "assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n),", "assert n.kind is list assert n.value == [[]] assert not n.is_leaf assert len(n.children)", "\"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4, 5, 6), \"set\": {7, 8,", "str, \"foo\") # lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def", "== \"\" assert n.kind is list assert n.value == [[[\"foo\"]]] assert not n.is_leaf", "\"baz\": {5, 6}}) foo = Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n,", "(None, \"foo\", -321)) # sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set())", "= [ Node(f\"{expect_name}[{i}]\", type(c), c, parent=n) for i, c in enumerate(expect_value) ] assert", "Node.build({\"foo\", 456, \"bar\", 123}) self.verify_collection(n, set, {\"foo\", 456, \"bar\", 123}) # dicts def", "test_float_zero(self): n = Node.build(0.0) self.verify_scalar(n, float, 0.0) def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n,", "tuple, (\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\",", "baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz,", "str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/*", "789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str,", "test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n,", "assert n2.name == \"[0]\" assert n2.kind is list assert n2.value == [[\"foo\"]] assert", "def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) ==", "def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\"))", "Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n = Node.build([123,", "== [Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk())", "1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self): n", "n.children[0] assert list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors()) == [foo, n]", "= Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\",", "False}, \"list\": [1, 2, 3], \"tuple\": (4, 5, 6), \"set\": {7, 8, 9},", "assert n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\") def", "test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n,", "baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b, bar, bar_0, bar_1,", "{list, tuple, set, dict} assert not n.is_leaf assert len(n.children) == len(expect_value) if n.kind", "# lists def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n", "str, \"foo\", parent=n), Node(\"[1]\", int, 123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def", "def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234)", "1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo,", "self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) # numbers", "test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n =", ") def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/*", "0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name ==", "[Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) ==", "None, \"last_key\": False}, \"list\": [1, 2, 3], \"tuple\": (4, 5, 6), \"set\": {7,", "[3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 =", "Node.build(\"foo\") assert list(n.dfwalk()) == [Node(\"\", str, \"foo\")] def test_simple_list(self): n = Node.build([\"foo\", 123,", "\"nan\" assert n.is_leaf # strings def test_empty_string(self): n = Node.build(\"\") self.verify_scalar(n, str, \"\")", "be compared to itself assert n.name == \"\" assert n.kind is float assert", "\"\" assert n.kind is list assert n.value == [[[\"foo\"]]] assert not n.is_leaf assert", "def test_node_ancestors(): n = Node.build({\"foo\": {\"bar\": {\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo", "== [ n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ]", "{5, 6}, parent=n, key=\"baz\", children=[]) baz_0 = Node(\".baz[0]\", int, 5, parent=baz) baz_1 =", "textwrap from browson.node import Node class TestNode_build: def verify_scalar(self, n, expect_kind, expect_value, expect_name=\"\"):", "bool, False) # numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def", "dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k, v in", "parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert", ".list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/* .tuple[2]/int/* .set/set/3 .set[0]/int/* .set[1]/int/* .set[2]/int/* .nested/tuple/1", "(4, 5, 6), \"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def", "(\"foo\",)) def test_tuple_heterogeneous(self): n = Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321))", "= Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123,", "n.value == expect_value assert n.kind in {list, tuple, set, dict} assert not n.is_leaf", "str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def", "n = Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n", "def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is list", "n = Node.build(float(\"-inf\")) self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN", "Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123]) def", "\"foo\", -321)) # sets def test_set_empty(self): n = Node.build(set()) self.verify_collection(n, set, set()) def", "key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\",", "foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n =", "False) # numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self):", "123}) # dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self):", "= Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123]) self.verify_collection(n, list, [123])", "\".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\",", "= Node(\".bar\", list, [3, 4], parent=n, key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3,", "in {list, tuple, set, dict} assert not n.is_leaf assert len(n.children) == len(expect_value) if", "Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self): n = Node.build(-5678) self.verify_scalar(n, int, -5678) def", "expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind assert n.value ==", "parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b =", "# singletons def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n", "n = Node.build(()) self.verify_collection(n, tuple, ()) def test_tuple_single_item(self): n = Node.build((\"foo\",)) self.verify_collection(n, tuple,", "self.verify_scalar(n, str, \"\") def test_short_string(self): n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists", "= Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n, bool, True)", "len(n.children) == len(expect_value) if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v,", "\"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/* .tuple/tuple/3 .tuple[0]/int/* .tuple[1]/int/*", "n.value == [[[\"foo\"]]] assert not n.is_leaf assert len(n.children) == 1 n2 = n.children[0]", "self.verify_scalar(n, float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be compared", "{\"baz\": \"xyzzy\"}}}) assert list(n.ancestors()) == [] foo = n.children[0] assert list(foo.ancestors()) == [n]", "Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\":", "= Node.build(set()) self.verify_collection(n, set, set()) def test_set_single_item(self): n = Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"})", "n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k) for k,", "Node.build(float(\"nan\")) # NaN cannot be compared to itself assert n.name == \"\" assert", "is expect_kind assert n.value == expect_value assert n.is_leaf def verify_collection(self, n, expect_kind, expect_value,", "\"set\": {7, 8, 9}, \"nested\": ([{\"key\": {\"value\"}}],), } ) def yield_str(node): yield str(node)", "== expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.is_leaf def", "def test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\"))", "def test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True)", "== 0 self.verify_collection(n2, list, [], \"[0]\") def test_list_of_list_of_list_of_one_string(self): n = Node.build([[[\"foo\"]]]) assert n.name", "= n.children[0] assert n2.name == \"[0]\" assert n2.kind is list assert n2.value ==", "n, foo, foo_a, foo_b, bar, bar_0, bar_1, baz, baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self):", "dict, {\"foo\": 123, \"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n =", "\"\" assert n.kind is list assert n.value == [[]] assert not n.is_leaf assert", "def test_list_empty(self): n = Node.build([]) self.verify_collection(n, list, []) def test_list_single_item(self): n = Node.build([123])", "n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n,", "[] assert not n2.is_leaf assert len(n2.children) == 0 self.verify_collection(n2, list, [], \"[0]\") def", "= Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4, parent=bar) bar.children.extend([bar_0, bar_1])", "Node.build(True) self.verify_scalar(n, bool, True) def test_False(self): n = Node.build(False) self.verify_scalar(n, bool, False) #", "Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789]) # nested lists def test_list_of_empty_list(self):", "] def test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4],", "test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self):", "def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n", "= Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def test_set_empty(self):", "self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\":", "test_float_nonzero(self): n = Node.build(1.234) self.verify_scalar(n, float, 1.234) def test_float_negative_inf(self): n = Node.build(float(\"-inf\")) self.verify_scalar(n,", "list, [None, True, False]) def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list,", "key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\") foo.children.extend([foo_a, foo_b]) bar = Node(\".bar\",", "\"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5 .dict/dict/3 .dict.key/int/* .dict.other_key/NoneType/* .dict.last_key/bool/* .list/list/3 .list[0]/int/* .list[1]/int/* .list[2]/int/*", "1 n2 = n.children[0] assert n2.name == \"[0]\" assert n2.kind is list assert", "assert not n.is_leaf assert len(n.children) == len(expect_value) if n.kind is dict: expect_children =", "n = Node.build(\"foo\") self.verify_scalar(n, str, \"foo\") # lists def test_list_empty(self): n = Node.build([])", "self.verify_scalar(n, bool, False) # numbers def test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0)", "= Node(\".foo.a\", int, 1, parent=foo, key=\"a\") foo_b = Node(\".foo.b\", int, 2, parent=foo, key=\"b\")", "assert list(foo.ancestors()) == [n] bar = foo.children[0] assert list(bar.ancestors()) == [foo, n] baz", "-456, 789]) self.verify_collection(n, list, [123, -456, 789]) # nested lists def test_list_of_empty_list(self): n", "Node.build([[[\"foo\"]]]) assert n.name == \"\" assert n.kind is list assert n.value == [[[\"foo\"]]]", "== 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\") # tuples def test_tuple_empty(self):", "test_None(self): n = Node.build(None) self.verify_scalar(n, type(None), None) def test_True(self): n = Node.build(True) self.verify_scalar(n,", "= Node.build({\"foo\"}) self.verify_collection(n, set, {\"foo\"}) def test_set_multiple(self): n = Node.build({\"foo\", 456, \"bar\", 123})", "int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) == [ n, foo, foo_a, foo_b,", "123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int, 123,", "len(expect_value) if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v), v, parent=n, key=k)", "def test_dict_multiple_items(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) self.verify_collection(n, dict, {\"foo\":", "compared to itself assert n.name == \"\" assert n.kind is float assert str(n.value)", "baz_0, baz_1, ] def test_str_visit_heterogeneous_structure(self): n = Node.build( { \"dict\": {\"key\": 321, \"other_key\":", "c, parent=n) for i, c in enumerate(expect_value) ] assert n.children == expect_children #", "n, expect_kind, expect_value, expect_name=\"\"): assert n.name == expect_name assert n.kind is expect_kind assert", "test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [", "Node.build({\"foo\": 123, \"bar\": 456, \"baz\": 789}) assert list(n.dfwalk()) == [ n, Node(\".foo\", int,", "test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str,", "Node.build((None, \"foo\", -321)) self.verify_collection(n, tuple, (None, \"foo\", -321)) # sets def test_set_empty(self): n", "dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def", "123, parent=n), Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123,", "{\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[] ) foo_a = Node(\".foo.a\", int, 1,", "float, float(\"-inf\")) def test_float_nan(self): n = Node.build(float(\"nan\")) # NaN cannot be compared to", "test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n, list, [123, -456, 789]) # nested", "test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123}) def test_dict_multiple_items(self): n =", "6}}) foo = Node( \".foo\", dict, {\"a\": 1, \"b\": 2}, parent=n, key=\"foo\", children=[]", "for k, v in expect_value.items() ] else: expect_children = [ Node(f\"{expect_name}[{i}]\", type(c), c,", "self.verify_collection(n, list, [None, True, False]) def test_list_of_ints(self): n = Node.build([123, -456, 789]) self.verify_collection(n,", "n.name == expect_name assert n.kind is expect_kind assert n.value == expect_value assert n.kind", "123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\", str, \"foo\", parent=n), Node(\"[1]\", int,", "assert len(n.children) == len(expect_value) if n.kind is dict: expect_children = [ Node(f\"{expect_name}.{k}\", type(v),", "test_zero(self): n = Node.build(0) self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n,", "n.kind is float assert str(n.value) == \"nan\" assert n.is_leaf # strings def test_empty_string(self):", "NaN cannot be compared to itself assert n.name == \"\" assert n.kind is", "# dicts def test_dict_empty(self): n = Node.build({}) self.verify_collection(n, dict, {}) def test_dict_single_item(self): n", "test_nested_dict(self): n = Node.build({\"foo\": {\"a\": 1, \"b\": 2}, \"bar\": [3, 4], \"baz\": {5,", "n2.kind is list assert n2.value == [] assert not n2.is_leaf assert len(n2.children) ==", "{\"value\"}}],), } ) def yield_str(node): yield str(node) assert \"\\n\".join(n.dfwalk(yield_str)) == textwrap.dedent( \"\"\"\\ /dict/5", "456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk()) ==", "\"bar\": 456, \"baz\": 789}) class TestNode_dfwalk: def test_leaf_node(self): n = Node.build(\"foo\") assert list(n.dfwalk())", "def test_list_of_singletons(self): n = Node.build([None, True, False]) self.verify_collection(n, list, [None, True, False]) def", "type(c), c, parent=n) for i, c in enumerate(expect_value) ] assert n.children == expect_children", "self.verify_collection(n, dict, {}) def test_dict_single_item(self): n = Node.build({\"foo\": 123}) self.verify_collection(n, dict, {\"foo\": 123})", "Node(\"[2]\", bool, True, parent=n), ] def test_simple_dict(self): n = Node.build({\"foo\": 123, \"bar\": 456,", "not n2.is_leaf assert len(n2.children) == 1 n3 = n2.children[0] self.verify_collection(n3, list, [\"foo\"], \"[0][0]\")", "self.verify_scalar(n, int, 0) def test_positive_int(self): n = Node.build(1234) self.verify_scalar(n, int, 1234) def test_negative_int(self):", "5, parent=baz) baz_1 = Node(\".baz[1]\", int, 6, parent=baz) baz.children.extend([baz_0, baz_1]) assert list(n.dfwalk()) ==", "key=\"bar\", children=[]) bar_0 = Node(\".bar[0]\", int, 3, parent=bar) bar_1 = Node(\".bar[1]\", int, 4,", "def test_simple_list(self): n = Node.build([\"foo\", 123, True]) assert list(n.dfwalk()) == [ n, Node(\"[0]\"," ]
[ "# print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result =", "勝敗を解釈 result = 0 break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score", "elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1 else: print(line2) assert False", "True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 =", "(i + 0.5) for i in range(BIN_SIZE)] y = list() y_each_phase = [list()", "score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index +", "= 3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)]", "for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for", "_ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i]))", "label = f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores = list() result =", "list() result = None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 =", "(turn % 2 == 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis =", "print(f\"勝者:{white}\") result = -1 else: print(line2) assert False break elif move == \"入玉宣言\":", "result = 0 break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score =", "// BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores),", "if move == \"同\": move += elements1[2] if move == \"投了\": # print(turn,", "line2 = f.readline().strip() # 勝敗を解釈 result = 0 break # 評価値を取得 score_index =", "/ BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase", "1 for i, score in enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH),", "False break elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn -", "print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i", "= elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2]", "in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for", "PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\")", "1 else: print(f\"勝者:{white}\") result = -1 break elif move == \"持将棋\": print(file_name, move)", "move == \"同\": move += elements1[2] if move == \"投了\": # print(turn, move,", "= [[list() for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0,", "phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\")", "= min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数", "as np import matplotlib.pyplot as plt import japanize_matplotlib from natsort import natsorted #", "natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31", "print(f\"勝者:{white}\") result = -1 break elif move == \"持将棋\": print(file_name, move) turns.append(turn -", "list() y_each_phase = [list() for _ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i]))", "= 0 break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index]", "for i, score in enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE", "f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black =", "\"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result", "break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている", "# 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 result =", "BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase =", "assert False break elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn", "plt import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns =", "print(turn, move, score) if (turn % 2 == 1 and is_miacis_black) or (turn", "y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\")", "result = None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split()", "i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name", "BIN_WIDTH * (i + 0.5) for i in range(BIN_SIZE)] y = list() y_each_phase", "# print(f\"勝者:{white}\") result = -1 else: print(line2) assert False break elif move ==", "== 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result = -1 break elif", "PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差", "\") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip()", "print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result = -1 break elif move ==", "x = [-1 + BIN_WIDTH * (i + 0.5) for i in range(BIN_SIZE)]", "total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score in enumerate(miacis_scores): index = min(int((score", "and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black else -result", "move == \"投了\": # print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す", "for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0]", "= [list() for _ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p", "= f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores = list() result = None", "in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in", "turn % 2 == 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result =", "{total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i + 0.5) for i", "= f.readline().strip() # 勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\") result =", "[[list() for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0,", "% 2 == 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result = -1", "turns = list() BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE result_points =", "f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() #", "[-1 + BIN_WIDTH * (i + 0.5) for i in range(BIN_SIZE)] y =", "f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1 elif", "import codecs import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib from", "min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\")", "range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names:", "i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\")", "f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores = list() result", "line2.split() # 指し手を取得 turn = int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう", "elements1[2] if move == \"投了\": # print(turn, move, end=\" \") turns.append(turn - 1)", "in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend() plt.xlabel(\"評価値(探索結果)\")", "= f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white = f.readline().strip() label =", "move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move +=", "else: print(f\"勝者:{white}\") result = -1 break elif move == \"持将棋\": print(file_name, move) turns.append(turn", "codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white", "+ BIN_WIDTH * (i + 0.5) for i in range(BIN_SIZE)] y = list()", "= natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date =", "もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE result_points", "move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2", "print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1", "= line2.split() # 指し手を取得 turn = int(elements1[0]) move = elements1[1] # 同* という行動は\"同", "print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け", "'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white = f.readline().strip()", "[0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name,", "# print(turn, move, score) if (turn % 2 == 1 and is_miacis_black) or", "if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 result = 0 break", "1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 result", "{np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 +", "0.5) for i in range(BIN_SIZE)] y = list() y_each_phase = [list() for _", "= result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i,", "# plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend() plt.xlabel(\"評価値(探索結果)\") plt.ylabel(\"平均報酬\") plt.savefig(\"evaluation_curve.png\",", "2 == 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result = -1 break", "startpos = f.readline().strip() black = f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black", "- result_for_miacis)] += 1 for i, score in enumerate(miacis_scores): index = min(int((score +", "miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)]", "= elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index + 1]", "-1 else: print(line2) assert False break elif move == \"入玉宣言\": print(file_name) print(turn, move,", "= f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores = list()", "0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black else", "index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase =", "move += elements1[2] if move == \"投了\": # print(turn, move, end=\" \") turns.append(turn", "move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す", "len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\")", "y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend() plt.xlabel(\"評価値(探索結果)\") plt.ylabel(\"平均報酬\") plt.savefig(\"evaluation_curve.png\", bbox_inches=\"tight\", pad_inches=0.05)", "print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\":", "is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1 -", "読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn %", "- 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈", "and is_miacis_black) or (turn % 2 == 0 and not is_miacis_black): miacis_scores.append(float(score) /", "f.readline().strip() black = f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\"", "2 == 1 and is_miacis_black) or (turn % 2 == 0 and not", "0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name, 'r',", "% 2 == 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result", "range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for i", "\"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\")", "line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result =", "という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2] if move == \"投了\":", "= f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split()", "line2: # print(f\"勝者:{white}\") result = -1 else: print(line2) assert False break elif move", "= list() result = None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1", "plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend() plt.xlabel(\"評価値(探索結果)\") plt.ylabel(\"平均報酬\") plt.savefig(\"evaluation_curve.png\", bbox_inches=\"tight\",", "elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2] if", "# 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\"", "marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x,", "f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores", "result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score", "評価値を取得 score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\"", "BIN_SIZE - 1) result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM -", "plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\",", "= f.readline().strip() # 勝敗を解釈 result = 0 break # 評価値を取得 score_index = elements2.index(\"評価値\")", "= 31 BIN_WIDTH = 2 / BIN_SIZE result_points = [list() for _ in", "= f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1", "in score: score += elements2[score_index + 1] # print(turn, move, score) if (turn", "指し手を取得 turn = int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move", "if move == \"投了\": # print(turn, move, end=\" \") turns.append(turn - 1) #", "f.readline().strip() # 勝敗を解釈 result = 0 break # 評価値を取得 score_index = elements2.index(\"評価値\") +", "codecs import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib from natsort", "in range(BIN_SIZE)] y = list() y_each_phase = [list() for _ in range(PHASE_NUM)] for", "== \"投了\": # print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if", "[list() for _ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in", "1 and is_miacis_black) or (turn % 2 == 0 and not is_miacis_black): miacis_scores.append(float(score)", "+= elements1[2] if move == \"投了\": # print(turn, move, end=\" \") turns.append(turn -", "in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names =", "== \"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn % 2 == 1:", "# 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if", "print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i + 0.5)", "+= elements2[score_index + 1] # print(turn, move, score) if (turn % 2 ==", "1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i * PHASE_NUM //", "range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for", "if \"詰\" in score: score += elements2[score_index + 1] # print(turn, move, score)", "from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE =", "score: score += elements2[score_index + 1] # print(turn, move, score) if (turn %", "'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white =", "y_each_phase = [list() for _ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for", "elements2 = line2.split() # 指し手を取得 turn = int(elements1[0]) move = elements1[1] # 同*", "move == \"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] ==", "1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1 else: print(line2) assert", "# 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip()", "line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 =", "score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in", "+ 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score +=", "= list() BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE result_points = [list()", "\"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2", "\"同\": move += elements1[2] if move == \"投了\": # print(turn, move, end=\" \")", "\"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1 else: print(line2) assert False break", "* (i + 0.5) for i in range(BIN_SIZE)] y = list() y_each_phase =", "glob import codecs import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib", "y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p],", "= [list() for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for", "5000) result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1", "2 == 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if", "# print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] ==", "== \"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\")", "# 勝敗を解釈 result = 0 break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1", "import matplotlib.pyplot as plt import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける #", "<gh_stars>1-10 #!/usr/bin/env python3 import glob import codecs import numpy as np import matplotlib.pyplot", "for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\")", "in line2: # print(f\"勝者:{white}\") result = -1 else: print(line2) assert False break elif", "line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 result = 0 break #", "# 指し手を取得 turn = int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if", "# 勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\") result = 1 else:", "else: print(line2) assert False break elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\"", "勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in", "else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score in enumerate(miacis_scores): index", "for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\",", "p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM):", "= None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() #", "f.readline().strip() # 勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\") result = 1", "result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list()", "PHASE_NUM = 3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for i in", "== \"**\": line2 = f.readline().strip() # 勝敗を解釈 result = 0 break # 評価値を取得", "= list() y_each_phase = [list() for _ in range(PHASE_NUM)] for i in range(BIN_SIZE):", "print(line2) assert False break elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \")", "評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得 turn = int(elements1[0]) move", "*\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2] if move == \"投了\": #", "result = 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1 else:", "file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos =", "= 1 else: print(f\"勝者:{white}\") result = -1 break elif move == \"持将棋\": print(file_name,", "min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i *", "読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 result = 0", "is_miacis_black = \"Miacis\" in black miacis_scores = list() result = None while True:", "\"Miacis\" in black miacis_scores = list() result = None while True: # 指し手が記述されている行を読み込み", "or (turn % 2 == 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis", "if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn % 2", "date = f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white = f.readline().strip() label", "同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2] if move ==", "勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\")", "if turn % 2 == 1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result", "-result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score in enumerate(miacis_scores): index =", "# もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE", "{len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\")", "elements2[score_index + 1] # print(turn, move, score) if (turn % 2 == 1", "turn = int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move ==", "0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis')", "break elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn - 1)", "= line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得 turn", "total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f", "(turn % 2 == 1 and is_miacis_black) or (turn % 2 == 0", "print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1", "f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores = list() result = None while", "line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn % 2 ==", "もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH = 2 /", "natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH =", "print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH", "for _ in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM):", "BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM", "= f.readline().strip() elements2 = line2.split() # 指し手を取得 turn = int(elements1[0]) move = elements1[1]", "score in enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1)", "+ 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i * PHASE_NUM", "not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1", "y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p", "1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index", "- 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\")", "black miacis_scores = list() result = None while True: # 指し手が記述されている行を読み込み line1 =", "result = -1 break elif move == \"持将棋\": print(file_name, move) turns.append(turn - 1)", "p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend()", "% 2 == 1 and is_miacis_black) or (turn % 2 == 0 and", "1) result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result)", "elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score", "result = 1 else: print(f\"勝者:{white}\") result = -1 break elif move == \"持将棋\":", "None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み", "import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH", "if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2:", "result_for_miacis)] += 1 for i, score in enumerate(miacis_scores): index = min(int((score + 1)", "= min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase = min(i", "import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib from natsort import", "# もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE = 31 BIN_WIDTH = 2", "== 1 and is_miacis_black) or (turn % 2 == 0 and not is_miacis_black):", "# 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move += elements1[2] if move", "= -1 break elif move == \"持将棋\": print(file_name, move) turns.append(turn - 1) #", "* PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数", "line2 = f.readline().strip() # 勝敗を解釈 if turn % 2 == 1: print(f\"勝者:{black}\") result", "import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list()", "{np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x =", "range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y,", "numpy as np import matplotlib.pyplot as plt import japanize_matplotlib from natsort import natsorted", "# 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index + 1] # print(turn,", "== \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if", "japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns = list() BIN_SIZE", "= [-1 + BIN_WIDTH * (i + 0.5) for i in range(BIN_SIZE)] y", "elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得", "1] # print(turn, move, score) if (turn % 2 == 1 and is_miacis_black)", "as plt import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける turns", "指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2", "white = f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in black miacis_scores =", "= 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result = -1 else: print(line2)", "file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date", "BIN_WIDTH = 2 / BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM", "in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): #", "3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis", "print(file_name) print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] ==", "\"投了\": # print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2]", "elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index + 1] #", "line1.split() # 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得 turn =", "while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip() elements1 = line1.split() # 評価値が記述されている行を読み込み line2", "= int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\":", "result_points_each_phase = [[list() for _ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis =", "range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\", label=\"理論値\") plt.legend() plt.xlabel(\"評価値(探索結果)\") plt.ylabel(\"平均報酬\")", "if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2:", "i, score in enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE -", "score) if (turn % 2 == 1 and is_miacis_black) or (turn % 2", "+= 1 for i, score in enumerate(miacis_scores): index = min(int((score + 1) //", "black = f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in", "move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip()", "0 break # 評価値を取得 score_index = elements2.index(\"評価値\") + 1 score = elements2[score_index] #", "{np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH *", "result = -1 else: print(line2) assert False break elif move == \"入玉宣言\": print(file_name)", "python3 import glob import codecs import numpy as np import matplotlib.pyplot as plt", "in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip()", "range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\"))", "label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x,", "# for p in range(PHASE_NUM): # plt.plot(x, y_each_phase[p], marker=\".\", label=f\"Miacis探索結果{p}\") plt.plot(x, x, linestyle=\"dashed\",", "_ in range(BIN_SIZE)] for i in range(PHASE_NUM)] total_result_for_miacis = [0, 0, 0] file_names", "\"詰\" in score: score += elements2[score_index + 1] # print(turn, move, score) if", "print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x", "is_miacis_black) or (turn % 2 == 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000)", "{total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i + 0.5) for i in", "line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得 turn = int(elements1[0]) move =", "== \"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\":", "natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip()", "= f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black = \"Miacis\" in black", "f.readline().strip() startpos = f.readline().strip() black = f.readline().strip() white = f.readline().strip() label = f.readline().strip()", "= 2 / BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM =", "matplotlib.pyplot as plt import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける # もし終盤が弱い→序盤・中盤は良いのに終盤で負ける", "1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if", "end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 =", "詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score: score += elements2[score_index + 1] # print(turn, move,", "in enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result)", "i in range(BIN_SIZE)] y = list() y_each_phase = [list() for _ in range(PHASE_NUM)]", "np import matplotlib.pyplot as plt import japanize_matplotlib from natsort import natsorted # もし序盤が弱い→序盤から悪くしてそのまま負ける", "is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score in enumerate(miacis_scores):", "for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for _ in", "in black miacis_scores = list() result = None while True: # 指し手が記述されている行を読み込み line1", "for i in range(BIN_SIZE)] y = list() y_each_phase = [list() for _ in", "= -1 else: print(line2) assert False break elif move == \"入玉宣言\": print(file_name) print(turn,", "読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in", "in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") #", "\"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2: #", "range(BIN_SIZE)] y = list() y_each_phase = [list() for _ in range(PHASE_NUM)] for i", "{np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i +", "-1 break elif move == \"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す", "print(f\"{total_result_for_miacis[0]}勝 {total_result_for_miacis[1]}引き分け {total_result_for_miacis[2]}敗\") x = [-1 + BIN_WIDTH * (i + 0.5) for", "= [0, 0, 0] file_names = natsorted(glob.glob(\"./*.kif\")) for file_name in file_names: f =", "elif move == \"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn - 1) #", "for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in", "turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() #", "# 勝敗を解釈 if \"先手の勝ち\" in line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\"", "+ 1] # print(turn, move, score) if (turn % 2 == 1 and", "31 BIN_WIDTH = 2 / BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)]", "score += elements2[score_index + 1] # print(turn, move, score) if (turn % 2", "= codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black = f.readline().strip()", "2 / BIN_SIZE result_points = [list() for _ in range(BIN_SIZE)] PHASE_NUM = 3", "enumerate(miacis_scores): index = min(int((score + 1) // BIN_WIDTH), BIN_SIZE - 1) result_points[index].append(result) phase", "for file_name in file_names: f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos", "# 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if turn", "move, score) if (turn % 2 == 1 and is_miacis_black) or (turn %", "in line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\")", "line2[0:2] == \"**\": line2 = f.readline().strip() # 勝敗を解釈 if \"先手の勝ち\" in line2: #", "range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x, y, marker=\".\", label=\"Miacisの探索結果\") # for p in range(PHASE_NUM): # plt.plot(x,", "\"**\": line2 = f.readline().strip() # 勝敗を解釈 result = 0 break # 評価値を取得 score_index", "// len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数", "import glob import codecs import numpy as np import matplotlib.pyplot as plt import", "y = list() y_each_phase = [list() for _ in range(PHASE_NUM)] for i in", "result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\") print(f\"{total_result_for_miacis[0]}勝", "== 0 and not is_miacis_black): miacis_scores.append(float(score) / 5000) result_for_miacis = result if is_miacis_black", "\"入玉宣言\": print(file_name) print(turn, move, end=\" \") turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2]", "# 評価値が記述されている行を読み込み line2 = f.readline().strip() elements2 = line2.split() # 指し手を取得 turn = int(elements1[0])", "miacis_scores = list() result = None while True: # 指し手が記述されている行を読み込み line1 = f.readline().strip()", "#!/usr/bin/env python3 import glob import codecs import numpy as np import matplotlib.pyplot as", "+ 0.5) for i in range(BIN_SIZE)] y = list() y_each_phase = [list() for", "[list() for _ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for _", "list() BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE result_points = [list() for", "file_names: f = codecs.open(file_name, 'r', 'shift_jis') date = f.readline().strip() startpos = f.readline().strip() black", "if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for i, score in", "- 1) result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1)", "line2: # print(f\"勝者:{black}\") result = 1 elif \"後手の勝ち\" in line2: # print(f\"勝者:{white}\") result", "result_points[index].append(result) phase = min(i * PHASE_NUM // len(miacis_scores), PHASE_NUM - 1) result_points_each_phase[phase][index].append(result) print(f\"対局数", "= elements2.index(\"評価値\") + 1 score = elements2[score_index] # 詰みだとスペース区切りで次に手数が記録されるため分割されている if \"詰\" in score:", "in range(PHASE_NUM)] for i in range(BIN_SIZE): y.append(np.mean(result_points[i])) for p in range(PHASE_NUM): y_each_phase[p].append(np.mean(result_points_each_phase[p][i])) plt.plot(x,", "= \"Miacis\" in black miacis_scores = list() result = None while True: #", "/ 5000) result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] +=", "1: print(f\"勝者:{black}\") result = 1 else: print(f\"勝者:{white}\") result = -1 break elif move", "print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2] == \"**\": line2 =", "elif move == \"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if line2[0:2]", "== \"同\": move += elements1[2] if move == \"投了\": # print(turn, move, end=\"", "result_for_miacis = result if is_miacis_black else -result total_result_for_miacis[int(1 - result_for_miacis)] += 1 for", "1) result_points_each_phase[phase][index].append(result) print(f\"対局数 {len(turns)}\") print(f\"最小手数 {np.min(turns)}\") print(f\"最大手数 {np.max(turns)}\") print(f\"平均手数 {np.mean(turns)}\") print(f\"標準偏差 {np.std(turns)}\") print(\"Miacisから見た勝敗\")", "_ in range(BIN_SIZE)] PHASE_NUM = 3 result_points_each_phase = [[list() for _ in range(BIN_SIZE)]", "BIN_SIZE = 31 BIN_WIDTH = 2 / BIN_SIZE result_points = [list() for _", "if (turn % 2 == 1 and is_miacis_black) or (turn % 2 ==", "= f.readline().strip() black = f.readline().strip() white = f.readline().strip() label = f.readline().strip() is_miacis_black =", "int(elements1[0]) move = elements1[1] # 同* という行動は\"同 *\"と記録されるため分割されてしまう if move == \"同\": move", "f.readline().strip() elements2 = line2.split() # 指し手を取得 turn = int(elements1[0]) move = elements1[1] #", "break elif move == \"持将棋\": print(file_name, move) turns.append(turn - 1) # 読み筋が記録されている場合があるのでコメントだったら読み込み直す if" ]
[ "#!/usr/bin/env python # Copyright 2013 Netflix \"\"\"Push all repos to stash \"\"\" from", "to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def main(): run_for_all_repos('git push origin master')", "\"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def main(): run_for_all_repos('git", "python # Copyright 2013 Netflix \"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos", "Netflix \"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def main():", "all repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def main(): run_for_all_repos('git push", "Copyright 2013 Netflix \"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos", "repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def main(): run_for_all_repos('git push origin", "2013 Netflix \"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos import run_for_all_repos def", "# Copyright 2013 Netflix \"\"\"Push all repos to stash \"\"\" from nflx_oc.commands.dev.repos import" ]
[ "def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def", "== f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f", "check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out", "return errors def print_integrity_errors(errors, mesh): for attr, index, message in errors: try: data", "\"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for attr, index, message in errors:", "== f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0],", "attr)[index] except (AttributeError, IndexError): data = '' print(\"{} {} {} {}\".format(attr, index, message,", "1] == f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] == f[:,", "mesh): for attr, index, message in errors: try: data = getattr(mesh, attr)[index] except", "faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh):", "0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] == f[:,", "])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ]))", ">= len(v))[0], ])) def check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v):", "f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:,", "np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f <", "0] == f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] == f[:,", "= getattr(mesh, attr)[index] except (AttributeError, IndexError): data = '' print(\"{} {} {} {}\".format(attr,", "== f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0],", "__future__ import print_function import numpy as np def faces_with_repeated_vertices(f): if f.shape[1] == 3:", "for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index", "0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors = [] for f_index in", "2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def", "in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f):", "f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([", "try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data = '' print(\"{} {}", "f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for attr, index, message in", "faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\",", "\"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return", "2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] ==", "import print_function import numpy as np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return", "v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors", "if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0]", "f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:,", "index, message in errors: try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data", "def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0],", "f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index in", "return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors =", "return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:,", "range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors,", "1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else:", "== f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0],", "np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1]", "== f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:,", "errors: try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data = '' print(\"{}", "f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0]", "np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] ==", "3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f", "of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def", "f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >=", "in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for attr,", "len(v))[0], ])) def check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\",", "np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors = [] for", "for attr, index, message in errors: try: data = getattr(mesh, attr)[index] except (AttributeError,", "f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for", "np.where(f[:, 1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:,", "= [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\"))", "vertex\")) return errors def print_integrity_errors(errors, mesh): for attr, index, message in errors: try:", "f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ]))", "from __future__ import print_function import numpy as np def faces_with_repeated_vertices(f): if f.shape[1] ==", "np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] ==", "2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0],", "errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for attr, index, message", "2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] ==", "in errors: try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data = ''", "faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh): for attr, index,", "message in errors: try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data =", "f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:,", "0] == f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] == f[:,", "out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors", "1] == f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v):", "])) def check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index,", "f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ]))", "data = getattr(mesh, attr)[index] except (AttributeError, IndexError): data = '' print(\"{} {} {}", "print_function import numpy as np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([", "])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:,", "except (AttributeError, IndexError): data = '' print(\"{} {} {} {}\".format(attr, index, message, data))", "1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1]", "errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated", "== 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:,", "[] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for", "3])[0], ])) def faces_with_out_of_range_vertices(f, v): return np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0],", "def print_integrity_errors(errors, mesh): for attr, index, message in errors: try: data = getattr(mesh,", "== f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0],", "0] == f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([", "f_index, \"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\"))", "np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else: return", "numpy as np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0]", "np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f,", "as np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] ==", "1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0],", "== f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f, v): return", "errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex out of", "import numpy as np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:,", "np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] ==", "mesh.v): errors.append((\"f\", f_index, \"Vertex out of range\")) for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index,", "for f_index in faces_with_repeated_vertices(mesh.f): errors.append((\"f\", f_index, \"Repeated vertex\")) return errors def print_integrity_errors(errors, mesh):", "np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0]", "f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:, 0]", "== f[:, 2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0],", "3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2]", "errors def print_integrity_errors(errors, mesh): for attr, index, message in errors: try: data =", "== f[:, 2])[0], np.where(f[:, 1] == f[:, 2])[0], ])) else: return np.unique(np.concatenate([ np.where(f[:,", "< 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors = [] for f_index", "else: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0],", "np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] ==", "np.where(f[:, 1] == f[:, 3])[0], np.where(f[:, 2] == f[:, 3])[0], ])) def faces_with_out_of_range_vertices(f,", "faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:,", "np.unique(np.concatenate([ np.where(f < 0)[0], np.where(f >= len(v))[0], ])) def check_integrity(mesh): errors = []", "print_integrity_errors(errors, mesh): for attr, index, message in errors: try: data = getattr(mesh, attr)[index]", "2])[0], np.where(f[:, 0] == f[:, 3])[0], np.where(f[:, 1] == f[:, 2])[0], np.where(f[:, 1]", "3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0],", "np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 0] ==", "f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:, 1])[0], np.where(f[:, 0] ==", "def check_integrity(mesh): errors = [] for f_index in faces_with_out_of_range_vertices(mesh.f, mesh.v): errors.append((\"f\", f_index, \"Vertex", "np def faces_with_repeated_vertices(f): if f.shape[1] == 3: return np.unique(np.concatenate([ np.where(f[:, 0] == f[:,", "attr, index, message in errors: try: data = getattr(mesh, attr)[index] except (AttributeError, IndexError):", "getattr(mesh, attr)[index] except (AttributeError, IndexError): data = '' print(\"{} {} {} {}\".format(attr, index,", "0] == f[:, 1])[0], np.where(f[:, 0] == f[:, 2])[0], np.where(f[:, 1] == f[:," ]
[ "request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label =", "# Get the top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and print", "[idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of", "#top5_idx = results[0].sort()[1][-5:] # Lookup and print the top 5 labels #top5_labels =", ") ## Predict #results = model_neuron( image ) # Get the top 5", "normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"),", "sample image and normalize it into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456,", "= num_infer throughput = current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer =", "pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i in range(len(pred_list)):", "transforms, datasets ## Create an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True)", "model_neuron( image ) # Get the top 5 results #top5_idx = results[0].sort()[1][-5:] #", "idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a sample image and", "0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(),", "= num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while", "num_infer throughput = current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer", ") # Get the top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and", "image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once", "time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in", "def one_thread(pred, input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result", "= [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2],", "224]), transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...])", "in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE", "for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE #", "import request from torchvision import models, transforms, datasets ## Create an image directory", "pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3],", "num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer - last_num_infer", "= torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ## Load model #model_neuron =", "- last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference", "while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i", "import json import numpy as np from concurrent import futures from urllib import", "= [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a sample image and normalize", "5 labels #top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels)", "in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1],", "num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput))", "NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer", "print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer =", "img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in enumerate(pred_list): executor.submit(one_thread, pred, image, i)", "as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ##", "import os import time import torch import torch_neuron import json import numpy as", "print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer <", "pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3],", "mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]),", "pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ]", "pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred,", "a sample image and normalize it into a tensor normalize = transforms.Normalize( mean=[0.485,", "image ) # Get the top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup", "a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the", "] num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index):", "torch import torch_neuron import json import numpy as np from concurrent import futures", "top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx =", "# Lookup and print the top 5 labels #top5_labels = [idx2label[idx] for idx", "range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer -", "= results[0].sort()[1][-5:] # Lookup and print the top 5 labels #top5_labels = [idx2label[idx]", "5 labels:\\n {}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD", "= json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a sample", "i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput =", "inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in enumerate(pred_list): executor.submit(one_thread, pred,", "in range(len(class_idx))] ## Import a sample image and normalize it into a tensor", "the top 5 labels #top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top 5", "= 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list =", "an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch", "num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer - last_num_infer print('current throughput:", "NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list", ") for _ in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1],", "num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \",", "= transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([", "pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for", "np from concurrent import futures from urllib import request from torchvision import models,", "num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE", "_ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ##", "for i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput", "of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt'", "print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3}", "current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run", "pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = []", "datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0]", "range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2],", "range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with", "print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE *", "classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file)", "def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS: \",", "torchvision import models, transforms, datasets ## Create an image directory containing a small", "small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top", "last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE)", "and print the top 5 labels #top5_labels = [idx2label[idx] for idx in top5_idx]", "in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def", "0 for i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer", "image and normalize it into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406],", "read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import", "into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset", "json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a sample image", "= [idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end", "directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to", "## Predict #results = model_neuron( image ) # Get the top 5 results", "pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2],", "num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer", "futures from urllib import request from torchvision import models, transforms, datasets ## Create", "idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label =", "\"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = []", "os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\")", ") # end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list", "torch_neuron import json import numpy as np from concurrent import futures from urllib", "class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a", "= [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1]", "top 5 labels #top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n", "100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list = [", "for _ in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1],", "kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top classifications", "throughput = current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0)", "* USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i in range(len(pred_list)): num_infer =", "request from torchvision import models, transforms, datasets ## Create an image directory containing", "top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE =", "pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i", "images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1)", "\", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list):", "## Import a sample image and normalize it into a tensor normalize =", "Import a sample image and normalize it into a tensor normalize = transforms.Normalize(", "a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset =", "= [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list = [ pred_list[0], pred_list[0],", "len(pred_list): num_infer = 0 for i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i]", ") image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer", "current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list))", "= 0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE:", "print the top 5 labels #top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top", "\"r\") as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))]", "THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD", "time import torch import torch_neuron import json import numpy as np from concurrent", "# begin of infer once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' )", "transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) #", "= torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image ) # Get", "as np from concurrent import futures from urllib import request from torchvision import", "last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0':", "import torch import torch_neuron import json import numpy as np from concurrent import", "exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label", "...]) # begin of infer once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt'", "num_infer = 0 for i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer", "it into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])", "open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k in", "result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer", "'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image ) # Get the top", "0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image,", "for k in range(len(class_idx))] ## Import a sample image and normalize it into", "range(len(class_idx))] ## Import a sample image and normalize it into a tensor normalize", "with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global", "= current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) #", "in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer", "infer once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results", "pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3],", "]) ) image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of", "os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0] image", "import time import torch import torch_neuron import json import numpy as np from", "## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron(", "transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis,", "the top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and print the top", "#print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE = 50", "50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)]", "pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0)", "= 0 for i in range(len(pred_list)): num_infer = num_infer + num_infer_per_thread[i] current_num_infer =", "results #top5_idx = results[0].sort()[1][-5:] # Lookup and print the top 5 labels #top5_labels", "_ in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1],", "= [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread", "pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def", "USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i in range(len(pred_list)): num_infer = num_infer", "#top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) #", "#model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image ) #", "<reponame>aws-samples/aws-inf1-gcr-workshop import os import time import torch import torch_neuron import json import numpy", "eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _", "for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of infer", "= pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer =", "USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _", "normalize it into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,", "image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels", "models, transforms, datasets ## Create an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\",", "current_num_infer = num_infer throughput = current_num_infer - last_num_infer print('current throughput: {} images/sec'.format(throughput)) last_num_infer", "torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image ) # Get the", "idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) ) # end of infer once", "pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread", "last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput)", "= eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ## Load", "end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load(", "0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \",", "= datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _ =", "num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD)", "numpy as np from concurrent import futures from urllib import request from torchvision", "infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' )", "labels:\\n {}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD =", "[torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0],", "\", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0", "## Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with", "torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ## Load model #model_neuron = torch.jit.load(", "num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i in", "import futures from urllib import request from torchvision import models, transforms, datasets ##", "= 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in", "urllib import request from torchvision import models, transforms, datasets ## Create an image", "with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for k", "once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results =", "# end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list =", "for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for _", "model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image )", "one_thread(pred, input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result =", "[class_idx[str(k)][1] for k in range(len(class_idx))] ## Import a sample image and normalize it", "USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer = num_infer", "begin of infer once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ##", "results[0].sort()[1][-5:] # Lookup and print the top 5 labels #top5_labels = [idx2label[idx] for", "in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD):", "global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] +=", "5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and print the top 5 labels", "index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index]", "pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread = [] for i in", "Fetch labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\",", "datasets ## Create an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\",", "0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) )", "num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad():", "Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in enumerate(pred_list): executor.submit(one_thread,", "pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3], pred_list[3], pred_list[3], pred_list[3], ] num_infer_per_thread =", "[] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label = [class_idx[str(k)][1] for", "k in range(len(class_idx))] ## Import a sample image and normalize it into a", "containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ## Fetch labels to output", "from concurrent import futures from urllib import request from torchvision import models, transforms,", "## Create an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\")", "std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ])", "+= USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer =", "json import numpy as np from concurrent import futures from urllib import request", "from urllib import request from torchvision import models, transforms, datasets ## Create an", "0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize,", "pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for _ in range(4)] pred_list = [ pred_list[0],", "NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i in range(len(pred_list)): num_infer", "range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput():", "{}\".format(top5_labels) ) # end of infer once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100", "print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS:", "len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE", "{} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor =", "and normalize it into a tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229,", "Get the top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and print the", "torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread", "normalize, ]) ) image, _ = eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin", "import models, transforms, datasets ## Create an image directory containing a small kitten", "throughput: {} images/sec'.format(throughput)) last_num_infer = current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor", "eval_dataset[0] image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ## Load model", "transforms.Compose([ transforms.Resize([224, 224]), transforms.ToTensor(), normalize, ]) ) image, _ = eval_dataset[0] image =", "i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for _ in", "image = torch.tensor(image.numpy()[np.newaxis, ...]) # begin of infer once ## Load model #model_neuron", "USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0 for", "# Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in enumerate(pred_list):", "concurrent import futures from urllib import request from torchvision import models, transforms, datasets", "= model_neuron( image ) # Get the top 5 results #top5_idx = results[0].sort()[1][-5:]", "request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx = json.load(read_file) idx2label", "from torchvision import models, transforms, datasets ## Create an image directory containing a", "transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder( os.path.dirname(\"./torch_neuron_test/\"), transforms.Compose([ transforms.Resize([224,", "top 5 results #top5_idx = results[0].sort()[1][-5:] # Lookup and print the top 5", "[] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global num_infer_per_thread for", "once USER_BATCH_SIZE = 50 NUM_LOOPS_PER_THREAD = 100 pred_list = [torch.jit.load( 'resnet50_neuron.pt' ) for", "# print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM", "of infer once ## Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict", "global num_infer_per_thread num_infer = 0 last_num_infer = num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD:", "import numpy as np from concurrent import futures from urllib import request from", "Create an image directory containing a small kitten os.makedirs(\"./torch_neuron_test/images\", exist_ok=True) request.urlretrieve(\"https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg\", \"./torch_neuron_test/images/kitten_small.jpg\") ##", "labels #top5_labels = [idx2label[idx] for idx in top5_idx] #print(\"Top 5 labels:\\n {}\".format(top5_labels) )", "= num_infer + num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer - last_num_infer print('current", "#model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred in enumerate(pred_list): executor.submit(one_thread, pred, image,", "'resnet50_neuron.pt' ) for _ in range(4)] pred_list = [ pred_list[0], pred_list[0], pred_list[0], pred_list[0],", "to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as", "pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result) def current_throughput(): global num_infer_per_thread num_infer = 0", "< NUM_LOOPS_PER_THREAD * USER_BATCH_SIZE * len(pred_list): num_infer = 0 for i in range(len(pred_list)):", "#results = model_neuron( image ) # Get the top 5 results #top5_idx =", "tensor normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) eval_dataset = datasets.ImageFolder(", "Load model #model_neuron = torch.jit.load( 'resnet50_neuron.pt' ) ## Predict #results = model_neuron( image", "the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file: class_idx", "pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2], pred_list[3],", "* len(pred_list): num_infer = 0 for i in range(len(pred_list)): num_infer = num_infer +", "+ num_infer_per_thread[i] current_num_infer = num_infer throughput = current_num_infer - last_num_infer print('current throughput: {}", "Predict #results = model_neuron( image ) # Get the top 5 results #top5_idx", "num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch, index): global", "input_batch, index): global num_infer_per_thread for _ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch)", "_ in range(NUM_LOOPS_PER_THREAD): with torch.no_grad(): result = pred(input_batch) num_infer_per_thread[index] += USER_BATCH_SIZE # print(\"result\",result)", "Lookup and print the top 5 labels #top5_labels = [idx2label[idx] for idx in", "num_infer print(\"NUM THREADS: \", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer", "current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for i,pred", "\", len(pred_list)) print(\"NUM_LOOPS_PER_THREAD: \", NUM_LOOPS_PER_THREAD) print(\"USER_BATCH_SIZE: \", USER_BATCH_SIZE) while num_infer < NUM_LOOPS_PER_THREAD *", "= current_num_infer time.sleep(1.0) # Run inference #model_feed_dict={'input_1:0': img_arr3} executor = futures.ThreadPoolExecutor(max_workers=16+1) executor.submit(current_throughput) for", "os import time import torch import torch_neuron import json import numpy as np", "labels to output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\")", "import torch_neuron import json import numpy as np from concurrent import futures from", "[ pred_list[0], pred_list[0], pred_list[0], pred_list[0], pred_list[1], pred_list[1], pred_list[1], pred_list[1], pred_list[2], pred_list[2], pred_list[2], pred_list[2],", "output the top classifications request.urlretrieve(\"https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json\",\"imagenet_class_index.json\") idx2label = [] with open(\"imagenet_class_index.json\", \"r\") as read_file:", "pred_list[3], ] num_infer_per_thread = [] for i in range(len(pred_list)): num_infer_per_thread.append(0) def one_thread(pred, input_batch," ]
[ "self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events", "timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of", "which is 30 minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_events_between(self): event = Event()", "+ timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from event2 = Event() summary2", "from icalendar import Calendar import random import string from datetime import timedelta, datetime", "def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time = self.now() + timedelta(hours=4)", "+ string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30))", "minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time =", "self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self):", "test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\",", "def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary)", "__init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return", "icalendar import Calendar import random import string from datetime import timedelta, datetime as", "events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def", "after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after,", "00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0],", "events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time -", "summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event()", "of shorter delta\"): # each of which are 15 minutes apart next_event_start_time =", "k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) #", "minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary =", "self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event)", "datetime as dt import pytz from util import Singleton from .. import CalService,", "+ timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30), max_time) self.assertEqual(_chop_dt(before),", "self.subTest(msg=\"rest of the day with events of shorter delta\"): # each of which", "self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\",", "Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26,", "empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end()))", "timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2)", "of the day with events of shorter delta\"): # each of which are", "purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking", "self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time", "e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start, end), events)) class", "event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start =", "self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in", "self.events() if end is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end):", "18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event)", "all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e", "= CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self):", "def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase +", "start, end=None): events = self.events() if end is None: end = pytz.utc.localize(dt.max) def", "print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary =", "summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00)))", "class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\")", "self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end =", "event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits,", "Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\")", "event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"): max_time,", "Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_next_events(self): event = Event()", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now()", "date.replace(microsecond=0) start_time = self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events today\"):", "+ timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase", "all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for", "event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 =", "e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time", "event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end", "Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15))", "end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt and", "self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def", "def events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar()", "import unittest import os from icalendar import Calendar import random import string from", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\",", "start_time = self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time,", "next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30), max_time)", "= self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start,", "CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def", "= \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\",", "e in all_events)) def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "= event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase +", "@classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance(", "0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_events_between(self): event", "26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) >", "# which is 30 minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase +", "timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30), max_time) self.assertEqual(_chop_dt(before), _chop_dt(event1.get_end()))", "= self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e", "from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end()", "def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary)", "setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "= os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\")", "timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now() +", "def date_search(self, start, end=None): events = self.events() if end is None: end =", "timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time )", "self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between(", "day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30))", "apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join(", "max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after,", "string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time", "import timedelta, datetime as dt import pytz from util import Singleton from ..", "timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time,", "event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020,", "start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the", "Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2))", "unittest import os from icalendar import Calendar import random import string from datetime", "setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) )", "CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def", "\"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service", "+ timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now() + timedelta(minutes=15) all_events =", "TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service =", "next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() +", "def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time = self.now()", "end=None): events = self.events() if end is None: end = pytz.utc.localize(dt.max) def _starts_between(e:", "class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service", "next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event)", "= CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge()", "os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def", "+ timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest", "self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after", "self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_events_between(self): event =", "= Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30)", "util import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote):", "event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19,", "string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event)", "self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"]", "event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now()", "if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else:", "e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod", "iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar", "event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is", "self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now() + timedelta(minutes=15) all_events", "def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar)", "end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\",", "= Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time +", "return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start, end=None): events", "self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_events_between(self): event = Event() summary", "next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before,", "timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start,", "= self.now() end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) >", "event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15))", "datetime import timedelta, datetime as dt import pytz from util import Singleton from", "dt import pytz from util import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote,", "summary for e in all_events)) def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase", "+ timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"): max_time, before, after", "each of which are 15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while", "self.create_calendar() def date_search(self, start, end=None): events = self.events() if end is None: end", "Event, start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda", "= event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2)", "shorter delta\"): # each of which are 15 minutes apart next_event_start_time = event2.get_end()", "= Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() +", "start return list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self):", "pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\",", "event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"): max_time, before,", "+ string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12))", "k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time +", "k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() +", "CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary", "from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar", "event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events =", "def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary)", "events = self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self,", "the day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time,", "- start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase +", "before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time)", "event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with", "def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda e:", "= self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between(", "self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 =", "timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from event2 = Event() summary2 =", "k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start", "import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar()", "string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1)", "event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events =", "+ string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\",", "timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) )", "events = self.events() if end is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event,", "next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time,", "max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30), max_time) self.assertEqual(_chop_dt(before), _chop_dt(event1.get_end())) self.assertEqual(_chop_dt(after),", "+ timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from", "summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\",", "event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e), events))", "> e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start, end), events))", "self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary)", "def purge(self): self.create_calendar() def date_search(self, start, end=None): events = self.events() if end is", "= self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest", "date_search(self, start, end=None): events = self.events() if end is None: end = pytz.utc.localize(dt.max)", "while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event", "import random import string from datetime import timedelta, datetime as dt import pytz", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now()", "self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary =", "= self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event)", "+ string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time", "are 15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time:", "+ timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"],", "> 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_next_events(self):", "next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event =", "from datetime import timedelta, datetime as dt import pytz from util import Singleton", "+ string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10))", ") next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event)", "timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary)", "self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def", "event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from event2 =", "event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the", "event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now() + timedelta(minutes=15)", "2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events)", "Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time", "self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events))", "= Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time =", "test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time = self.now() +", "None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt", "summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time =", "self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with events", "end is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end", "iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self):", ") else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return", ") self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary", "self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0)", "summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is", "_starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return", "+ timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time", "= Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase +", "Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\",", "self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26,", "start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 =", "next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event)", "start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e:", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() +", "self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def", "which are 15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time <", "self.cal_service.add_event(event1) # which is 30 minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase", "= next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30),", "test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception,", "test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\",", "start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after =", "+ timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def", "self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return", "+ string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18,", "15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary", "string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2)", "@Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\",", "today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time)", "+ timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now() end = self.now()", "if end is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return", "end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e,", "Calendar import random import string from datetime import timedelta, datetime as dt import", "end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event() next_event.add(\"summary\",", "= self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in", "purge(self): self.create_calendar() def date_search(self, start, end=None): events = self.events() if end is None:", "before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(timedelta(minutes=30), max_time) self.assertEqual(_chop_dt(before), _chop_dt(event1.get_end())) self.assertEqual(_chop_dt(after), _chop_dt(event2.get_start()))", "pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt >", "= self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before,", "self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda", "self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with", "event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"],", "timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with events of", "event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which", "os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance())", "# each of which are 15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15)", "timedelta, datetime as dt import pytz from util import Singleton from .. import", "self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_next_events(self): event =", "timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self):", "def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self):", "random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\",", "event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2", "self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1", "end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event()", "event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now()", "event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30", "Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event:", "summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now() + timedelta(minutes=12)) self.cal_service.add_event(event) start = self.now()", "event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"):", "for e in all_events)) def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase +", "with self.subTest(msg=\"rest of the day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time,", "event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase", ".. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar =", "summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2)", "in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\") self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service =", "add_event(self, event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e),", "= Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self,", "+ timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between(", "string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary", "end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day", "next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time )", "k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary =", "self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time", "with self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time,", "< end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event()", "+ string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self):", "max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before,", "30 minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() +", "def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary)", "day with events of shorter delta\"): # each of which are 15 minutes", "timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() + timedelta(minutes=30) event2.add(\"summary\", summary2) event2.add(\"dtstart\", event2_start_time)", "Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def", "def _starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start", "end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start, end),", "is 30 minutes from event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "self.calendar.subcomponents return list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start, end=None):", "e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start, end=None): events = self.events()", "return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start,", "CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\",", "summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event,", "_chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time = self.now() + timedelta(hours=4) with", "from util import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def", "\"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events =", "in all_events)) def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0],", "= self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt):", "event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event)", "now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event =", "\"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time +", "_starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ:", "import pytz from util import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event", "self.subTest(msg=\"rest of the day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time", "Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2))", "self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_next_events(self): event = Event() summary", "string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event)", "else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now())", "start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar", "summary for e in all_events)) def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase", "Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start, end=None): events = self.events() if", "= Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() +", "self.cal_service.add_event(event) start = self.now() end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end)", "+ timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\",", "next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase", "> 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_events_between(self):", "k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15))", "as dt import pytz from util import Singleton from .. import CalService, CalRemote,", "== summary for e in all_events)) def test_get_events_between(self): event = Event() summary =", "self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with events of shorter delta\"): #", "and e[\"dtstart\"].dt > start return list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase):", "= Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2,", "product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self):", "end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after =", "all_events)) def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\",", "string from datetime import timedelta, datetime as dt import pytz from util import", "list(map(lambda e: Event(e), events)) def purge(self): self.create_calendar() def date_search(self, start, end=None): events =", "self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day is empty\"): max_time, before, after =", "+ timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] ==", "self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event =", "self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event):", "end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar =", "self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2)", "Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] ==", "in all_events)) def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\", self.now()", "before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time)", "next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0], Event) self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date:", "all_events)) def test_get_events_between(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\",", "== summary for e in all_events)) def test_get_next_events(self): event = Event() summary =", "pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My", "calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def", "19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0)", "import os from icalendar import Calendar import random import string from datetime import", "list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\"", "event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\",", "summary2) event2.add(\"dtstart\", event2_start_time) event2.add(\"dtend\", event2_start_time + timedelta(minutes=15)) self.cal_service.add_event(event2) with self.subTest(msg=\"rest of the day", "self.now() end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events) > 0)", "event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time", "is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end >", "def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event) def events(self): events = self.calendar.subcomponents", "start_time) self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\",", "k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2", "test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\",", "with self.subTest(msg=\"rest of the day with events of shorter delta\"): # each of", "start = self.now() end = self.now() + timedelta(minutes=15) all_events = self.cal_service.get_events_between(start, end) self.assertTrue(len(all_events)", "def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event", "\"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar() def add_event(self, event: Event): self.calendar.add_component(event)", "event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2_start_time = event1.get_end() +", "create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My calendar product//mxm.dk//\") self.calendar.add(\"version\", \"2.0\") def __init__(self): self.create_calendar()", "e in all_events)) def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "pytz from util import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton", "return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event()", "return list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if", "events of shorter delta\"): # each of which are 15 minutes apart next_event_start_time", "of the day is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time )", "0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events)) def test_get_next_events(self): event", "dt): return date.replace(microsecond=0) start_time = self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no", "self.assertEqual(next_events[0][\"summary\"], summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time =", "Event() summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=1))", "summary2 = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\",", "events)) def purge(self): self.create_calendar() def date_search(self, start, end=None): events = self.events() if end", "\"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"]", "for e in all_events)) def test_get_next_events(self): event = Event() summary = \"\".join(random.choices(string.ascii_uppercase +", "self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def", "summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event", "end_time) with self.subTest(msg=\"rest of the day with events of shorter delta\"): # each", "random import string from datetime import timedelta, datetime as dt import pytz from", "pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events()", "= self.events() if end is None: end = pytz.utc.localize(dt.max) def _starts_between(e: Event, start,", "+ timedelta(minutes=15) while next_event_start_time < end_time: next_ev_summary = \"\".join( random.choices(string.ascii_uppercase + string.digits, k=6)", "Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end()", "end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time) event1 = Event() summary = \"\".join(random.choices(string.ascii_uppercase", "self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event()", "Event() event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits,", "import Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def", "event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events = self.cal_service.get_all_events() self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary", "os from icalendar import Calendar import random import string from datetime import timedelta,", "summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event.add(\"summary\", summary) event.add(\"dtstart\", self.now() + timedelta(minutes=2)) event.add(\"dtend\",", "string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00)))", "is empty\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before),", "k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\",", "summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event1.add(\"summary\", summary) event1.add(\"dtstart\", start_time + timedelta(minutes=15)) event1.add(\"dtend\",", "= \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2,", "+ string.digits, k=6)) event2.add(\"summary\", summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10))", ") self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with", "summary) self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now()", "self.now() + timedelta(hours=4) with self.subTest(\"no events today\"): max_time, before, after = self.cal_service.get_max_available_time_between( start_time,", "self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertGreater(max_time, timedelta(minutes=30)) self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of", "_chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with events of shorter delta\"):", "26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10))", "import Calendar import random import string from datetime import timedelta, datetime as dt", "= self.cal_service.get_max_available_time_between( start_time, end_time ) self.assertEqual(max_time, end_time - start_time) self.assertEqual(before, start_time) self.assertEqual(after, end_time)", "00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\") event.set_reminder(timedelta(minutes=10)) self.cal_service.add_event(event) all_events", "delta\"): # each of which are 15 minutes apart next_event_start_time = event2.get_end() +", "summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6)) event = Event() event.add(\"summary\", summary) event.add(\"dtstart\", pytz.utc.localize(dt(2020,", "\"\".join( random.choices(string.ascii_uppercase + string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time)", "Remote...\") def setUp(self): self.cal_service.purge() def now(self): return pytz.utc.localize(dt.now()) def test_cant_add_with_too_few_params(self): summary = \"\".join(random.choices(string.ascii_uppercase", "timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from event2", "CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self): self.calendar = Calendar() self.calendar.add(\"prodid\", \"-//My", "event.add(\"summary\", summary) self.assertRaises(Exception, self.cal_service.add_event, event) def test_add_and_get_event(self): summary = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=6))", "the day with events of shorter delta\"): # each of which are 15", "import string from datetime import timedelta, datetime as dt import pytz from util", "end) self.assertTrue(len(all_events) > 0) self.assertIsInstance(all_events[0], Event) self.assertTrue(any(e[\"summary\"] == summary for e in all_events))", "2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\", \"My Hood\")", "self.assertEqual(next_events[1][\"summary\"], summary2) def test_get_max_available_time_between(self): def _chop_dt(date: dt): return date.replace(microsecond=0) start_time = self.now() end_time", "string.digits, k=6) ) next_event = Event() next_event.add(\"summary\", next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time +", "timedelta(minutes=1)) event.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event) event2 = Event() summary2 = \"\".join(random.choices(string.ascii_uppercase +", "summary2) event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events()", "self.assertEqual(_chop_dt(before), _chop_dt(event2.get_end())) self.assertEqual(after, end_time) with self.subTest(msg=\"rest of the day with events of shorter", "self.cal_service = CalService.instance( iCloudCaldavRemote.instance(purgable_calendar) ) else: self.cal_service = CalService.instance(CalMockRemote.instance()) print(\"Mocking Remote...\") def setUp(self):", "with events of shorter delta\"): # each of which are 15 minutes apart", "event2.add(\"dtstart\", self.now() + timedelta(minutes=2)) event2.add(\"dtend\", self.now() + timedelta(minutes=10)) self.cal_service.add_event(event2) next_events = self.cal_service.get_next_events() self.assertIsInstance(next_events[0],", "return date.replace(microsecond=0) start_time = self.now() end_time = self.now() + timedelta(hours=4) with self.subTest(\"no events", "start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes from event2 = Event()", "start_time + timedelta(minutes=15)) event1.add(\"dtend\", start_time + timedelta(minutes=30)) self.cal_service.add_event(event1) # which is 30 minutes", "= pytz.utc.localize(dt.max) def _starts_between(e: Event, start, end): return end > e[\"dtstart\"].dt and e[\"dtstart\"].dt", "of which are 15 minutes apart next_event_start_time = event2.get_end() + timedelta(minutes=15) while next_event_start_time", "event.add(\"dtstart\", pytz.utc.localize(dt(2020, 2, 26, 18, 00))) event.add(\"dtend\", pytz.utc.localize(dt(2020, 2, 26, 19, 00))) event.add(\"location\",", "> start return list(filter(lambda e: _starts_between(e, start, end), events)) class TestCalService(unittest.TestCase): @classmethod def", "events)) class TestCalService(unittest.TestCase): @classmethod def setUpClass(self): if \"DONOTMOCK\" in os.environ: purgable_calendar = os.getenv(\"CALDAV_PURGABLE_CALENDAR\")", "Singleton from .. import CalService, CalRemote, iCloudCaldavRemote, Event @Singleton class CalMockRemote(CalRemote): def create_calendar(self):", "next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15) max_time, before, after", "next_event) next_event.add(\"dtstart\", next_event_start_time) next_event.add(\"dtend\", next_event_start_time + timedelta(minutes=15)) self.cal_service.add_event(next_event) next_event_start_time = next_event.get_end() + timedelta(minutes=15)" ]
[ "all possible (M, point, i, num) tests we have \"\"\" for M in", "dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k, n) = x return", "num) tests we have \"\"\" for M in list_mgroup(): interesting = get_test_points(M) num_examples", "contracts.utils import raise_wrapped from nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds,", "i, num) tests we have \"\"\" for M in list_manifolds(): interesting = get_test_points(M)", "def _args0(x): (M, p, i, n) = x return M, p def _attrs0(x):", "point = interesting[i] try: M.belongs(point) except Exception as e: msg = 'M %s", "in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point", "M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k,", "def list_manifold_point(): \"\"\" Yields all possible (M, point, i, num) tests we have", "import itertools from contracts.utils import raise_wrapped from nose.tools import nottest from geometry import", "possible (M, point, i, num) tests we have \"\"\" for M in list_manifolds():", "= len(interesting) * len(interesting) k = 0 for p1, p2 in itertools.product(interesting, interesting):", "num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable", "def _args1(x): (M, p, i, n) = x return M, p def _attrs1(x):", "_args1(x): (M, p, i, n) = x return M, p def _attrs1(x): (M,", "if isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) ==", "all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i,", "M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples):", "yield M, p1, p2, k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds,", "arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n)", "does not contain %s: %s' % (M, point, e) raise_wrapped(Exception, e, msg) yield", "attributes=_attrs0) def _args1(x): (M, p, i, n) = x return M, p def", "e: msg = 'M %s does not contain %s: %s' % (M, point,", "p, i, n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0,", "point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_mgroup(): \"\"\"", "for i in range(num_examples): point = interesting[i] try: M.belongs(point) except Exception as e:", "= fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M,", "point, i, num) tests we have \"\"\" for M in list_manifolds(): interesting =", "= get_test_points(M) num_examples = len(interesting) * len(interesting) k = 0 for p1, p2", "1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def", "(M, p, i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point =", "tests we have \"\"\" for M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue", "possible (M, point, i, num) tests we have \"\"\" for M in list_mgroup():", "point, i, num) tests we have \"\"\" for M in list_manifolds(): if not", "x return M, p1, p2 def _attrs(x): (M, p1, p2, k, n) =", "try: M.belongs(point) except Exception as e: msg = 'M %s does not contain", "return M, p def _attrs0(x): (M, p, i, n) = x return dict(manifolds=1,", "manifold=M)) def _args(x): (M, p1, p2, k, n) = x return M, p1,", "(M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n) = x", "len(interesting) * len(interesting) k = 0 for p1, p2 in itertools.product(interesting, interesting): yield", "arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M))", "list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point =", "MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import * def list_manifolds(): return all_manifolds @nottest", "def list_manifold_points(): \"\"\" Yields all possible (M, point1, point2, i, num) tests we", "p1, p2, k, n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2) for_all_manifold_pairs =", "have \"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) *", "import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import * def list_manifolds(): return all_manifolds", "as e: msg = 'M %s does not contain %s: %s' % (M,", "from .checks_generation import * def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting", "from nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation", "import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import *", "Yields all possible (M, point1, point2, i, num) tests we have \"\"\" for", "(M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k, n)", "attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n) = x return", "_args(x): (M, p1, p2, k, n) = x return M, p1, p2 def", "point, i, num_examples def list_manifold_points(): \"\"\" Yields all possible (M, point1, point2, i,", "= fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n) = x return", "i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1,", "logger.warning('No test points for %s and not random.' % M) return interesting def", "M) return interesting def list_manifold_point(): \"\"\" Yields all possible (M, point, i, num)", "num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M:", "x return M, p def _attrs0(x): (M, p, i, n) = x return", "return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p,", "%s: %s' % (M, point, e) raise_wrapped(Exception, e, msg) yield M, point, i,", "0 for p1, p2 in itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples", "logger from .checks_generation import * def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2):", "n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2) for_all_manifold_pairs = fancy_test_decorator(lister=list_manifold_points, arguments=_args, attributes=_attrs)", "k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1,", "num_examples = len(interesting) * len(interesting) k = 0 for p1, p2 in itertools.product(interesting,", "M, p1, p2 def _attrs(x): (M, p1, p2, k, n) = x return", "M def list_mgroup_point(): \"\"\" Yields all possible (M, point, i, num) tests we", "MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields all possible (M, point, i,", "p1, p2 in itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples k +=", "M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting)", "point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n) =", "RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No", "num_examples def list_mgroup(): \"\"\" Yields all possible (M, point, i, num) tests we", "dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n) = x return M, p", "p1, p2 def _attrs(x): (M, p1, p2, k, n) = x return dict(type='manifolds',", "isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields all possible (M, point,", "= fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1,", "\"\"\" Yields all possible (M, point1, point2, i, num) tests we have \"\"\"", "%s and not random.' % M) return interesting def list_manifold_point(): \"\"\" Yields all", "def _attrs0(x): (M, p, i, n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point", "(M, p, i, n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point,", "from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import * def list_manifolds():", "_attrs0(x): (M, p, i, n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point =", "= M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if", "num) tests we have \"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples", "attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def", "def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M,", "return interesting def list_manifold_point(): \"\"\" Yields all possible (M, point, i, num) tests", "n) = x return M, p def _attrs1(x): (M, p, i, n) =", "= x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup", "p2, k, n) = x return M, p1, p2 def _attrs(x): (M, p1,", "def list_mgroup_point(): \"\"\" Yields all possible (M, point, i, num) tests we have", "x return M, p def _attrs1(x): (M, p, i, n) = x return", "for %s and not random.' % M) return interesting def list_manifold_point(): \"\"\" Yields", "% (M, point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def", "not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields all possible (M,", "_attrs1(x): (M, p, i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point", "fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1,", "fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1,", "= len(interesting) for i in range(num_examples): point = interesting[i] try: M.belongs(point) except Exception", "all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for i", "interesting): yield M, p1, p2, k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda:", "Exception as e: msg = 'M %s does not contain %s: %s' %", "%s' % (M, point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples", "point, i, num) tests we have \"\"\" for M in list_mgroup(): interesting =", "dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i,", "p def _attrs1(x): (M, p, i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M,", "except Exception as e: msg = 'M %s does not contain %s: %s'", "M, point, i, num_examples def list_mgroup(): \"\"\" Yields all possible (M, point, i,", "list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields all", "# @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points for %s and", "for M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point():", "list_mgroup_point(): \"\"\" Yields all possible (M, point, i, num) tests we have \"\"\"", "i in range(num_examples): point = interesting[i] try: M.belongs(point) except Exception as e: msg", "list_manifold_point(): \"\"\" Yields all possible (M, point, i, num) tests we have \"\"\"", "p, i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point,", "interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point = interesting[i]", "in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) * len(interesting) k = 0", "def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random):", "= 'M %s does not contain %s: %s' % (M, point, e) raise_wrapped(Exception,", "def list_mgroup(): \"\"\" Yields all possible (M, point, i, num) tests we have", "+= 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M)))", "in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points for", "manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,),", "(M, point, i, num) tests we have \"\"\" for M in list_manifolds(): if", "\"\"\" for M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M def", "return all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for", "return M, p1, p2 def _attrs(x): (M, p1, p2, k, n) = x", "num_examples = len(interesting) for i in range(num_examples): point = interesting[i] try: M.belongs(point) except", "raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_manifold_points(): \"\"\" Yields all", "interesting def list_manifold_point(): \"\"\" Yields all possible (M, point, i, num) tests we", "(M, point, i, num) tests we have \"\"\" for M in list_manifolds(): interesting", "if len(interesting) == 0: logger.warning('No test points for %s and not random.' %", "have \"\"\" for M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M", "@UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points for %s and not", "0: logger.warning('No test points for %s and not random.' % M) return interesting", "list_manifold_points(): \"\"\" Yields all possible (M, point1, point2, i, num) tests we have", "return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup,", "attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k, n) =", "RandomManifold, all_manifolds, logger from .checks_generation import * def list_manifolds(): return all_manifolds @nottest def", "p1, p2, k, n) = x return M, p1, p2 def _attrs(x): (M,", "in range(num_examples): point = interesting[i] try: M.belongs(point) except Exception as e: msg =", "we have \"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting)", "e, msg) yield M, point, i, num_examples def list_manifold_points(): \"\"\" Yields all possible", "len(interesting) k = 0 for p1, p2 in itertools.product(interesting, interesting): yield M, p1,", "num_examples def list_manifold_points(): \"\"\" Yields all possible (M, point1, point2, i, num) tests", "M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\"", "(M, p, i, n) = x return M, p def _attrs0(x): (M, p,", "random.' % M) return interesting def list_manifold_point(): \"\"\" Yields all possible (M, point,", "in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields", "coding=utf-8 import itertools from contracts.utils import raise_wrapped from nose.tools import nottest from geometry", "arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2,", "for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for i in", "== 0: logger.warning('No test points for %s and not random.' % M) return", "in itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples k += 1 for_all_manifolds", "n) = x return M, p def _attrs0(x): (M, p, i, n) =", "def _args(x): (M, p1, p2, k, n) = x return M, p1, p2", "p2, k, n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2) for_all_manifold_pairs = fancy_test_decorator(lister=list_manifold_points,", "p, i, n) = x return M, p def _attrs1(x): (M, p, i,", "M, p def _attrs0(x): (M, p, i, n) = x return dict(manifolds=1, manifold=M,", "for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) * len(interesting) k", "* len(interesting) k = 0 for p1, p2 in itertools.product(interesting, interesting): yield M,", "range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points for %s", "have \"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for", "x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M,", "\"\"\" Yields all possible (M, point, i, num) tests we have \"\"\" for", "len(interesting) for i in range(num_examples): point = interesting[i] try: M.belongs(point) except Exception as", "matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k, n) = x return M,", "x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup =", "yield M, point, i, num_examples def list_manifold_points(): \"\"\" Yields all possible (M, point1,", "dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda", "itertools from contracts.utils import raise_wrapped from nose.tools import nottest from geometry import MatrixLieGroup,", "point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda", "list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point =", "test points for %s and not random.' % M) return interesting def list_manifold_point():", "k, n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2) for_all_manifold_pairs = fancy_test_decorator(lister=list_manifold_points, arguments=_args,", "* def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if", "fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n) = x return M,", "list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold):", "(M, p1, p2, k, n) = x return M, p1, p2 def _attrs(x):", "range(num_examples): point = interesting[i] try: M.belongs(point) except Exception as e: msg = 'M", "(M, point1, point2, i, num) tests we have \"\"\" for M in list_manifolds():", "for M in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for i in", "for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x):", "M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n) = x return M,", "tests we have \"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples =", "= interesting[i] try: M.belongs(point) except Exception as e: msg = 'M %s does", "num) tests we have \"\"\" for M in list_manifolds(): if not isinstance(M, MatrixLieGroup):", "we have \"\"\" for M in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting)", "interesting = get_test_points(M) num_examples = len(interesting) * len(interesting) k = 0 for p1,", "for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n) = x", "k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda", "= x return M, p def _attrs1(x): (M, p, i, n) = x", "i, num) tests we have \"\"\" for M in list_mgroup(): interesting = get_test_points(M)", "interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points for %s and not random.'", "point, i, num_examples def list_mgroup(): \"\"\" Yields all possible (M, point, i, num)", "n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def", "M, p1, p2, k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda", "def _attrs(x): (M, p1, p2, k, n) = x return dict(type='manifolds', manifold=M, point1=p1,", "M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x): (M, p1, p2, k, n) = x", "M, p def _attrs1(x): (M, p, i, n) = x return dict(manifolds=1, matrixgroups=1,", "continue yield M def list_mgroup_point(): \"\"\" Yields all possible (M, point, i, num)", "not random.' % M) return interesting def list_manifold_point(): \"\"\" Yields all possible (M,", "geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import * def list_manifolds(): return", "k, n) = x return M, p1, p2 def _attrs(x): (M, p1, p2,", "_attrs(x): (M, p1, p2, k, n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2)", "p2 def _attrs(x): (M, p1, p2, k, n) = x return dict(type='manifolds', manifold=M,", ".checks_generation import * def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting =", "i, n) = x return M, p def _attrs0(x): (M, p, i, n)", "p def _attrs0(x): (M, p, i, n) = x return dict(manifolds=1, manifold=M, point=p)", "\"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) * len(interesting)", "p, i, n) = x return M, p def _attrs0(x): (M, p, i,", "for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M:", "i, num_examples def list_manifold_points(): \"\"\" Yields all possible (M, point1, point2, i, num)", "\"\"\" for M in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for i", "interesting[i] try: M.belongs(point) except Exception as e: msg = 'M %s does not", "# coding=utf-8 import itertools from contracts.utils import raise_wrapped from nose.tools import nottest from", "'M %s does not contain %s: %s' % (M, point, e) raise_wrapped(Exception, e,", "msg) yield M, point, i, num_examples def list_mgroup(): \"\"\" Yields all possible (M,", "from contracts.utils import raise_wrapped from nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold,", "i, num_examples def list_mgroup(): \"\"\" Yields all possible (M, point, i, num) tests", "e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_mgroup(): \"\"\" Yields", "(M, point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_manifold_points():", "i, num) tests we have \"\"\" for M in list_manifolds(): if not isinstance(M,", "possible (M, point1, point2, i, num) tests we have \"\"\" for M in", "point1, point2, i, num) tests we have \"\"\" for M in list_manifolds(): interesting", "(M, p, i, n) = x return M, p def _attrs1(x): (M, p,", "k = 0 for p1, p2 in itertools.product(interesting, interesting): yield M, p1, p2,", "we have \"\"\" for M in list_manifolds(): if not isinstance(M, MatrixLieGroup): continue yield", "fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p,", "points for %s and not random.' % M) return interesting def list_manifold_point(): \"\"\"", "point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_manifold_points(): \"\"\"", "@nottest def get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for i in", "manifold=str(M))) def _args0(x): (M, p, i, n) = x return M, p def", "def _attrs1(x): (M, p, i, n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p)", "for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test", "= x return M, p def _attrs0(x): (M, p, i, n) = x", "i, n) = x return M, p def _attrs1(x): (M, p, i, n)", "itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples k += 1 for_all_manifolds =", "import * def list_manifolds(): return all_manifolds @nottest def get_test_points(M, num_random=2): interesting = M.interesting_points()", "n) = x return dict(manifolds=1, matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1)", "for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, matrixgroups=1, manifold=M)) def _args(x):", "msg) yield M, point, i, num_examples def list_manifold_points(): \"\"\" Yields all possible (M,", "tests we have \"\"\" for M in list_mgroup(): interesting = get_test_points(M) num_examples =", "Yields all possible (M, point, i, num) tests we have \"\"\" for M", "M, point, i, num_examples def list_manifold_points(): \"\"\" Yields all possible (M, point1, point2,", "n) = x return M, p1, p2 def _attrs(x): (M, p1, p2, k,", "msg = 'M %s does not contain %s: %s' % (M, point, e)", "contain %s: %s' % (M, point, e) raise_wrapped(Exception, e, msg) yield M, point,", "M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M, p, i, n) =", "M in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples):", "p2, k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,),", "(M, p1, p2, k, n) = x return dict(type='manifolds', manifold=M, point1=p1, point2=p2) for_all_manifold_pairs", "_args0(x): (M, p, i, n) = x return M, p def _attrs0(x): (M,", "M.belongs(point) except Exception as e: msg = 'M %s does not contain %s:", "i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0: logger.warning('No test points", "= 0 for p1, p2 in itertools.product(interesting, interesting): yield M, p1, p2, k,", "= x return M, p1, p2 def _attrs(x): (M, p1, p2, k, n)", "and not random.' % M) return interesting def list_manifold_point(): \"\"\" Yields all possible", "(M, point, e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_mgroup():", "get_test_points(M) num_examples = len(interesting) * len(interesting) k = 0 for p1, p2 in", "for p1, p2 in itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples k", "p2 in itertools.product(interesting, interesting): yield M, p1, p2, k, num_examples k += 1", "return M, p def _attrs1(x): (M, p, i, n) = x return dict(manifolds=1,", "matrixgroups=1, manifold=M, point=p) for_all_mgroup_point = fancy_test_decorator(lister=list_mgroup_point, arguments=_args1, attributes=_attrs1) for_all_mgroup = fancy_test_decorator(lister=list_mgroup, arguments=lambda M:", "arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n) = x return M, p", "list_mgroup(): \"\"\" Yields all possible (M, point, i, num) tests we have \"\"\"", "len(interesting) == 0: logger.warning('No test points for %s and not random.' % M)", "manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x): (M, p, i, n)", "yield M def list_mgroup_point(): \"\"\" Yields all possible (M, point, i, num) tests", "i, n) = x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0)", "yield M, point, i, num_examples def list_mgroup(): \"\"\" Yields all possible (M, point,", "M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) * len(interesting) k =", "\"\"\" for M in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for i", "interesting = M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform())", "point2, i, num) tests we have \"\"\" for M in list_manifolds(): interesting =", "get_test_points(M, num_random=2): interesting = M.interesting_points() if isinstance(M, RandomManifold): for i in range(num_random): #", "in list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point", "all possible (M, point1, point2, i, num) tests we have \"\"\" for M", "not contain %s: %s' % (M, point, e) raise_wrapped(Exception, e, msg) yield M,", "= get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point = interesting[i] try:", "e) raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_manifold_points(): \"\"\" Yields", "(M, point, i, num) tests we have \"\"\" for M in list_mgroup(): interesting", "nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import", "%s does not contain %s: %s' % (M, point, e) raise_wrapped(Exception, e, msg)", "if not isinstance(M, MatrixLieGroup): continue yield M def list_mgroup_point(): \"\"\" Yields all possible", "raise_wrapped(Exception, e, msg) yield M, point, i, num_examples def list_mgroup(): \"\"\" Yields all", "have \"\"\" for M in list_mgroup(): interesting = get_test_points(M) num_examples = len(interesting) for", "list_manifolds(): interesting = get_test_points(M) num_examples = len(interesting) * len(interesting) k = 0 for", "get_test_points(M) num_examples = len(interesting) for i in range(num_examples): point = interesting[i] try: M.belongs(point)", "raise_wrapped from nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from", "% M) return interesting def list_manifold_point(): \"\"\" Yields all possible (M, point, i,", "p1, p2, k, num_examples k += 1 for_all_manifolds = fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M:", "e, msg) yield M, point, i, num_examples def list_mgroup(): \"\"\" Yields all possible", "= x return dict(manifolds=1, manifold=M, point=p) for_all_manifold_point = fancy_test_decorator(lister=list_manifold_point, arguments=_args0, attributes=_attrs0) def _args1(x):", "nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger from .checks_generation import * def", "isinstance(M, RandomManifold): for i in range(num_random): # @UnusedVariable interesting.append(M.sample_uniform()) if len(interesting) == 0:", "import raise_wrapped from nose.tools import nottest from geometry import MatrixLieGroup, RandomManifold, all_manifolds, logger", "all_manifolds, logger from .checks_generation import * def list_manifolds(): return all_manifolds @nottest def get_test_points(M,", "= fancy_test_decorator(lister=lambda: all_manifolds, arguments=lambda M: (M,), attributes=lambda M: dict(manifolds=1, manifold=str(M))) def _args0(x): (M," ]
[ "range(n)} for origin, destination in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] +=", "1, n): rank = len(graph[x]) + len(graph[y]) if x in graph[y]: rank -=", "value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph graph", "len(outgoing) == 1 and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return -1", "node_id in range(len(graph)): if node_id not in safe and node_id not in unsafe:", "not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents =", "parents = [i for i in range(len(is_connected))] rank = [1 for _ in", "find_eventual_safe_nodes(graph): safe = set() unsafe = set() def traverse(node_id, visited): if node_id in", "for _ in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id])", "1)] rank = [1 for _ in range(len(edges) + 1)] def find(node_id): if", "node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time for adjacent_weight, adjacent_node", "= set(), set() queue = collections.deque([[0, source, 0]]) while queue: total, location_id, turn", "range(len(edges) + 1)] rank = [1 for _ in range(len(edges) + 1)] def", "for y in range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] =", "def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def", "not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for adjacent in", "trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result =", "adjacent not in safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False", "source: int, target: int) -> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph =", "stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(), set() queue = collections.deque([[0,", "= [] for x in range(len(input_string)): for y in range(x + 1, len(input_string)):", "= get_graph() def get_color(node_id): colors = set() for adjacent in graph[node_id]: if adjacent", "get_graph(): graph = collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight, destination]) return", "= [origin, destination] return result def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set)", "roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank = 0 for x", "set() for adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def", "adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result)", "not in safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id)", "def get_graph(): graph = collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return", "x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents = [i for i", "node_id not in colors: if not traverse(node_id, True): return False return True def", "if node_id not in colors: if not traverse(node_id, True): return False return True", "queries: List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin, destination], value", "list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited): if", "destination in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing)", "= [] for origin, destination in edges: if union(origin, destination): result = [origin,", "get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return", "in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue = collections.deque([0]) while", "1 return graph, in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x]", "unsafe.add(node_id) return False if adjacent not in safe and not traverse(adjacent, visited |", "in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return", "- 1] = value return result def network_delay_time(times, n, k): queue = [[0,", "if parent_a == parent_b: return True rank_a = rank[parent_a] rank_b = rank[parent_b] if", "set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] =", "i, letter in enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word) return graph", "False if adjacent not in colors and not traverse(adjacent, not color): return False", "+= 1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) ->", "queue = collections.deque([0]) while queue: node_id = queue.popleft() for adjacent in rooms[node_id]: if", "for adjacent in rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms)", "in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return", "origin, destination, weight in times: graph[origin].append([weight, destination]) return graph graph = get_graph() while", "node_id == len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited", "return rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b] =", "def find_eventual_safe_nodes(graph): safe = set() unsafe = set() def traverse(node_id, visited): if node_id", "queue: node_id = queue.popleft() for adjacent in rooms[node_id]: if adjacent not in visited:", "adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id]", "traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if adjacent not in flowers:", "for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time +", "return result def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for origin, destination", "+ '*' + word[i + 1:]].append(word) return graph if endWord not in wordList:", "== endWord: return distance + 1 for i, letter in enumerate(word): transform =", "edges: List[List[int]]) -> List[int]: in_degree = {i: 0 for i in range(n)} for", "x in range(n): for y in range(x + 1, n): rank = len(graph[x])", "in unsafe: unsafe.add(node_id) return False if adjacent not in safe and not traverse(adjacent,", "== len(visited) def number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))] rank =", "def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return False for adjacent in", "parent_a == parent_b: return True rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a", "result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited | {node_id}) for adjacent in", "prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0 for x in", "rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] +=", "for i, stops in enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i", "in enumerate(word): transform = word[:i] + '*' + word[i + 1:] for word", "temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value,", "wordList + [beginWord]: for i, letter in enumerate(word): graph[word[:i] + '*' + word[i", "any([traverse(adjacent, path + [adjacent], visited | {node_id}) for adjacent in graph[node_id]]): return 1", "in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph graph =", "total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time for adjacent_weight,", "result = traverse(adjacent, target_node, temp_result * weight, visited | {node_id}) if result !=", "maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination)", "+ len(graph[y]) if x in graph[y]: rank -= 1 max_rank = max(max_rank, rank)", "if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for", "== num_courses: return result return [] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]])", "+= 1 return False result = [] for origin, destination in edges: if", "graph graph = get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id == target_node:", "collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result = [] while queue: node_id =", "bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes): for stop", "color for adjacent in graph[node_id]: if adjacent in colors and colors[adjacent] == color:", "colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if", "stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str, s2: str) ->", "return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe = set() def traverse(node_id, visited):", "def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree = {i: 0 for i", "neighbors = [] for x in range(len(input_string)): for y in range(x + 1,", "temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string", "in graph[node_id]: if adjacent in colors and colors[adjacent] == color: return False if", "stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph =", "1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors", "node_id == target_node: return temp_result for weight, adjacent in graph[node_id]: if adjacent not", "word in wordList + [beginWord]: for i, letter in enumerate(word): graph[word[:i] + '*'", "in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for adjacent in bus_graph[location_id]:", "adjacent not in visited: result = traverse(adjacent, target_node, temp_result * weight, visited |", "return temp_result for weight, adjacent in graph[node_id]: if adjacent not in visited: result", "= collections.defaultdict(list) for word in wordList + [beginWord]: for i, letter in enumerate(word):", "while queue: value, input_string = queue.popleft() if input_string == s2: return value for", "visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord: str, endWord: str, wordList:", "in flowers: traverse(adjacent) for node_id in range(1, n + 1): if node_id not", "2, 3, 4} def get_graph(): graph = collections.defaultdict(list) for origin, destination in paths:", "= [[0, k]] visited = set() def get_graph(): graph = collections.defaultdict(list) for origin,", "for adjacent in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1,", "graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph graph = get_graph() def traverse(node_id,", "= set() def get_graph(): graph = collections.defaultdict(list) for origin, destination, weight in times:", "def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if adjacent not in", "destination in edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))", "visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i for i", "temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while", "False safe.add(node_id) return True for node_id in range(len(graph)): if node_id not in safe", "in graph[node_id]: if adjacent not in flowers: traverse(adjacent) for node_id in range(1, n", "1] = value return result def network_delay_time(times, n, k): queue = [[0, k]]", "union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b: return", "bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(), set() queue = collections.deque([[0, source,", "= [None for _ in range(n)] for key, value in flowers.items(): result[key -", "traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return False for adjacent in graph[node_id]:", "for i in range(n)} for origin, destination in trust: if origin in outgoing:", "in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1])", "= get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n:", "= traverse(adjacent, target_node, temp_result * weight, visited | {node_id}) if result != -1:", "set(), set() queue = collections.deque([[0, source, 0]]) while queue: total, location_id, turn =", "in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) ==", "return total for adjacent in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total", "False if adjacent not in safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id)", "not in flowers: traverse(node_id) result = [None for _ in range(n)] for key,", "for node_id in range(len(graph)): if node_id not in safe and node_id not in", "List[List[int]]) -> List[int]: in_degree = {i: 0 for i in range(n)} for origin,", "def get_neighbors(input_string): neighbors = [] for x in range(len(input_string)): for y in range(x", "enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph,", "for x, row in enumerate(is_connected): for y, value in enumerate(row): if y >", "return -1 def kSimilarity(s1: str, s2: str) -> int: visited = set() def", "in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] ==", "return False return True for node_id in range(len(graph)): if node_id not in colors:", "result return -1 result = [] for node_id, target_id in queries: if node_id", "turn == 0: if location_id == target: return total for adjacent in stop_graph[location_id]:", "+ 1, n): rank = len(graph[x]) + len(graph[y]) if x in graph[y]: rank", "enumerate(row): if y > x and value == 1: union(x, y) for x", "len(graph[x]) + len(graph[y]) if x in graph[y]: rank -= 1 max_rank = max(max_rank,", "if node_id not in graph or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id,", "get_neighbors(input_string): neighbors = [] for x in range(len(input_string)): for y in range(x +", "destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id): colors", "adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight,", "1 for i in range(n)} for origin, destination in trust: if origin in", "collections.defaultdict(list) in_degree = {x: 0 for x in range(num_courses)} for destination, origin in", "[] for node_id, target_id in queries: if node_id not in graph or target_id", "queue.append([total + 1, adjacent, 1]) else: for adjacent in bus_graph[location_id]: if adjacent not", "endWord: return distance + 1 for i, letter in enumerate(word): transform = word[:i]", "for weight, adjacent in graph[node_id]: if adjacent not in visited: result = traverse(adjacent,", "endWord: str, wordList: List[str]) -> int: def get_graph(): graph = collections.defaultdict(list) for word", "return True for node_id in range(len(graph)): if node_id not in colors: if not", "trust: List[List[int]]) -> int: trusts = {i + 1: 0 for i in", "safe.add(node_id) return True for node_id in range(len(graph)): if node_id not in safe and", "= find(node_b) if parent_a == parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b]", "+ 1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(),", "= collections.deque([[0, source, 0]]) while queue: total, location_id, turn = queue.popleft() if turn", "trusts = {i + 1: 0 for i in range(n)} outgoing = {i", "1 max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe", "return False result = [] for origin, destination in edges: if union(origin, destination):", "graph graph = get_graph() max_rank = 0 for x in range(n): for y", "= {1, 2, 3, 4} def get_graph(): graph = collections.defaultdict(list) for origin, destination", "[total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph =", "heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph", "def get_graph(): graph = collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight, destination])", "while queue: total, location_id, turn = queue.popleft() if turn == 0: if location_id", "in_degree = {i: 0 for i in range(n)} for origin, destination in edges:", "= set() def get_neighbors(input_string): neighbors = [] for x in range(len(input_string)): for y", "bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for adjacent in bus_graph[location_id]: if", "List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list) for", "= [] def traverse(node_id, path, visited): if node_id in visited: return 1 visited.add(node_id)", "set()) == 1: return [] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) ->", "destination, weight in times: graph[origin].append([weight, destination]) return graph graph = get_graph() while queue:", "adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree =", "return graph, in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] ==", "for x in range(n): for y in range(x + 1, n): rank =", "return graph if endWord not in wordList: return -1 graph = get_graph() visited", "+ '*' + word[i + 1:] for word in graph[transform]: if word not", "0 for x in range(n): for y in range(x + 1, n): rank", "if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return", "in range(len(input_string)): for y in range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x],", "= parent_a else: parents[node_a] = parent_b rank[parent_b] += 1 return False result =", "in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses: return result return [] def", "result = [] while queue: node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]:", "y in range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y],", "if adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def", "rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b] +=", "origin, destination in edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] == 0,", "for adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False if adjacent", "max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe = set() def", "return True rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a]", "if adjacent not in flowers: traverse(adjacent) for node_id in range(1, n + 1):", "= {x: 0 for x in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination)", "return value for neighbor in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value", "= collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result = [] while queue: node_id", "neighbor not in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord:", "[] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph", "def all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited): if node_id in visited:", "traverse(node_id, True): return False return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors", "in graph[transform]: if word not in visited: visited.add(word) queue.append([distance + 1, word]) return", "get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1", "return False if adjacent not in colors and not traverse(adjacent, not color): return", "ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: def get_graph(): graph = collections.defaultdict(list)", "x in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return", "return True for node_id in range(len(graph)): if node_id not in safe and node_id", "temp_result * weight, visited | {node_id}) if result != -1: return result return", "queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i for i in", "[beginWord]: for i, letter in enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word)", "= 0 for x in range(n): for y in range(x + 1, n):", "graph graph = get_graph() def get_color(node_id): colors = set() for adjacent in graph[node_id]:", "traverse(adjacent) for node_id in range(1, n + 1): if node_id not in flowers:", "[None for _ in range(n)] for key, value in flowers.items(): result[key - 1]", "1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool:", "== 0: if location_id == target: return total for adjacent in stop_graph[location_id]: if", "return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1, 2, 3,", "destination]) return graph graph = get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id)", "queue.popleft() if input_string == s2: return value for neighbor in get_neighbors(input_string): if neighbor", "0 if traverse(0, [0], set()) == 1: return [] return result def minimum_vertices_reach_all_nodes(n:", "+= 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n - 1: return", "+= 1 else: parents[parent_a] = parent_b rank[parent_b] += 1 for x, row in", "in range(len(edges) + 1)] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id])", "def get_color(node_id): colors = set() for adjacent in graph[node_id]: if adjacent in flowers:", "in range(len(is_connected))] rank = [1 for _ in range(len(is_connected))] def find(node_id): if parents[node_id]", "for adjacent in graph[node_id]: if adjacent not in flowers: traverse(adjacent) for node_id in", "in queries: if node_id not in graph or target_id not in graph: result.append(float(-1))", "visited = {beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft()", "find(node_a) parent_b = find(node_b) if parent_a == parent_b: return rank_a = rank[parent_a] rank_b", "stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes): for stop in stops: bus_graph[i", "adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses,", "return -1 graph = get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]]) while", "graph[y]: rank -= 1 max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe", "rank = [1 for _ in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id:", "colors and not traverse(adjacent, not color): return False return True for node_id in", "return 1 return 0 if traverse(0, [0], set()) == 1: return [] return", "collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph()", "= collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string = queue.popleft() if input_string ==", "def traverse(node_id, path, visited): if node_id in visited: return 1 visited.add(node_id) if node_id", "in range(1, n + 1): if node_id not in flowers: traverse(node_id) result =", "for i in range(len(is_connected))] rank = [1 for _ in range(len(is_connected))] def find(node_id):", "int: visited = set() def get_neighbors(input_string): neighbors = [] for x in range(len(input_string)):", "turn = queue.popleft() if turn == 0: if location_id == target: return total", "rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] += 1", "not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites):", "graph[node_id]: if adjacent in colors and colors[adjacent] == color: return False if adjacent", "collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for adjacent in graph[node_id]: if adjacent", "flower_colors = {1, 2, 3, 4} def get_graph(): graph = collections.defaultdict(list) for origin,", "for i in range(n)} outgoing = {i + 1 for i in range(n)}", "not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes:", "== n - 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = []", "traverse(node_id, target_node, temp_result, visited): if node_id == target_node: return temp_result for weight, adjacent", "== 0: queue.append(adjacent) if len(result) == num_courses: return result return [] def calcEquation(equations:", "-1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0", "rank[parent_b] += 1 return False result = [] for origin, destination in edges:", "def union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b:", "-> int: trusts = {i + 1: 0 for i in range(n)} outgoing", "-1 def all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited): if node_id in", "if node_id not in safe and node_id not in unsafe: traverse(node_id, set()) return", "range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree", "colors and colors[adjacent] == color: return False if adjacent not in colors and", "_ in range(n)] for key, value in flowers.items(): result[key - 1] = value", "/ value, origin]) return graph graph = get_graph() def traverse(node_id, target_node, temp_result, visited):", "bus_visited, stop_visited = set(), set() queue = collections.deque([[0, source, 0]]) while queue: total,", "flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def get_graph():", "parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b] += 1 for x,", "num_courses: return result return [] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) ->", "1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0]", "== n: return total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in", "is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for adjacent in", "str, wordList: List[str]) -> int: def get_graph(): graph = collections.defaultdict(list) for word in", "for node_id, target_id in queries: if node_id not in graph or target_id not", "if adjacent not in visited: result = traverse(adjacent, target_node, temp_result * weight, visited", "parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a ==", "visited.add(node_id) if node_id == len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path +", "for x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents = [i for", "range(x + 1, n): rank = len(graph[x]) + len(graph[y]) if x in graph[y]:", "in graph[node_id]: if adjacent not in visited: result = traverse(adjacent, target_node, temp_result *", "{i + 1 for i in range(n)} for origin, destination in trust: if", "return result return [] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:", "in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses: return", "1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(), set()", "result = [] def traverse(node_id, path, visited): if node_id in visited: return 1", "stop_graph = get_graph() bus_visited, stop_visited = set(), set() queue = collections.deque([[0, source, 0]])", "traverse(node_id, color): colors[node_id] = color for adjacent in graph[node_id]: if adjacent in colors", "in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue", "graph = get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) ==", "visited = {0} queue = collections.deque([0]) while queue: node_id = queue.popleft() for adjacent", "stops in enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1)", "network_delay_time(times, n, k): queue = [[0, k]] visited = set() def get_graph(): graph", "return False return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1,", "= queue.popleft() for adjacent in rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent)", "total for adjacent in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total +", "def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: def get_graph(): graph =", "enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word) return graph if endWord not", "in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank = 0 for", "= max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe = set()", "return 1 visited.add(node_id) if node_id == len(graph) - 1: result.append(path) else: if any([traverse(adjacent,", "1: union(x, y) for x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents", "queue.popleft() if turn == 0: if location_id == target: return total for adjacent", "not in colors and not traverse(adjacent, not color): return False return True for", "in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False if adjacent not in", "destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph, in_degree", "def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for origin, destination in roads:", "in enumerate(row): if y > x and value == 1: union(x, y) for", "{x: 0 for x in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination]", "in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord: str, endWord:", "for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def", "for [origin, destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin])", "node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent]", "0 for x in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] +=", "graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph, in_degree = get_graph() queue =", "in range(n): for y in range(x + 1, n): rank = len(graph[x]) +", "adjacent not in flowers: traverse(adjacent) for node_id in range(1, n + 1): if", "= parent_b rank[parent_b] += 1 for x, row in enumerate(is_connected): for y, value", "traverse(0, [0], set()) == 1: return [] return result def minimum_vertices_reach_all_nodes(n: int, edges:", "for i, letter in enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word) return", "int, trust: List[List[int]]) -> int: trusts = {i + 1: 0 for i", "1: 0 for i in range(n)} outgoing = {i + 1 for i", "if parent_a == parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a", "value in flowers.items(): result[key - 1] = value return result def network_delay_time(times, n,", "!= node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a = find(node_a)", "node_id not in safe and node_id not in unsafe: traverse(node_id, set()) return list(safe)", "if len(visited) == n: return total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node", "and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result", "parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b]", "in range(len(edges) + 1)] rank = [1 for _ in range(len(edges) + 1)]", "return graph graph = get_graph() def get_color(node_id): colors = set() for adjacent in", "return total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue,", "parent_b = find(node_b) if parent_a == parent_b: return True rank_a = rank[parent_a] rank_b", "collections.defaultdict(list) for [origin, destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value,", "return result def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: def get_graph():", "List[int]: in_degree = {i: 0 for i in range(n)} for origin, destination in", "not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str, s2:", "colors = set() for adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return", "if adjacent not in colors and not traverse(adjacent, not color): return False return", "for neighbor in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value + 1,", "neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string = queue.popleft() if", "n + 1): if node_id not in flowers: traverse(node_id) result = [None for", "return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited", "for node_id in range(1, n + 1): if node_id not in flowers: traverse(node_id)", "range(len(graph)): if node_id not in safe and node_id not in unsafe: traverse(node_id, set())", "queue: total, location_id, turn = queue.popleft() if turn == 0: if location_id ==", "node_id not in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool)", "trusts[destination] += 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n - 1:", "True): return False return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors =", "result return [] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def", "if traverse(0, [0], set()) == 1: return [] return result def minimum_vertices_reach_all_nodes(n: int,", "def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph =", "-> List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin, destination], value in zip(equations,", "destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph", "traverse(adjacent, target_node, temp_result * weight, visited | {node_id}) if result != -1: return", "result[key - 1] = value return result def network_delay_time(times, n, k): queue =", "+ 1, neighbor]) return -1 def ladderLength(beginWord: str, endWord: str, wordList: List[str]) ->", "in edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def", "def redundant_connections(edges): parents = [i for i in range(len(edges) + 1)] rank =", "= {beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft() if", "in visited: unsafe.add(node_id) return False for adjacent in graph[node_id]: if adjacent in unsafe:", "parent_b rank[parent_b] += 1 return False result = [] for origin, destination in", "True for node_id in range(len(graph)): if node_id not in colors: if not traverse(node_id,", "graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1", "result def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for origin, destination in", "1 else: parents[parent_a] = parent_b rank[parent_b] += 1 for x, row in enumerate(is_connected):", "temp_result for weight, adjacent in graph[node_id]: if adjacent not in visited: result =", "[] for x in range(len(input_string)): for y in range(x + 1, len(input_string)): temp_string", "[] for origin, destination in edges: if union(origin, destination): result = [origin, destination]", "parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b =", "1 and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph):", "trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1", "redundant_connections(edges): parents = [i for i in range(len(edges) + 1)] rank = [1", "for origin, destination in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1", "node_id not in graph or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id,", "unsafe.add(node_id) return False for adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return", "int, edges: List[List[int]]) -> List[int]: in_degree = {i: 0 for i in range(n)}", "visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i for", "for x in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1", "return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if adjacent", "rank -= 1 max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe =", "[adjacent], visited | {node_id}) for adjacent in graph[node_id]]): return 1 return 0 if", "== 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue =", "List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin, destination], value in", "list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for", "flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if adjacent not in flowers: traverse(adjacent)", "queue.popleft() if word == endWord: return distance + 1 for i, letter in", "if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for", "True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1, 2, 3, 4}", "in range(n)] for key, value in flowers.items(): result[key - 1] = value return", "adjacent in rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) ==", "times: graph[origin].append([weight, destination]) return graph graph = get_graph() while queue: total_time, node_id =", "x in range(len(input_string)): for y in range(x + 1, len(input_string)): temp_string = list(input_string)", "bool: visited = {0} queue = collections.deque([0]) while queue: node_id = queue.popleft() for", "return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree = {x:", "in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def", "origin]) return graph graph = get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id", "-= 1 max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe = set()", "range(1, n + 1): if node_id not in flowers: traverse(node_id) result = [None", "rank[parent_b] += 1 for x, row in enumerate(is_connected): for y, value in enumerate(row):", "color: return False if adjacent not in colors and not traverse(adjacent, not color):", "visited): if node_id == target_node: return temp_result for weight, adjacent in graph[node_id]: if", "-> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops", "graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses:", "{node_id}) if result != -1: return result return -1 result = [] for", "queue: value, input_string = queue.popleft() if input_string == s2: return value for neighbor", "= queue.popleft() if input_string == s2: return value for neighbor in get_neighbors(input_string): if", "unsafe = set() def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return False", "adjacent in colors and colors[adjacent] == color: return False if adjacent not in", "for _ in range(n)] for key, value in flowers.items(): result[key - 1] =", "word in graph[transform]: if word not in visited: visited.add(word) queue.append([distance + 1, word])", "and not traverse(adjacent, not color): return False return True for node_id in range(len(graph)):", "node_id = queue.popleft() for adjacent in rooms[node_id]: if adjacent not in visited: visited.add(adjacent)", "location_id, turn = queue.popleft() if turn == 0: if location_id == target: return", "return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree = {i: 0", "= collections.defaultdict(list) in_degree = {x: 0 for x in range(num_courses)} for destination, origin", "in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]])", "temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1)", "int) -> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i,", "-= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses: return result", "and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for", "in flowers: traverse(node_id) result = [None for _ in range(n)] for key, value", "range(len(edges) + 1)] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return", "in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph", "colors[adjacent] == color: return False if adjacent not in colors and not traverse(adjacent,", "1 visited.add(node_id) if node_id == len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path", "if y > x and value == 1: union(x, y) for x in", "word == endWord: return distance + 1 for i, letter in enumerate(word): transform", "weight, visited | {node_id}) if result != -1: return result return -1 result", "def network_delay_time(times, n, k): queue = [[0, k]] visited = set() def get_graph():", "list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]])", "if neighbor not in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def", "= word[:i] + '*' + word[i + 1:] for word in graph[transform]: if", "- 1: result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited | {node_id}) for", "in visited: return 1 visited.add(node_id) if node_id == len(graph) - 1: result.append(path) else:", "get_color(node_id) for adjacent in graph[node_id]: if adjacent not in flowers: traverse(adjacent) for node_id", "'*' + word[i + 1:]].append(word) return graph if endWord not in wordList: return", "colors[node_id] = color for adjacent in graph[node_id]: if adjacent in colors and colors[adjacent]", "in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] =", "if node_id == len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path + [adjacent],", "| {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for node_id in range(len(graph)): if", "0: if location_id == target: return total for adjacent in stop_graph[location_id]: if adjacent", "course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0 for x", "s1]]) visited.add(s1) while queue: value, input_string = queue.popleft() if input_string == s2: return", "in range(n)} for origin, destination in edges: in_degree[destination] += 1 return list(filter(lambda x:", "len(set(parents)) def redundant_connections(edges): parents = [i for i in range(len(edges) + 1)] rank", "== 1 and trusts[list(outgoing)[0]] == n - 1: return list(outgoing)[0] return -1 def", "in graph[y]: rank -= 1 max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph):", "find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b) if", "flowers.items(): result[key - 1] = value return result def network_delay_time(times, n, k): queue", "queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result = [] while queue:", "i in range(len(is_connected))] rank = [1 for _ in range(len(is_connected))] def find(node_id): if", "0, in_degree.keys()))) result = [] while queue: node_id = queue.popleft() result.append(node_id) for adjacent", "def kSimilarity(s1: str, s2: str) -> int: visited = set() def get_neighbors(input_string): neighbors", "result def network_delay_time(times, n, k): queue = [[0, k]] visited = set() def", "else: result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]], source: int, target:", "collections.defaultdict(list) for word in wordList + [beginWord]: for i, letter in enumerate(word): graph[word[:i]", "not in graph or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1,", "[] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree = {i:", "for adjacent in graph[node_id]: if adjacent in colors and colors[adjacent] == color: return", "in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result =", "0: queue.append(adjacent) if len(result) == num_courses: return result return [] def calcEquation(equations: List[List[str]],", "'*' + word[i + 1:] for word in graph[transform]: if word not in", "collections.deque([0]) while queue: node_id = queue.popleft() for adjacent in rooms[node_id]: if adjacent not", "[1 for _ in range(len(edges) + 1)] def find(node_id): if parents[node_id] != node_id:", "return graph graph = get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id ==", "and node_id not in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors =", "adjacent, 1]) else: for adjacent in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent)", "calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list)", "if result != -1: return result return -1 result = [] for node_id,", "= collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph =", "heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time for adjacent_weight, adjacent_node in graph[node_id]:", "for i in range(n)} for origin, destination in edges: in_degree[destination] += 1 return", "safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True", "range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents = [i for i in range(len(edges)", "graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result", "set() queue = collections.deque([[0, source, 0]]) while queue: total, location_id, turn = queue.popleft()", "input_string == s2: return value for neighbor in get_neighbors(input_string): if neighbor not in", "for adjacent in graph[node_id]]): return 1 return 0 if traverse(0, [0], set()) ==", "False return True for node_id in range(len(graph)): if node_id not in colors: if", "1)] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def", "x and value == 1: union(x, y) for x in range(len(is_connected)): find(x) return", "1 parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b] += 1 return False", "in visited: result = traverse(adjacent, target_node, temp_result * weight, visited | {node_id}) if", "target: return total for adjacent in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent)", "str) -> int: visited = set() def get_neighbors(input_string): neighbors = [] for x", "parent_b rank[parent_b] += 1 for x, row in enumerate(is_connected): for y, value in", "+ 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return", "for _ in range(len(edges) + 1)] def find(node_id): if parents[node_id] != node_id: parents[node_id]", "destination): result = [origin, destination] return result def maximal_network_rank(n, roads): def get_graph(): graph", "parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b] += 1", "wordList: return -1 graph = get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]])", "letter in enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word) return graph if", "in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str, s2: str)", "= {i: 0 for i in range(n)} for origin, destination in edges: in_degree[destination]", "{node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for node_id in range(len(graph)): if node_id", "graph, in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0,", "graph[origin].append([weight, destination]) return graph graph = get_graph() while queue: total_time, node_id = heapq.heappop(queue)", "transform = word[:i] + '*' + word[i + 1:] for word in graph[transform]:", "visited: return 1 visited.add(node_id) if node_id == len(graph) - 1: result.append(path) else: if", "in range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x]", "origin, destination in edges: if union(origin, destination): result = [origin, destination] return result", "stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else:", "for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank", "graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id): colors = set() for adjacent", "parent_a == parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a >", "{node_id}) for adjacent in graph[node_id]]): return 1 return 0 if traverse(0, [0], set())", "+ 1)] rank = [1 for _ in range(len(edges) + 1)] def find(node_id):", "= find(node_b) if parent_a == parent_b: return True rank_a = rank[parent_a] rank_b =", "+ 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited,", "1:]].append(word) return graph if endWord not in wordList: return -1 graph = get_graph()", "[1 for _ in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id] =", "queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string = queue.popleft() if input_string", "graph = collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph", "{0} queue = collections.deque([0]) while queue: node_id = queue.popleft() for adjacent in rooms[node_id]:", "if node_id not in flowers: traverse(node_id) result = [None for _ in range(n)]", "List[List[int]]) -> bool: visited = {0} queue = collections.deque([0]) while queue: node_id =", "if node_id in visited: unsafe.add(node_id) return False for adjacent in graph[node_id]: if adjacent", "in range(len(graph)): if node_id not in safe and node_id not in unsafe: traverse(node_id,", "in range(n)} outgoing = {i + 1 for i in range(n)} for origin,", "prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph, in_degree = get_graph() queue", "len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))] rank", "paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id): colors = set()", "| {node_id}) if result != -1: return result return -1 result = []", "+ [adjacent], visited | {node_id}) for adjacent in graph[node_id]]): return 1 return 0", "rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a", "in_degree.keys()))) result = [] while queue: node_id = queue.popleft() result.append(node_id) for adjacent in", "set() unsafe = set() def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return", "input_string = queue.popleft() if input_string == s2: return value for neighbor in get_neighbors(input_string):", "y in range(x + 1, n): rank = len(graph[x]) + len(graph[y]) if x", "set() def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return False for adjacent", "row in enumerate(is_connected): for y, value in enumerate(row): if y > x and", "safe and node_id not in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors", "x, row in enumerate(is_connected): for y, value in enumerate(row): if y > x", "= queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] ==", "== target_node: return temp_result for weight, adjacent in graph[node_id]: if adjacent not in", "parent_b: return True rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b:", "while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time", "adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent", "node_id in range(len(graph)): if node_id not in colors: if not traverse(node_id, True): return", "= heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time for adjacent_weight, adjacent_node in", "visited: result = traverse(adjacent, target_node, temp_result * weight, visited | {node_id}) if result", "parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a =", "get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id == target_node: return temp_result for", "numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: def get_graph(): bus_graph = collections.defaultdict(list)", "if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1:", "total, location_id, turn = queue.popleft() if turn == 0: if location_id == target:", "= [1 for _ in range(len(edges) + 1)] def find(node_id): if parents[node_id] !=", "else: parents[node_a] = parent_b rank[parent_b] += 1 return False result = [] for", "queue: distance, word = queue.popleft() if word == endWord: return distance + 1", "if word == endWord: return distance + 1 for i, letter in enumerate(word):", "visited: unsafe.add(node_id) return False for adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id)", "1, adjacent, 1]) else: for adjacent in bus_graph[location_id]: if adjacent not in stop_visited:", "1: return [] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree", "return len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))]", "= parent_b rank[parent_b] += 1 return False result = [] for origin, destination", "len(graph[y]) if x in graph[y]: rank -= 1 max_rank = max(max_rank, rank) return", "+ 1 for i in range(n)} for origin, destination in trust: if origin", "= get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id == target_node: return temp_result", "1 return False result = [] for origin, destination in edges: if union(origin,", "range(n): for y in range(x + 1, n): rank = len(graph[x]) + len(graph[y])", "def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes):", "values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph graph = get_graph() def", "| {node_id}) for adjacent in graph[node_id]]): return 1 return 0 if traverse(0, [0],", "return parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a", "max_rank = 0 for x in range(n): for y in range(x + 1,", "= value return result def network_delay_time(times, n, k): queue = [[0, k]] visited", "for node_id in range(len(graph)): if node_id not in colors: if not traverse(node_id, True):", "if adjacent not in safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return", "node_id not in flowers: traverse(node_id) result = [None for _ in range(n)] for", "for origin, destination in edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] ==", "collections import heapq from typing import List def find_town_judge(n: int, trust: List[List[int]]) ->", "-1 graph = get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]]) while queue:", "distance + 1 for i, letter in enumerate(word): transform = word[:i] + '*'", "not in safe and node_id not in unsafe: traverse(node_id, set()) return list(safe) def", "in enumerate(is_connected): for y, value in enumerate(row): if y > x and value", "graph[word[:i] + '*' + word[i + 1:]].append(word) return graph if endWord not in", "{i + 1: 0 for i in range(n)} outgoing = {i + 1", "adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for adjacent", "for x in range(len(input_string)): for y in range(x + 1, len(input_string)): temp_string =", "= find(node_a) parent_b = find(node_b) if parent_a == parent_b: return rank_a = rank[parent_a]", "return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string = queue.popleft()", "rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def", "graph or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return", "+ 1, adjacent, 1]) else: for adjacent in bus_graph[location_id]: if adjacent not in", "in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys())))", "1 for i, letter in enumerate(word): transform = word[:i] + '*' + word[i", "adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents", "== 1: union(x, y) for x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges):", "visited = set() def get_neighbors(input_string): neighbors = [] for x in range(len(input_string)): for", "flowers: traverse(adjacent) for node_id in range(1, n + 1): if node_id not in", "outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n", "in colors: if not traverse(node_id, True): return False return True def flower_planting_no_adjacent(n, paths):", "in range(x + 1, n): rank = len(graph[x]) + len(graph[y]) if x in", "if adjacent in colors and colors[adjacent] == color: return False if adjacent not", "node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b", "rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b] +=", "node_id in range(1, n + 1): if node_id not in flowers: traverse(node_id) result", "False result = [] for origin, destination in edges: if union(origin, destination): result", "while queue: distance, word = queue.popleft() if word == endWord: return distance +", "flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]:", "result = [origin, destination] return result def maximal_network_rank(n, roads): def get_graph(): graph =", "y) for x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents = [i", "destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank = 0", "= {0} queue = collections.deque([0]) while queue: node_id = queue.popleft() for adjacent in", "= [i for i in range(len(is_connected))] rank = [1 for _ in range(len(is_connected))]", "y, value in enumerate(row): if y > x and value == 1: union(x,", "in_degree[x] == 0, in_degree.keys()))) result = [] while queue: node_id = queue.popleft() result.append(node_id)", "queue: node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if", "graph[node_id]: if adjacent not in visited: result = traverse(adjacent, target_node, temp_result * weight,", "word = queue.popleft() if word == endWord: return distance + 1 for i,", "traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id]", "if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1 and", "!= -1: return result return -1 result = [] for node_id, target_id in", "= len(graph[x]) + len(graph[y]) if x in graph[y]: rank -= 1 max_rank =", "not traverse(adjacent, not color): return False return True for node_id in range(len(graph)): if", "set())) return result def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: def", "else: if any([traverse(adjacent, path + [adjacent], visited | {node_id}) for adjacent in graph[node_id]]):", "-> bool: visited = {0} queue = collections.deque([0]) while queue: node_id = queue.popleft()", "get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0 for x in range(num_courses)} for", "get_graph(): graph = collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph", "parent_a else: parents[node_a] = parent_b rank[parent_b] += 1 return False result = []", "+ 1 for i, letter in enumerate(word): transform = word[:i] + '*' +", "traverse(node_id, path, visited): if node_id in visited: return 1 visited.add(node_id) if node_id ==", "> rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b]", "queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord: str, endWord: str, wordList: List[str])", "= get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance, word", "if turn == 0: if location_id == target: return total for adjacent in", "union(origin, destination): result = [origin, destination] return result def maximal_network_rank(n, roads): def get_graph():", "= {i + 1: 0 for i in range(n)} outgoing = {i +", "queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str, s2: str) -> int: visited", "False return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int) flower_colors = {1, 2,", "distance, word = queue.popleft() if word == endWord: return distance + 1 for", "graph = get_graph() def get_color(node_id): colors = set() for adjacent in graph[node_id]: if", "all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited): if node_id in visited: return", "value in enumerate(row): if y > x and value == 1: union(x, y)", "= temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue:", "range(n)} outgoing = {i + 1 for i in range(n)} for origin, destination", "[i for i in range(len(is_connected))] rank = [1 for _ in range(len(is_connected))] def", "graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False if adjacent not in safe", "minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree = {i: 0 for i in", "get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance, word =", "len(visited) == n: return total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not", "graph[transform]: if word not in visited: visited.add(word) queue.append([distance + 1, word]) return -1", "return graph graph = get_graph() max_rank = 0 for x in range(n): for", "== 0, in_degree.keys()))) result = [] while queue: node_id = queue.popleft() result.append(node_id) for", "in edges: if union(origin, destination): result = [origin, destination] return result def maximal_network_rank(n,", "= collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for adjacent in graph[node_id]: if", "+ word[i + 1:]].append(word) return graph if endWord not in wordList: return -1", "graph = collections.defaultdict(list) for [origin, destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1", "in graph or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set()))", "letter in enumerate(word): transform = word[:i] + '*' + word[i + 1:] for", "find(node_a) parent_b = find(node_b) if parent_a == parent_b: return True rank_a = rank[parent_a]", "0]) return -1 def kSimilarity(s1: str, s2: str) -> int: visited = set()", "set() def get_graph(): graph = collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight,", "def traverse(node_id, color): colors[node_id] = color for adjacent in graph[node_id]: if adjacent in", "max_rank = max(max_rank, rank) return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe =", "unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color):", "target_node, temp_result, visited): if node_id == target_node: return temp_result for weight, adjacent in", "key, value in flowers.items(): result[key - 1] = value return result def network_delay_time(times,", "= rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else:", "collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def get_graph(): graph = collections.defaultdict(list) for", "0 for i in range(n)} for origin, destination in edges: in_degree[destination] += 1", "keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue = collections.deque([0]) while queue: node_id", "heapq from typing import List def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts", "max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe = set() def traverse(node_id, visited): if", "traverse(node_id) result = [None for _ in range(n)] for key, value in flowers.items():", "= queue.popleft() if turn == 0: if location_id == target: return total for", "visited.add(s1) while queue: value, input_string = queue.popleft() if input_string == s2: return value", "collections.defaultdict(list) for i, stops in enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop)", "visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for node_id in range(len(graph)):", "def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts = {i + 1: 0", "{1, 2, 3, 4} def get_graph(): graph = collections.defaultdict(list) for origin, destination in", "word[i + 1:]].append(word) return graph if endWord not in wordList: return -1 graph", "if rank_a > rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a] =", "== len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited |", "return result return -1 result = [] for node_id, target_id in queries: if", "in wordList + [beginWord]: for i, letter in enumerate(word): graph[word[:i] + '*' +", "List def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts = {i + 1:", "def number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))] rank = [1 for", "from typing import List def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts =", "get_graph() def get_color(node_id): colors = set() for adjacent in graph[node_id]: if adjacent in", "List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin, destination], value in zip(equations, values):", "1, neighbor]) return -1 def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int:", "beginWord]]) while queue: distance, word = queue.popleft() if word == endWord: return distance", "or target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result", "return False if adjacent not in safe and not traverse(adjacent, visited | {node_id}):", "value return result def network_delay_time(times, n, k): queue = [[0, k]] visited =", "temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue =", "= rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a]", "== target: return total for adjacent in stop_graph[location_id]: if adjacent not in bus_visited:", "parents[parent_a] = parent_b rank[parent_b] += 1 for x, row in enumerate(is_connected): for y,", "return -1 def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: def get_graph():", "1:] for word in graph[transform]: if word not in visited: visited.add(word) queue.append([distance +", "typing import List def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts = {i", "range(len(is_connected))] rank = [1 for _ in range(len(is_connected))] def find(node_id): if parents[node_id] !=", "= collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph =", "= queue.popleft() if word == endWord: return distance + 1 for i, letter", "flowers: traverse(node_id) result = [None for _ in range(n)] for key, value in", "while queue: node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1", "0]]) while queue: total, location_id, turn = queue.popleft() if turn == 0: if", "{beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft() if word", "n: return total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in visited:", "not in visited: result = traverse(adjacent, target_node, temp_result * weight, visited | {node_id})", "and colors[adjacent] == color: return False if adjacent not in colors and not", "adjacent in unsafe: unsafe.add(node_id) return False if adjacent not in safe and not", "+ 1: 0 for i in range(n)} outgoing = {i + 1 for", "= collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def get_graph(): graph = collections.defaultdict(list)", "queue.append(adjacent) if len(result) == num_courses: return result return [] def calcEquation(equations: List[List[str]], values:", "1: result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited | {node_id}) for adjacent", "graph = get_graph() def traverse(node_id, target_node, temp_result, visited): if node_id == target_node: return", "not color): return False return True for node_id in range(len(graph)): if node_id not", "1): if node_id not in flowers: traverse(node_id) result = [None for _ in", "= collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight, destination]) return graph graph", "= get_graph() bus_visited, stop_visited = set(), set() queue = collections.deque([[0, source, 0]]) while", "get_graph() bus_visited, stop_visited = set(), set() queue = collections.deque([[0, source, 0]]) while queue:", "queue = collections.deque([[0, source, 0]]) while queue: total, location_id, turn = queue.popleft() if", "origin, destination in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if", "in safe and not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return", "List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin, destination],", "not in wordList: return -1 graph = get_graph() visited = {beginWord} queue =", "in range(n)} for origin, destination in trust: if origin in outgoing: outgoing.remove(origin) trusts[destination]", "adjacent in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return", "bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def", "range(n)] for key, value in flowers.items(): result[key - 1] = value return result", "in range(len(graph)): if node_id not in colors: if not traverse(node_id, True): return False", "len(graph) - 1: result.append(path) else: if any([traverse(adjacent, path + [adjacent], visited | {node_id})", "-1 result = [] for node_id, target_id in queries: if node_id not in", "[[0, k]] visited = set() def get_graph(): graph = collections.defaultdict(list) for origin, destination,", "bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph()", "source, 0]]) while queue: total, location_id, turn = queue.popleft() if turn == 0:", "adjacent in graph[node_id]: if adjacent not in flowers: traverse(adjacent) for node_id in range(1,", "range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def", "visited = set() def get_graph(): graph = collections.defaultdict(list) for origin, destination, weight in", "str, s2: str) -> int: visited = set() def get_neighbors(input_string): neighbors = []", "neighbor]) return -1 def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: def", "[0], set()) == 1: return [] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]])", "in times: graph[origin].append([weight, destination]) return graph graph = get_graph() while queue: total_time, node_id", "result def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: def get_graph(): bus_graph", "in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1", "i in range(n)} outgoing = {i + 1 for i in range(n)} for", "return False safe.add(node_id) return True for node_id in range(len(graph)): if node_id not in", "weight in times: graph[origin].append([weight, destination]) return graph graph = get_graph() while queue: total_time,", "if len(result) == num_courses: return result return [] def calcEquation(equations: List[List[str]], values: List[float],", "adjacent in stop_graph[location_id]: if adjacent not in bus_visited: bus_visited.add(adjacent) queue.append([total + 1, adjacent,", "rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1 parents[node_b] = parent_a", "range(n)} for origin, destination in edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x]", "+ 1:] for word in graph[transform]: if word not in visited: visited.add(word) queue.append([distance", "and value == 1: union(x, y) for x in range(len(is_connected)): find(x) return len(set(parents))", "stop_visited = set(), set() queue = collections.deque([[0, source, 0]]) while queue: total, location_id,", "== parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b:", "True rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a] +=", "in enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return", "value, origin]) return graph graph = get_graph() def traverse(node_id, target_node, temp_result, visited): if", "if node_id == target_node: return temp_result for weight, adjacent in graph[node_id]: if adjacent", "for i in range(len(edges) + 1)] rank = [1 for _ in range(len(edges)", "enumerate(word): transform = word[:i] + '*' + word[i + 1:] for word in", "- 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = [] def traverse(node_id,", "path + [adjacent], visited | {node_id}) for adjacent in graph[node_id]]): return 1 return", "for key, value in flowers.items(): result[key - 1] = value return result def", "visited): if node_id in visited: unsafe.add(node_id) return False for adjacent in graph[node_id]: if", "not in colors: if not traverse(node_id, True): return False return True def flower_planting_no_adjacent(n,", "= collections.defaultdict(list) for i, stops in enumerate(routes): for stop in stops: bus_graph[i +", "def get_graph(): graph = collections.defaultdict(list) for word in wordList + [beginWord]: for i,", "graph = collections.defaultdict(list) for word in wordList + [beginWord]: for i, letter in", "in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id]", "1 return 0 if traverse(0, [0], set()) == 1: return [] return result", "= find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a = find(node_a) parent_b = find(node_b)", "return result def network_delay_time(times, n, k): queue = [[0, k]] visited = set()", "for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if", "graph = collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph", "= collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes): for stop in", "in range(num_courses)} for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph,", "i, letter in enumerate(word): transform = word[:i] + '*' + word[i + 1:]", "queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0:", "node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b: return True", "origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id):", "rank_a > rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a] = parent_b", "parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b: return True rank_a", "n): rank = len(graph[x]) + len(graph[y]) if x in graph[y]: rank -= 1", "> x and value == 1: union(x, y) for x in range(len(is_connected)): find(x)", "union(x, y) for x in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents =", "in safe and node_id not in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph):", "collections.deque([[0, source, 0]]) while queue: total, location_id, turn = queue.popleft() if turn ==", "path, visited): if node_id in visited: return 1 visited.add(node_id) if node_id == len(graph)", "flowers = collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def get_graph(): graph =", "for adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id):", "+ adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list)", "result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent)", "target_id in queries: if node_id not in graph or target_id not in graph:", "== color: return False if adjacent not in colors and not traverse(adjacent, not", "+ 1)] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id]", "in enumerate(word): graph[word[:i] + '*' + word[i + 1:]].append(word) return graph if endWord", "1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses: return result return", "range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string))", "n - 1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = [] def", "graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank = 0 for x in", "= [i for i in range(len(edges) + 1)] rank = [1 for _", "-> int: visited = set() def get_neighbors(input_string): neighbors = [] for x in", "+ 1): if node_id not in flowers: traverse(node_id) result = [None for _", "node_id, target_id in queries: if node_id not in graph or target_id not in", "values: List[float], queries: List[List[str]]) -> List[float]: def get_graph(): graph = collections.defaultdict(list) for [origin,", "color): return False return True for node_id in range(len(graph)): if node_id not in", "edges: if union(origin, destination): result = [origin, destination] return result def maximal_network_rank(n, roads):", "0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue = collections.deque([0])", "stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited =", "if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected):", "= set() unsafe = set() def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id)", "i, stops in enumerate(routes): for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i +", "get_graph(): graph = collections.defaultdict(list) for [origin, destination], value in zip(equations, values): graph[origin].append([value, destination])", "value for neighbor in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value +", "for y in range(x + 1, n): rank = len(graph[x]) + len(graph[y]) if", "get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes): for", "queue = [[0, k]] visited = set() def get_graph(): graph = collections.defaultdict(list) for", "-1: return result return -1 result = [] for node_id, target_id in queries:", "in_degree = {x: 0 for x in range(num_courses)} for destination, origin in prerequisites:", "visited): if node_id in visited: return 1 visited.add(node_id) if node_id == len(graph) -", "visited.add(node_id) if len(visited) == n: return total_time for adjacent_weight, adjacent_node in graph[node_id]: if", "word[i + 1:] for word in graph[transform]: if word not in visited: visited.add(word)", "get_color(node_id): colors = set() for adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent])", "return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(), set() queue", "= collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft() if word == endWord:", "== parent_b: return True rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a >", "= rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else:", "1, set())) return result def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int:", "unsafe.add(node_id) return False safe.add(node_id) return True for node_id in range(len(graph)): if node_id not", "def get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0 for x in range(num_courses)}", "graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id): colors = set() for", "origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph() max_rank =", "True for node_id in range(len(graph)): if node_id not in safe and node_id not", "-> List[int]: in_degree = {i: 0 for i in range(n)} for origin, destination", "if location_id == target: return total for adjacent in stop_graph[location_id]: if adjacent not", "target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]], source: int, target: int) ->", "i in range(n)} for origin, destination in trust: if origin in outgoing: outgoing.remove(origin)", "rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a]", "1 for x, row in enumerate(is_connected): for y, value in enumerate(row): if y", "if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) == num_courses: return result return []", "graph = get_graph() visited = {beginWord} queue = collections.deque([[1, beginWord]]) while queue: distance,", "target_node: return temp_result for weight, adjacent in graph[node_id]: if adjacent not in visited:", "enumerate(is_connected): for y, value in enumerate(row): if y > x and value ==", "for origin, destination in edges: if union(origin, destination): result = [origin, destination] return", "queue.popleft() for adjacent in rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return", "+= 1 parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b] += 1 return", "return 0 if traverse(0, [0], set()) == 1: return [] return result def", "if endWord not in wordList: return -1 graph = get_graph() visited = {beginWord}", "not in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def", "neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string =", "traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for node_id in", "adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str,", "adjacent_node in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node])", "-1 def ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int: def get_graph(): graph", "if adjacent in unsafe: unsafe.add(node_id) return False if adjacent not in safe and", "temp_result, visited): if node_id == target_node: return temp_result for weight, adjacent in graph[node_id]:", "in colors and colors[adjacent] == color: return False if adjacent not in colors", "1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited", "graph if endWord not in wordList: return -1 graph = get_graph() visited =", "while queue: node_id = queue.popleft() for adjacent in rooms[node_id]: if adjacent not in", "return distance + 1 for i, letter in enumerate(word): transform = word[:i] +", "3, 4} def get_graph(): graph = collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination)", "stop_visited.add(adjacent) queue.append([total, adjacent, 0]) return -1 def kSimilarity(s1: str, s2: str) -> int:", "parents = [i for i in range(len(edges) + 1)] rank = [1 for", "collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return graph graph = get_graph()", "4} def get_graph(): graph = collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin)", "result = [] for node_id, target_id in queries: if node_id not in graph", "paths): flowers = collections.defaultdict(int) flower_colors = {1, 2, 3, 4} def get_graph(): graph", "graph[node_id]: if adjacent not in flowers: traverse(adjacent) for node_id in range(1, n +", "[origin, destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return", "result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]], source: int, target: int)", "return [] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree =", "rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b] += 1", "len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue", "endWord not in wordList: return -1 graph = get_graph() visited = {beginWord} queue", "in graph[node_id]]): return 1 return 0 if traverse(0, [0], set()) == 1: return", "find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b):", "set() def get_neighbors(input_string): neighbors = [] for x in range(len(input_string)): for y in", "adjacent in graph[node_id]: if adjacent in colors and colors[adjacent] == color: return False", "collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in enumerate(routes): for stop in stops:", "unsafe: unsafe.add(node_id) return False if adjacent not in safe and not traverse(adjacent, visited", "if any([traverse(adjacent, path + [adjacent], visited | {node_id}) for adjacent in graph[node_id]]): return", "if union(origin, destination): result = [origin, destination] return result def maximal_network_rank(n, roads): def", "[] def traverse(node_id, path, visited): if node_id in visited: return 1 visited.add(node_id) if", "x: in_degree[x] == 0, in_degree.keys()))) result = [] while queue: node_id = queue.popleft()", "rank) return max_rank def find_eventual_safe_nodes(graph): safe = set() unsafe = set() def traverse(node_id,", "def traverse(node_id, target_node, temp_result, visited): if node_id == target_node: return temp_result for weight,", "def get_graph(): graph = collections.defaultdict(list) for [origin, destination], value in zip(equations, values): graph[origin].append([value,", "rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b", "int: def get_graph(): graph = collections.defaultdict(list) for word in wordList + [beginWord]: for", "outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]] == n -", "node_id in visited: return 1 visited.add(node_id) if node_id == len(graph) - 1: result.append(path)", "y > x and value == 1: union(x, y) for x in range(len(is_connected)):", "find(x) return len(set(parents)) def redundant_connections(edges): parents = [i for i in range(len(edges) +", "parent_b = find(node_b) if parent_a == parent_b: return rank_a = rank[parent_a] rank_b =", "_ in range(len(edges) + 1)] def find(node_id): if parents[node_id] != node_id: parents[node_id] =", "for destination, origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph,", "= list(input_string) temp_string[x], temp_string[y] = temp_string[y], temp_string[x] neighbors.append(''.join(temp_string)) return neighbors queue = collections.deque([[0,", "graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id)", "= collections.defaultdict(list) for [origin, destination], value in zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 /", "list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in graph[node_id]: if adjacent not", "+ 1:]].append(word) return graph if endWord not in wordList: return -1 graph =", "+ [beginWord]: for i, letter in enumerate(word): graph[word[:i] + '*' + word[i +", "def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a,", "import heapq from typing import List def find_town_judge(n: int, trust: List[List[int]]) -> int:", "if x in graph[y]: rank -= 1 max_rank = max(max_rank, rank) return max_rank", "visited | {node_id}) for adjacent in graph[node_id]]): return 1 return 0 if traverse(0,", "range(len(graph)): if node_id not in colors: if not traverse(node_id, True): return False return", "find_town_judge(n: int, trust: List[List[int]]) -> int: trusts = {i + 1: 0 for", "origin in outgoing: outgoing.remove(origin) trusts[destination] += 1 if len(outgoing) == 1 and trusts[list(outgoing)[0]]", "if not traverse(node_id, True): return False return True def flower_planting_no_adjacent(n, paths): flowers =", "= get_color(node_id) for adjacent in graph[node_id]: if adjacent not in flowers: traverse(adjacent) for", "graph[destination].append([1 / value, origin]) return graph graph = get_graph() def traverse(node_id, target_node, temp_result,", "result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]], source: int,", "int, target: int) -> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list)", "value == 1: union(x, y) for x in range(len(is_connected)): find(x) return len(set(parents)) def", "for adjacent in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent, 0])", "collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft() if word == endWord: return", "location_id == target: return total for adjacent in stop_graph[location_id]: if adjacent not in", "List[List[int]]) -> int: trusts = {i + 1: 0 for i in range(n)}", "adjacent in graph[node_id]]): return 1 return 0 if traverse(0, [0], set()) == 1:", "import List def find_town_judge(n: int, trust: List[List[int]]) -> int: trusts = {i +", "in range(len(is_connected)): find(x) return len(set(parents)) def redundant_connections(edges): parents = [i for i in", "+= 1 return graph, in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda x:", "graph graph = get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited)", "rank_a = rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1", "origin in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph, in_degree =", "in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0] def traverse(node_id): flowers[node_id] = get_color(node_id) for adjacent in", "return graph graph = get_graph() while queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if", "return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color", "queue = collections.deque([[1, beginWord]]) while queue: distance, word = queue.popleft() if word ==", "edges: in_degree[destination] += 1 return list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms:", "+= 1 for x, row in enumerate(is_connected): for y, value in enumerate(row): if", "adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree", "destination in edges: if union(origin, destination): result = [origin, destination] return result def", "weight, adjacent in graph[node_id]: if adjacent not in visited: result = traverse(adjacent, target_node,", "def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0} queue = collections.deque([0]) while queue:", "k]] visited = set() def get_graph(): graph = collections.defaultdict(list) for origin, destination, weight", "not traverse(adjacent, visited | {node_id}): unsafe.add(node_id) return False safe.add(node_id) return True for node_id", "_ in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return", "get_graph(): graph = collections.defaultdict(list) for origin, destination in paths: graph[origin].append(destination) graph[destination].append(origin) return graph", "result = [] for origin, destination in edges: if union(origin, destination): result =", "in rooms[node_id]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited)", "rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1 parents[node_b] =", "destination] return result def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for origin,", "* weight, visited | {node_id}) if result != -1: return result return -1", "return -1 result = [] for node_id, target_id in queries: if node_id not", "False for adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False if", "return False for adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False", "color): colors[node_id] = color for adjacent in graph[node_id]: if adjacent in colors and", "== 1: return [] return result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]:", "= color for adjacent in graph[node_id]: if adjacent in colors and colors[adjacent] ==", "get_graph(): graph = collections.defaultdict(list) for word in wordList + [beginWord]: for i, letter", "colors: if not traverse(node_id, True): return False return True def flower_planting_no_adjacent(n, paths): flowers", "node_b): parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b: return rank_a", "graph = get_graph() max_rank = 0 for x in range(n): for y in", "in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]],", "+ word[i + 1:] for word in graph[transform]: if word not in visited:", "wordList: List[str]) -> int: def get_graph(): graph = collections.defaultdict(list) for word in wordList", "for word in wordList + [beginWord]: for i, letter in enumerate(word): graph[word[:i] +", "[origin, destination] return result def maximal_network_rank(n, roads): def get_graph(): graph = collections.defaultdict(set) for", "= rank[parent_a] rank_b = rank[parent_b] if rank_a > rank_b: rank[parent_a] += 1 parents[node_b]", "int: trusts = {i + 1: 0 for i in range(n)} outgoing =", "= [] while queue: node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent]", "in_degree[destination] += 1 return graph, in_degree graph, in_degree = get_graph() queue = collections.deque(list(filter(lambda", "bus_graph, stop_graph bus_graph, stop_graph = get_graph() bus_visited, stop_visited = set(), set() queue =", "= collections.deque([0]) while queue: node_id = queue.popleft() for adjacent in rooms[node_id]: if adjacent", "-> int: def get_graph(): graph = collections.defaultdict(list) for word in wordList + [beginWord]:", "target_id not in graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result def", "= {i + 1 for i in range(n)} for origin, destination in trust:", "x in graph[y]: rank -= 1 max_rank = max(max_rank, rank) return max_rank def", "result = [None for _ in range(n)] for key, value in flowers.items(): result[key", "in flowers.items(): result[key - 1] = value return result def network_delay_time(times, n, k):", "result != -1: return result return -1 result = [] for node_id, target_id", "range(len(input_string)): for y in range(x + 1, len(input_string)): temp_string = list(input_string) temp_string[x], temp_string[y]", "traverse(adjacent, not color): return False return True for node_id in range(len(graph)): if node_id", "s2: str) -> int: visited = set() def get_neighbors(input_string): neighbors = [] for", "word[:i] + '*' + word[i + 1:] for word in graph[transform]: if word", "visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord: str, endWord: str,", "import collections import heapq from typing import List def find_town_judge(n: int, trust: List[List[int]])", "def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for adjacent", "for y, value in enumerate(row): if y > x and value == 1:", "List[str]) -> int: def get_graph(): graph = collections.defaultdict(list) for word in wordList +", "0 for i in range(n)} outgoing = {i + 1 for i in", "rank = [1 for _ in range(len(edges) + 1)] def find(node_id): if parents[node_id]", "in wordList: return -1 graph = get_graph() visited = {beginWord} queue = collections.deque([[1,", "queries: if node_id not in graph or target_id not in graph: result.append(float(-1)) else:", "stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph bus_graph,", "return -1 def all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited): if node_id", "in unsafe: traverse(node_id, set()) return list(safe) def is_graph_bipartite(graph): colors = collections.defaultdict(bool) def traverse(node_id,", "return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = [] def traverse(node_id, path, visited):", "destination]) graph[destination].append([1 / value, origin]) return graph graph = get_graph() def traverse(node_id, target_node,", "result def minimum_vertices_reach_all_nodes(n: int, edges: List[List[int]]) -> List[int]: in_degree = {i: 0 for", "get_graph() max_rank = 0 for x in range(n): for y in range(x +", "in colors and not traverse(adjacent, not color): return False return True for node_id", "def get_graph(): graph = collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin) return", "visited | {node_id}) if result != -1: return result return -1 result =", "for stop in stops: bus_graph[i + 1].append(stop) stop_graph[stop].append(i + 1) return bus_graph, stop_graph", "get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result = [] while", "= get_graph() max_rank = 0 for x in range(n): for y in range(x", "== s2: return value for neighbor in get_neighbors(input_string): if neighbor not in visited:", "if parents[node_id] != node_id: parents[node_id] = find(parents[node_id]) return parents[node_id] def union(node_a, node_b): parent_a", "not traverse(node_id, True): return False return True def flower_planting_no_adjacent(n, paths): flowers = collections.defaultdict(int)", "{i: 0 for i in range(n)} for origin, destination in edges: in_degree[destination] +=", "adjacent, 0]) return -1 def kSimilarity(s1: str, s2: str) -> int: visited =", "collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight, destination]) return graph graph =", "number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))] rank = [1 for _", "not in flowers: traverse(adjacent) for node_id in range(1, n + 1): if node_id", "adjacent in graph[node_id]: if adjacent not in visited: result = traverse(adjacent, target_node, temp_result", "= [1 for _ in range(len(is_connected))] def find(node_id): if parents[node_id] != node_id: parents[node_id]", "def numBusesToDestination(routes: List[List[int]], source: int, target: int) -> int: def get_graph(): bus_graph =", "list(filter(lambda x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited =", "return len(set(parents)) def redundant_connections(edges): parents = [i for i in range(len(edges) + 1)]", "x: in_degree[x] == 0, in_degree.keys())) def keys_and_rooms(rooms: List[List[int]]) -> bool: visited = {0}", "= get_graph() queue = collections.deque(list(filter(lambda x: in_degree[x] == 0, in_degree.keys()))) result = []", "total_time for adjacent_weight, adjacent_node in graph[node_id]: if adjacent_node not in visited: heapq.heappush(queue, [total_time", "[] while queue: node_id = queue.popleft() result.append(node_id) for adjacent in graph[node_id]: in_degree[adjacent] -=", "len(result) == num_courses: return result return [] def calcEquation(equations: List[List[str]], values: List[float], queries:", "for i, letter in enumerate(word): transform = word[:i] + '*' + word[i +", "> rank_b: rank[parent_a] += 1 parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b]", "adjacent not in colors and not traverse(adjacent, not color): return False return True", "safe = set() unsafe = set() def traverse(node_id, visited): if node_id in visited:", "value, input_string = queue.popleft() if input_string == s2: return value for neighbor in", "if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a] =", "roads): def get_graph(): graph = collections.defaultdict(set) for origin, destination in roads: graph[origin].add(destination) graph[destination].add(origin)", "in visited: visited.add(adjacent) queue.append(adjacent) return len(rooms) == len(visited) def number_of_provinces(is_connected): parents = [i", "in paths: graph[origin].append(destination) graph[destination].append(origin) return graph graph = get_graph() def get_color(node_id): colors =", "k): queue = [[0, k]] visited = set() def get_graph(): graph = collections.defaultdict(list)", "return [] def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def get_graph():", "List[List[int]], source: int, target: int) -> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph", "= parent_a rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b] += 1 for", "for origin, destination, weight in times: graph[origin].append([weight, destination]) return graph graph = get_graph()", "i in range(n)} for origin, destination in edges: in_degree[destination] += 1 return list(filter(lambda", "adjacent in graph[node_id]: if adjacent in unsafe: unsafe.add(node_id) return False if adjacent not", "find(node_b) if parent_a == parent_b: return rank_a = rank[parent_a] rank_b = rank[parent_b] if", "node_id in visited: unsafe.add(node_id) return False for adjacent in graph[node_id]: if adjacent in", "1]) else: for adjacent in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total,", "-1 def kSimilarity(s1: str, s2: str) -> int: visited = set() def get_neighbors(input_string):", "parent_a = find(node_a) parent_b = find(node_b) if parent_a == parent_b: return rank_a =", "[i for i in range(len(edges) + 1)] rank = [1 for _ in", "queue: total_time, node_id = heapq.heappop(queue) visited.add(node_id) if len(visited) == n: return total_time for", "kSimilarity(s1: str, s2: str) -> int: visited = set() def get_neighbors(input_string): neighbors =", "neighbor in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor) queue.append([value + 1, neighbor])", "= [] for node_id, target_id in queries: if node_id not in graph or", "rank[parent_b] if rank_a > rank_b: parents[parent_b] = parent_a rank[parent_a] += 1 else: parents[parent_a]", "= set() for adjacent in graph[node_id]: if adjacent in flowers: colors.add(flowers[adjacent]) return list(flower_colors.difference(colors))[0]", "s2: return value for neighbor in get_neighbors(input_string): if neighbor not in visited: visited.add(neighbor)", "n, k): queue = [[0, k]] visited = set() def get_graph(): graph =", "graph[node_id]]): return 1 return 0 if traverse(0, [0], set()) == 1: return []", "graph[destination].add(origin) return graph graph = get_graph() max_rank = 0 for x in range(n):", "graph = collections.defaultdict(list) for origin, destination, weight in times: graph[origin].append([weight, destination]) return graph", "in prerequisites: graph[origin].append(destination) in_degree[destination] += 1 return graph, in_degree graph, in_degree = get_graph()", "if node_id in visited: return 1 visited.add(node_id) if node_id == len(graph) - 1:", "len(visited) def number_of_provinces(is_connected): parents = [i for i in range(len(is_connected))] rank = [1", "if input_string == s2: return value for neighbor in get_neighbors(input_string): if neighbor not", "str, endWord: str, wordList: List[str]) -> int: def get_graph(): graph = collections.defaultdict(list) for", "in graph[node_id]: in_degree[adjacent] -= 1 if in_degree[adjacent] == 0: queue.append(adjacent) if len(result) ==", "graph: result.append(float(-1)) else: result.append(traverse(node_id, target_id, 1, set())) return result def numBusesToDestination(routes: List[List[int]], source:", "not in visited: visited.add(neighbor) queue.append([value + 1, neighbor]) return -1 def ladderLength(beginWord: str,", "rank = len(graph[x]) + len(graph[y]) if x in graph[y]: rank -= 1 max_rank", "def course_schedule_two(num_courses, prerequisites): def get_graph(): graph = collections.defaultdict(list) in_degree = {x: 0 for", "graph = collections.defaultdict(list) in_degree = {x: 0 for x in range(num_courses)} for destination,", "else: parents[parent_a] = parent_b rank[parent_b] += 1 for x, row in enumerate(is_connected): for", "parents[node_b] = parent_a else: parents[node_a] = parent_b rank[parent_b] += 1 return False result", "= find(node_a) parent_b = find(node_b) if parent_a == parent_b: return True rank_a =", "int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for i, stops in", "visited: heapq.heappush(queue, [total_time + adjacent_weight, adjacent_node]) return -1 def course_schedule_two(num_courses, prerequisites): def get_graph():", "target: int) -> int: def get_graph(): bus_graph = collections.defaultdict(list) stop_graph = collections.defaultdict(list) for", "parents[node_a] = parent_b rank[parent_b] += 1 return False result = [] for origin,", "outgoing = {i + 1 for i in range(n)} for origin, destination in", "= set() def traverse(node_id, visited): if node_id in visited: unsafe.add(node_id) return False for", "1: return list(outgoing)[0] return -1 def all_paths_source_to_target(graph): result = [] def traverse(node_id, path,", "find(node_b) if parent_a == parent_b: return True rank_a = rank[parent_a] rank_b = rank[parent_b]", "else: for adjacent in bus_graph[location_id]: if adjacent not in stop_visited: stop_visited.add(adjacent) queue.append([total, adjacent,", "target_node, temp_result * weight, visited | {node_id}) if result != -1: return result", "colors = collections.defaultdict(bool) def traverse(node_id, color): colors[node_id] = color for adjacent in graph[node_id]:", "rank[parent_a] += 1 else: parents[parent_a] = parent_b rank[parent_b] += 1 for x, row", "zip(equations, values): graph[origin].append([value, destination]) graph[destination].append([1 / value, origin]) return graph graph = get_graph()", "for word in graph[transform]: if word not in visited: visited.add(word) queue.append([distance + 1,", "i in range(len(edges) + 1)] rank = [1 for _ in range(len(edges) +", "collections.deque([[0, s1]]) visited.add(s1) while queue: value, input_string = queue.popleft() if input_string == s2:", "bus_visited.add(adjacent) queue.append([total + 1, adjacent, 1]) else: for adjacent in bus_graph[location_id]: if adjacent" ]
[ "def remove(self): \"\"\" Remove and return the element at the top of the", "if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with left child if", "0 # denotes next index where new element should go def _down_heapify(self): parent_index", "self.size() == 0: return None self.next_index -= 1 to_remove = self.cbt[0] last_element =", "[None for _ in range(initial_size)] # initialize arrays self.next_index = 0 # denotes", "with right child if right_child is not None: min_element = min(right_child, min_element) #", "if parent is rightly placed if min_element == parent: return if min_element ==", "== right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index def size(self):", "1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last element of the", "initialize arrays self.next_index = 0 # denotes next index where new element should", "self.next_index: left_child = self.cbt[left_child_index] # check if right child exists if right_child_index <", "parent is rightly placed if min_element == parent: return if min_element == left_child:", "not remove the elementm, rather we allow next `insert` operation to overwrite it", "self.cbt[parent_index] = min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent", "= right_child_index def size(self): return self.next_index def remove(self): \"\"\" Remove and return the", "return None self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place", "we do not remove the elementm, rather we allow next `insert` operation to", "if self.size() == 0: return None self.next_index -= 1 to_remove = self.cbt[0] last_element", "right_child is not None: min_element = min(right_child, min_element) # check if parent is", "left_child) # compare with right child if right_child is not None: min_element =", "size(self): return self.next_index def remove(self): \"\"\" Remove and return the element at the", "= parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index]", "# check if left child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index]", "None self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last", "return the element at the top of the heap \"\"\" if self.size() ==", "= last_element # we do not remove the elementm, rather we allow next", "next index where new element should go def _down_heapify(self): parent_index = 0 while", "min_element = parent # check if left child exists if left_child_index < self.next_index:", "to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last element of the cbt", "left_child = None right_child = None min_element = parent # check if left", "# check if parent is rightly placed if min_element == parent: return if", "return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent =", "right_child_index def size(self): return self.next_index def remove(self): \"\"\" Remove and return the element", "the top of the heap \"\"\" if self.size() == 0: return None self.next_index", "index where new element should go def _down_heapify(self): parent_index = 0 while parent_index", "right_child_index = 2 * parent_index + 2 parent = self.cbt[parent_index] left_child = None", "self.next_index = 0 # denotes next index where new element should go def", "range(initial_size)] # initialize arrays self.next_index = 0 # denotes next index where new", "of the cbt at the root self.cbt[0] = last_element # we do not", "last_element = self.cbt[self.next_index] # place last element of the cbt at the root", "* parent_index + 2 parent = self.cbt[parent_index] left_child = None right_child = None", "= self.cbt[right_child_index] # compare with left child if left_child is not None: min_element", "right_child = self.cbt[right_child_index] # compare with left child if left_child is not None:", "= min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index]", "remove(self): \"\"\" Remove and return the element at the top of the heap", "element should go def _down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index", "= min_element parent = right_child_index def size(self): return self.next_index def remove(self): \"\"\" Remove", "= 0 while parent_index < self.next_index: left_child_index = 2 * parent_index + 1", "child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if right", "self.cbt[left_child_index] # check if right child exists if right_child_index < self.next_index: right_child =", "# initialize arrays self.next_index = 0 # denotes next index where new element", "rightly placed if min_element == parent: return if min_element == left_child: self.cbt[left_child_index] =", "< self.next_index: left_child = self.cbt[left_child_index] # check if right child exists if right_child_index", "right child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with", "= None right_child = None min_element = parent # check if left child", "self.cbt = [None for _ in range(initial_size)] # initialize arrays self.next_index = 0", "0 while parent_index < self.next_index: left_child_index = 2 * parent_index + 1 right_child_index", "parent self.cbt[parent_index] = min_element parent = right_child_index def size(self): return self.next_index def remove(self):", "parent_index + 1 right_child_index = 2 * parent_index + 2 parent = self.cbt[parent_index]", "self.cbt[parent_index] left_child = None right_child = None min_element = parent # check if", "= 2 * parent_index + 1 right_child_index = 2 * parent_index + 2", "left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent =", "None: min_element = min(right_child, min_element) # check if parent is rightly placed if", "= self.cbt[self.next_index] # place last element of the cbt at the root self.cbt[0]", "min(parent, left_child) # compare with right child if right_child is not None: min_element", "left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element ==", "the heap \"\"\" if self.size() == 0: return None self.next_index -= 1 to_remove", "if left child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check", "_down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index = 2 * parent_index", "# compare with left child if left_child is not None: min_element = min(parent,", "parent_index + 2 parent = self.cbt[parent_index] left_child = None right_child = None min_element", "+ 2 parent = self.cbt[parent_index] left_child = None right_child = None min_element =", "new element should go def _down_heapify(self): parent_index = 0 while parent_index < self.next_index:", "if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if right child exists", "in range(initial_size)] # initialize arrays self.next_index = 0 # denotes next index where", "placed if min_element == parent: return if min_element == left_child: self.cbt[left_child_index] = parent", "top of the heap \"\"\" if self.size() == 0: return None self.next_index -=", "last element of the cbt at the root self.cbt[0] = last_element # we", "child if right_child is not None: min_element = min(right_child, min_element) # check if", "check if left child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] #", "do not remove the elementm, rather we allow next `insert` operation to overwrite", "= self.cbt[parent_index] left_child = None right_child = None min_element = parent # check", "min_element parent = right_child_index def size(self): return self.next_index def remove(self): \"\"\" Remove and", "# check if right child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index]", "= min(parent, left_child) # compare with right child if right_child is not None:", "= left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent", "Remove and return the element at the top of the heap \"\"\" if", "cbt at the root self.cbt[0] = last_element # we do not remove the", "\"\"\" Remove and return the element at the top of the heap \"\"\"", "parent_index < self.next_index: left_child_index = 2 * parent_index + 1 right_child_index = 2", "= None min_element = parent # check if left child exists if left_child_index", "= parent self.cbt[parent_index] = min_element parent = right_child_index def size(self): return self.next_index def", "return self.next_index def remove(self): \"\"\" Remove and return the element at the top", "self.next_index def remove(self): \"\"\" Remove and return the element at the top of", "denotes next index where new element should go def _down_heapify(self): parent_index = 0", "if right child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare", "the root self.cbt[0] = last_element # we do not remove the elementm, rather", "left child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if", "== 0: return None self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index]", "self.cbt[right_child_index] # compare with left child if left_child is not None: min_element =", "self.cbt[0] = last_element # we do not remove the elementm, rather we allow", "2 * parent_index + 1 right_child_index = 2 * parent_index + 2 parent", "left_child = self.cbt[left_child_index] # check if right child exists if right_child_index < self.next_index:", "# denotes next index where new element should go def _down_heapify(self): parent_index =", "elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index", "heap \"\"\" if self.size() == 0: return None self.next_index -= 1 to_remove =", "self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last element", "self.next_index: left_child_index = 2 * parent_index + 1 right_child_index = 2 * parent_index", "child if left_child is not None: min_element = min(parent, left_child) # compare with", "element of the cbt at the root self.cbt[0] = last_element # we do", "left_child_index = 2 * parent_index + 1 right_child_index = 2 * parent_index +", "is rightly placed if min_element == parent: return if min_element == left_child: self.cbt[left_child_index]", "min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index elif", "def size(self): return self.next_index def remove(self): \"\"\" Remove and return the element at", "last_element # we do not remove the elementm, rather we allow next `insert`", "element at the top of the heap \"\"\" if self.size() == 0: return", "if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index", "\"\"\" if self.size() == 0: return None self.next_index -= 1 to_remove = self.cbt[0]", "def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize arrays", "go def _down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index = 2", "right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index def size(self): return", "2 * parent_index + 2 parent = self.cbt[parent_index] left_child = None right_child =", "left_child is not None: min_element = min(parent, left_child) # compare with right child", "the elementm, rather we allow next `insert` operation to overwrite it self.cbt[self.next_index] =", "if left_child is not None: min_element = min(parent, left_child) # compare with right", "and return the element at the top of the heap \"\"\" if self.size()", "parent: return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent", "0: return None self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] #", "min(right_child, min_element) # check if parent is rightly placed if min_element == parent:", "left child if left_child is not None: min_element = min(parent, left_child) # compare", "we allow next `insert` operation to overwrite it self.cbt[self.next_index] = to_remove self._down_heapify() return", "is not None: min_element = min(parent, left_child) # compare with right child if", "= self.cbt[0] last_element = self.cbt[self.next_index] # place last element of the cbt at", "parent = self.cbt[parent_index] left_child = None right_child = None min_element = parent #", "None right_child = None min_element = parent # check if left child exists", "should go def _down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index =", "parent = right_child_index def size(self): return self.next_index def remove(self): \"\"\" Remove and return", "left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if right child exists if", "def _down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index = 2 *", "= 2 * parent_index + 2 parent = self.cbt[parent_index] left_child = None right_child", "min_element = min(right_child, min_element) # check if parent is rightly placed if min_element", "is not None: min_element = min(right_child, min_element) # check if parent is rightly", "self.cbt[0] last_element = self.cbt[self.next_index] # place last element of the cbt at the", "= self.cbt[left_child_index] # check if right child exists if right_child_index < self.next_index: right_child", "with left child if left_child is not None: min_element = min(parent, left_child) #", "the element at the top of the heap \"\"\" if self.size() == 0:", "None min_element = parent # check if left child exists if left_child_index <", "arrays self.next_index = 0 # denotes next index where new element should go", "Heap: def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize", "< self.next_index: left_child_index = 2 * parent_index + 1 right_child_index = 2 *", "allow next `insert` operation to overwrite it self.cbt[self.next_index] = to_remove self._down_heapify() return to_remove", "None: min_element = min(parent, left_child) # compare with right child if right_child is", "self.cbt[self.next_index] # place last element of the cbt at the root self.cbt[0] =", "of the heap \"\"\" if self.size() == 0: return None self.next_index -= 1", "__init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize arrays self.next_index", "= min(right_child, min_element) # check if parent is rightly placed if min_element ==", "1 right_child_index = 2 * parent_index + 2 parent = self.cbt[parent_index] left_child =", "exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with left child", "elementm, rather we allow next `insert` operation to overwrite it self.cbt[self.next_index] = to_remove", "child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with left", "2 parent = self.cbt[parent_index] left_child = None right_child = None min_element = parent", "place last element of the cbt at the root self.cbt[0] = last_element #", "< self.next_index: right_child = self.cbt[right_child_index] # compare with left child if left_child is", "self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element == right_child:", "parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element", "* parent_index + 1 right_child_index = 2 * parent_index + 2 parent =", "self.next_index: right_child = self.cbt[right_child_index] # compare with left child if left_child is not", "right_child = None min_element = parent # check if left child exists if", "right child if right_child is not None: min_element = min(right_child, min_element) # check", "min_element) # check if parent is rightly placed if min_element == parent: return", "+ 1 right_child_index = 2 * parent_index + 2 parent = self.cbt[parent_index] left_child", "not None: min_element = min(parent, left_child) # compare with right child if right_child", "class Heap: def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] #", "_ in range(initial_size)] # initialize arrays self.next_index = 0 # denotes next index", "for _ in range(initial_size)] # initialize arrays self.next_index = 0 # denotes next", "at the root self.cbt[0] = last_element # we do not remove the elementm,", "exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if right child", "rather we allow next `insert` operation to overwrite it self.cbt[self.next_index] = to_remove self._down_heapify()", "= parent # check if left child exists if left_child_index < self.next_index: left_child", "min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index def", "not None: min_element = min(right_child, min_element) # check if parent is rightly placed", "min_element == parent: return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] =", "parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] =", "remove the elementm, rather we allow next `insert` operation to overwrite it self.cbt[self.next_index]", "parent_index = 0 while parent_index < self.next_index: left_child_index = 2 * parent_index +", "compare with left child if left_child is not None: min_element = min(parent, left_child)", "# place last element of the cbt at the root self.cbt[0] = last_element", "= 0 # denotes next index where new element should go def _down_heapify(self):", "check if parent is rightly placed if min_element == parent: return if min_element", "the cbt at the root self.cbt[0] = last_element # we do not remove", "if min_element == parent: return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index]", "where new element should go def _down_heapify(self): parent_index = 0 while parent_index <", "-= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last element of", "check if right child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] #", "while parent_index < self.next_index: left_child_index = 2 * parent_index + 1 right_child_index =", "min_element = min(parent, left_child) # compare with right child if right_child is not", "parent # check if left child exists if left_child_index < self.next_index: left_child =", "compare with right child if right_child is not None: min_element = min(right_child, min_element)", "initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize arrays self.next_index =", "# compare with right child if right_child is not None: min_element = min(right_child,", "== left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element", "right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with left child if left_child", "if right_child is not None: min_element = min(right_child, min_element) # check if parent", "self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index def size(self): return self.next_index", "root self.cbt[0] = last_element # we do not remove the elementm, rather we", "== parent: return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element", "# we do not remove the elementm, rather we allow next `insert` operation", "at the top of the heap \"\"\" if self.size() == 0: return None", "<reponame>michal0janczyk/udacity_data_structures_and_algorithms_nanodegree class Heap: def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)]", "= [None for _ in range(initial_size)] # initialize arrays self.next_index = 0 #", "min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] =", "self.cbt[parent_index] = min_element parent = right_child_index def size(self): return self.next_index def remove(self): \"\"\"" ]
[ "m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta:", "\"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\" def __str__(self): return f\"{self.pk}: '{self.title}'\"", "media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering", "m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\"", "import models as m class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media", "<reponame>rko619619/Skidon from django.db import models as m class Katalog(m.Model): title = m.TextField(unique=True) content", "ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}:", "\"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\" def __str__(self): return", "= m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\",", "= m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural =", "blank=True) class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"]", "Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self):", "m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\",", "content = m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural", "Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True,", "\"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya #", "verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return", "= \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya", "adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\",", "\"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\" def __str__(self): return f\"{self.pk}:", "models as m class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media =", "class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\", \"adress\"] def", "= m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering =", "m class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress", "m.TextField(null=True, blank=True) class Meta: verbose_name_plural = \"katalog\" ordering = [\"id\", \"title\", \"content\", \"media\",", "\"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\" def __str__(self):", "= [\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\"", "as m class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True)", "django.db import models as m class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True)", "[\"id\", \"title\", \"content\", \"media\", \"adress\"] def __repr__(self): return f\"Zavedeniya # {self.pk}: '{self.title}'\" def", "from django.db import models as m class Katalog(m.Model): title = m.TextField(unique=True) content =", "title = m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True)", "= m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress = m.TextField(null=True, blank=True) class", "class Katalog(m.Model): title = m.TextField(unique=True) content = m.TextField(unique=True) media = m.URLField(unique=True) adress =" ]
[ "'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M',", "40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40,", "else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g", "y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num):", "else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if", "20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30,", "y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9,", "== 0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results)", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio,", "0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0)", "Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit,", "= 0 for i in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if", "1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1)", "count = -1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5)", "or atitle == 'Gmeanratio': if MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline", "0-16 y1.append(float(strline[0])) ''' count = -1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2)", "100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100,", "= marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0)", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio,", "baseline == 0: return 1 for i in results: if i == 0:", "x14, x15, x16, x17 global y1, y2, y3, y4, y5, y6, y7, y8,", "get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean", "#print resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks 10 an 20 utililist", "'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M',", "100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if atitle == 'Ameanratio'", "= 0 while fileidx < group: tmpUtil = [] f1 = open(var1+\".txt\", 'r')", "x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15,", "label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11,", "'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean',", "100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode) #", "are for Limited-preemptive scheduling so # of arguments is 6. def wayofMean(way, num,", "= [] tmpRes5 = [] tmpRes6 = [] tmpRes7 = [] tmpRes8 =", "1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1)", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1 = []", "100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100,", "y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num):", "pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12,", "i < 0: continue elif baseline >= i : if i/baseline <= 1:", "100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "= [] x2 = [] y2 = [] x3 = [] y3 =", "'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M',", "wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST", "MST == 1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title =", "= line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean if", "for tasks 10 an 20 utililist = [] if num == 40: readyres", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10,", "y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker =", "resTotal3 = [] resTotal4 = [] resTotal5 = [] resTotal6 = [] resTotal7", "marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot(", "'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L',", "y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker =", "'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1,", "[] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s,", "y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13,", "[] resTotal17 = [] def fileInput(var1, group, s): fileidx = 0 utililist =", "100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "tmp = [] icount = 0 for j in i: #every numinSets input", "= [] x6 = [] y6 = [] x7 = [] y7 =", "label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3,", "f1: if count == -1: #filename to get utilization: filename = line.split('_') #print", "[] x10 = [] y10 = [] x11 = [] y11 = []", "== 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName =", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode", "wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean,", "[] tmpRes16 = [] tmpRes17 = [] for line in f1: if count", "0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s,", "'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M',", ">= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return 1 return", "3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST", ")) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g = 6 if", "[] tmpRes11 = [] tmpRes12 = [] tmpRes13 = [] tmpRes14 = []", "0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s,", "y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker =", "'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio',", "20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L')", "10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40,", "= [] count = 0 if num == 40: icount = (icount+1)%6 elif", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio,", "100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100,", "tasks 10 an 20 utililist = [] if num == 40: readyres =", "== 'Gmeanratio': if MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else:", "marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)',", "tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14]))", "else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g", "or atitle == 'Gmeanratio': if MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline", "# of arguments is 6. def wayofMean(way, num, atitle, typ, s, MST, btype", "1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3)", "resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14)", "20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20,", "marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo',", "label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04,", "= strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit,", "'-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker =", "1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1)", "100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode)", "1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio',", "i in getResPerUtili(resTotal1,s, num): #when g = 6 if atitle == 'Ameanratio' or", "y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if atitle ==", "= [] x12 = [] y12 = [] x13 = [] y13 =", "[[] for i in range(6)] elif num == 30: readyres = [[] for", "count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9)", "0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0)", "size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio':", "10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20,", "100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100,", "'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M',", "label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot( x1, y1,", "as np import matplotlib.pyplot as plt import itertools from matplotlib import rcParams from", "res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0:", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y6.append(way(i, num)) else: y6.append(way(i,", "20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2,", "== 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14,", "mode == 'ILP': if num < 30: ax.plot( x1, y1, '-', marker =", "num < 30: ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot(", "ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix]", "'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean',", "wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean,", "x11, x12, x13, x14, x15, x16, x17 global y1, y2, y3, y4, y5,", "'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20,", "mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST ==", "baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return 1", "results: if i == 0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else:", "TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation", "== 'Gmeanratio': if MST == 0: #print i, num #print way(i, num) y14.append(way(i,", "tmpRes2 = [] tmpRes3 = [] tmpRes4 = [] tmpRes5 = [] tmpRes6", "i in getResPerUtili(resTotal17,s, num): #when g = 6 if atitle == 'Ameanratio' or", "'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M',", "Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g = 6 if", "icount = (icount+1)%7 else: icount = (icount+1)%8 icount = 0 count = 0", "y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num):", "resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx", "== 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in", "20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30,", "Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle ==", "y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15,", "marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else:", "count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if num ==", "Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g = 6", "else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g", "== 'Gmeanratio': if MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else:", "else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g", "label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17,", "fileInput(target, g, s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i)", "= [] resTotal2 = [] resTotal3 = [] resTotal4 = [] resTotal5 =", "1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1)", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100,", "20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20,", "ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder =", "3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1)", "== 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in", "tmp.append(j) count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count", "'-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(),", "'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10,", "resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13)", "'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)',", "'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean,", "2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20,", "'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean',", "else: res.append(1) if len(results) == 0: return 1 return np.mean(res) def Gmeanratio(results, baseline):", "'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20,", "0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0)", "wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean,", "2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1)", "1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1)", "100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "line in f1: if count == -1: #filename to get utilization: filename =", "ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's',", "import numpy as np import matplotlib.pyplot as plt import itertools from matplotlib import", "1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1)", "'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "resTotal15 = [] resTotal16 = [] resTotal17 = [] def fileInput(var1, group, s):", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y7.append(way(i, num)) else: y7.append(way(i,", "elif mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0)", "40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y8.append(way(i,", "40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio,", "if MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for", "20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20,", "'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio',", "x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker", "[[] for i in range(7)] else: readyres = [[] for i in range(8)]", "[representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this, 6 sets of methods are", "'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L',", "if MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline =", "else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g = 6 if atitle", "wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean,", "100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40,", ")) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g = 6 if", "'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype", "i in getResPerUtili(resTotal14,s, num): #when g = 6 if atitle == 'Ameanratio' or", "'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S',", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "if MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M',", "20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20,", "else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax", "100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100,", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M',", "x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i)", "atitle == 'Gmeanratio': if MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline ))", "y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num", "1 for i in results: if i == 0: res.append(1) elif i <", "target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for", "30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2,", "Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry", "'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L',", "wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean,", "'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M',", "i: #every numinSets input for each utilization tmp.append(j) count+=1 #print icount if count", "y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g =", "strline = strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline,", "= 1 def main(): args = sys.argv if len(args) < 1 or len(args)", "100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S',", "y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0,", "if btype != 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST ==", "'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20)", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio',", "'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode)", "'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio,", "wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean,", "y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker =", "marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(),", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1,", "marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30:", "res.append(1) if len(results) == 0: return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean',", "'Gmeanratio': if MST == 0: #print i, num #print way(i, num) y14.append(way(i, num))", "10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10,", "= [] y5 = [] x6 = [] y6 = [] x7 =", "linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode ==", "[] resTotal15 = [] resTotal16 = [] resTotal17 = [] def fileInput(var1, group,", "100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100,", "flag = 0 while fileidx < group: tmpUtil = [] f1 = open(var1+\".txt\",", "y1 = [] x2 = [] y2 = [] x3 = [] y3", "while fileidx < group: tmpUtil = [] f1 = open(var1+\".txt\", 'r') count =", "1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11)", "tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7]))", "[] y1 = [] x2 = [] y2 = [] x3 = []", "#CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count ==", "= [[] for i in range(8)] count = 0 for ind, i in", "#wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio,", "'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "\"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode == 'ILP': title", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') ''' if __name__ == \"__main__\": main()", "= 0-16 y1.append(float(strline[0])) ''' count = -1 continue count += 1 f1.close() resTotal1.append(tmpRes1)", "#wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio,", "Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g = 6", "+= 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10)", "[] y5 = [] x6 = [] y6 = [] x7 = []", "100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target", "40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40,", "getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13) for i in", "x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i)", "mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot(", "1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1)", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y6.append(way(i,", "else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g = 6 if atitle", "resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = []", "MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4)", "1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio',", "x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot(", "2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "matplotlib matplotlib.use('Agg') import matplotlib.patches as mpatches import random import math import sys import", "== -1: #filename to get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content", "'Gmeanratio': if MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline", "0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0)", "0: if mode == 'REP': if num < 30: ax.plot( x4, y4, '-',", "100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100,", "100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100,", "else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g", "100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100,", "<= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) == 0: return 1", "if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName", "'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10,", "'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L',", "= [] def fileInput(var1, group, s): fileidx = 0 utililist = [] flag", "0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0)", "for i in range(6)] elif num == 30: readyres = [[] for i", "= marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0)", "1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "in getResPerUtili(resTotal2,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "i == 0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if", "= marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0)", "= marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0)", "mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot(", "'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "range(8)] count = 0 for ind, i in enumerate(res): #each file #print \"\"", "x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif", "[] tmpRes17 = [] for line in f1: if count == -1: #filename", ")) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g = 6 if", "resTotal8 = [] resTotal9 = [] resTotal10 = [] resTotal11 = [] resTotal12", "= marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0)", "ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-',", "i in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if atitle == 'Ameanratio'", "x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker", "= [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio,", "10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10,", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100,", "i in range(7)] else: readyres = [[] for i in range(8)] count =", "atitle == 'Gmeanratio': if MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline ))", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y1.append(way(i, num)) else:", "Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g = 6", "== 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14,", "'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') ''' if", "atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20)", "i in results: if i == 0: res.append(1) elif i < 0: continue", "20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30,", "#ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline", "x13 = [] y13 = [] x14 = [] y14 = [] x15", "in i: #every numinSets input for each utilization tmp.append(j) count+=1 #print icount if", "== 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4", ")) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g = 6 if", "#ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-',", "group, s): fileidx = 0 utililist = [] flag = 0 while fileidx", "= [] if baseline ==0: return 1 for i in results: if i", "== 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype", "100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100,", "100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100,", "[] x2 = [] y2 = [] x3 = [] y3 = []", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')'", "= [] x11 = [] y11 = [] x12 = [] y12 =", "in getResPerUtili(resTotal12,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if num <", "def Ameanratio(results, baseline): res = [] if baseline ==0: return 1 for i", "#plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle ==", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y5.append(way(i, num))", "'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20,", "#wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio,", "100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100,", "len(i) tmp = [] icount = 0 for j in i: #every numinSets", "x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1:", "getResPerUtili(resTotal3,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6 def getResPerUtili(res,", "y15 = [] x16 = [] y16 = [] x17 = [] y17", "> numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if num == 40:", "#Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix", "100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100,", "'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S',", "'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2,", "10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10,", "100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode) #", "pdf pp = PdfPages(folder + fileName + '.pdf') if btype != 'N': atitle", "resTotal14 = [] resTotal15 = [] resTotal16 = [] resTotal17 = [] def", "wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean,", "marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)',", "#ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0)", "30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2,", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M',", "y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker =", "icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if", "y9, y10, y11, y12, y13, y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3,", "label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot(", "'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10,", "'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio,", "= [] tmpRes4 = [] tmpRes5 = [] tmpRes6 = [] tmpRes7 =", "1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes,", "== 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else:", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y4.append(way(i, num)) else: y4.append(way(i,", "x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker", "= marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0)", "global x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12,", "= (icount+1)%8 icount = 0 count = 0 for i in readyres: utililist.append(i)", "marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif", "label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16,", "x10, x11, x12, x13, x14, x15, x16, x17 global y1, y2, y3, y4,", "'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean',", "#filename to get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get", "'Gmeanratio': if MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i))", "resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return", "marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)',", "2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count = -1 continue count +=", "= max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g = 6 if atitle", "label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode", "x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13,", "'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio',", "#ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1)", "tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9]))", "'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S',", "else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g = 6 if atitle", "if num == 40: readyres = [[] for i in range(6)] elif num", "'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode)", "for i in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if atitle ==", "'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L',", "strline = strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count =", "i in enumerate(res): #each file #print \"\" #print i #print len(i) tmp =", "0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) ==", "else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i in utili[0]:", "= [] resTotal6 = [] resTotal7 = [] resTotal8 = [] resTotal9 =", "y12, y13, y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6,", "'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode)", "mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST ==", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio,", "'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M',", "== 'Gmeanratio': if MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i))", "marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit',", "1 or len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y6.append(way(i, num))", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio',", "to get Arithmetic mean and Gmean if 0 <count < s*2: if count%2==1:", "of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean':", "y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if atitle ==", "as mpatches import random import math import sys import numpy as np import", "y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = []", "strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x =", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y12.append(way(i,", "'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean',", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y7.append(way(i, num))", "#print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean if 0 <count", "20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20,", "'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline", "#TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if", ")) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g = 6 if", "in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if atitle == 'Ameanratio' or", "40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio,", "Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g = 6 if", "x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker", "tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6]))", ") #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 )", "'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean',", "#wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio,", "for i in range(7)] else: readyres = [[] for i in range(8)] count", "100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i in", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1,", "fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num):", "'-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(),", "if MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for", "linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5,", "2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30,", "'Gmeanratio': if MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i))", "= [] x16 = [] y16 = [] x17 = [] y17 =", "0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0)", "100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100,", "= sys.argv if len(args) < 1 or len(args) > 2: print \"Usage: python", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100,", "'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S',", "= 6 Inflation if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST", "0: return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) #", "'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio',", "resTotal13 = [] resTotal14 = [] resTotal15 = [] resTotal16 = [] resTotal17", "x1 = [] y1 = [] x2 = [] y2 = [] x3", "== 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline", "'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode)", "== 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline", "y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in pdf pp", "# wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10,", "100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100,", "'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio',", "if num == 40: icount = (icount+1)%6 elif num == 30: icount =", "TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2]))", "'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S')", "y4 = [] x5 = [] y5 = [] x6 = [] y6", "linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode ==", "line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print strline #strline[x]", "20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2,", "if MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for", "0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100,", "100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "baseline >= i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1)", "= [] flag = 0 while fileidx < group: tmpUtil = [] f1", "y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g =", "100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100,", "'-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(),", "i in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if atitle == 'Ameanratio'", "wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean,", "res = [] if baseline == 0: return 1 for i in results:", "or atitle == 'Gmeanratio': if MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline", "MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i", "100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean,", "'-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13,", "= 0 for ind, i in enumerate(res): #each file #print \"\" #print i", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: #print", "ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-',", "wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio,", "'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M',", "'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean',", "marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes", "30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40,", "100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100,", "'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M',", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1)", "fileidx += 1 return utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work for", "0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s,", "s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i)", "wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean,", "y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13,", "ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif", "= marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0)", "ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-',", "== 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in", "= marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes )", "\"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85,", "for Limited-preemptive scheduling so # of arguments is 6. def wayofMean(way, num, atitle,", "the results are for Limited-preemptive scheduling so # of arguments is 6. def", "Inflation if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0:", "30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40,", "if MST == 0: if mode == 'REP': if num < 30: ax.plot(", "TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0]))", "= marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0)", "mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S',", "#print \"\" #print i #print len(i) tmp = [] icount = 0 for", "0: return 1 for i in results: if i == 0: res.append(1) elif", "'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20,", "= plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\",", "'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40,", "'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "0 tmpRes1 = [] tmpRes2 = [] tmpRes3 = [] tmpRes4 = []", "10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10,", "#each file #print \"\" #print i #print len(i) tmp = [] icount =", "(icount+1)%8 icount = 0 count = 0 for i in readyres: utililist.append(i) return", "'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g =", "for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s,", "100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100,", "'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') ''' if __name__ == \"__main__\":", "[] y3 = [] x4 = [] y4 = [] x5 = []", "= [] resTotal16 = [] resTotal17 = [] def fileInput(var1, group, s): fileidx", "x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker", "ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-',", "print fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num): #when g =", "#wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio,", "= marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0)", "'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean',", "'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean',", "'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8,", "'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10,", "0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0)", "[] resTotal8 = [] resTotal9 = [] resTotal10 = [] resTotal11 = []", "else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g", "'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M',", "20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20,", "# Now assume all the results are for Limited-preemptive scheduling so # of", "= [] resTotal17 = [] def init(): global x1, x2, x3, x4, x5,", "= -1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6)", "100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100,", "wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean,", "'Gmeanratio': if MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i))", "tmpy7 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i", "#strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock,", "10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10,", "y13, y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7,", "= [] y17 = [] resTotal1 = [] resTotal2 = [] resTotal3 =", "'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean',", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10,", "count = 0 if num == 40: icount = (icount+1)%6 elif num ==", "0 utililist = [] flag = 0 while fileidx < group: tmpUtil =", "wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean,", "or atitle == 'Gmeanratio': if MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline", "'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "= [] y16 = [] x17 = [] y17 = [] resTotal1 =", "'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio',", "= marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0)", "= [] x5 = [] y5 = [] x6 = [] y6 =", "'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7, y7,", "6 sets of methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0)", "Mbaseline = max(y4) tmpy4 = [] if atitle == 'Ameanratio' or atitle ==", ": if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) ==", "getResPerUtili(resTotal1,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M',", "[] x16 = [] y16 = [] x17 = [] y17 = []", "'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline =", "i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num):", "label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4,", "'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i)", "20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2,", "'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10,", "label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(),", "getResPerUtili(resTotal15,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "1 return utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks 10", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio,", "resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13,", "Ameanratio(results, baseline): res = [] if baseline ==0: return 1 for i in", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100,", "num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s,", "marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST == 0: if", "0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s,", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0)", "'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10,", "2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10,", "0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0)", "linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11,", "'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode)", "100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100,", "x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker", "#plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means", "30: ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6,", "== 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2:", "100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100,", "tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1:", "tmpRes13 = [] tmpRes14 = [] tmpRes15 = [] tmpRes16 = [] tmpRes17", "if len(args) < 1 or len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\"", "label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10,", ") #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10,", "'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L',", "100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100,", "'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean',", "[] x3 = [] y3 = [] x4 = [] y4 = []", "'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio',", "marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass", "30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40,", "1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1)", "#TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry", "'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode)", "size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if", "y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g =", "matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1 =", "= fileInput(target, g, s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i)", "ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-',", "== s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline =", "'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio',", "results: if i == 0: res.append(1) elif i < 0: continue elif baseline", "num): #when g = 6 Inflation if atitle == 'Ameanratio' or atitle ==", "Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try:", "if num < 30: ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0)", "1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1)", "'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0)", "'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "'-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(),", "getResPerUtili(res, numinSets, num): #work for tasks 10 an 20 utililist = [] if", "30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S')", "== 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in", "in getResPerUtili(resTotal16,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT':", "wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean,", "30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30,", "matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1 = [] y1 = []", "'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M',", "'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S',", "tmpy13 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i", "marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker =", "0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0)", "100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100,", "label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13,", "for line in f1: if count == -1: #filename to get utilization: filename", "'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40,", "'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2,", "= marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0)", "0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g = 6", "y12 = [] x13 = [] y13 = [] x14 = [] y14", "y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker =", "10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10,", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y6.append(way(i, num)) else:", "20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2,", "100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if atitle == 'Ameanratio' or atitle", "100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100,", "1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1)", "f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12)", "resTotal1 = [] resTotal2 = [] resTotal3 = [] resTotal4 = [] resTotal5", "input for each utilization tmp.append(j) count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp", "'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L',", "y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num):", "0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix,", "atitle == 'Gmeanratio': if MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else:", "tmpRes17 = [] for line in f1: if count == -1: #filename to", "[] if baseline == 0: return 1 for i in results: if i", "100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100,", "y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num):", "label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13,", "num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when", "tmpRes15 = [] tmpRes16 = [] tmpRes17 = [] for line in f1:", "'Gmeanratio': if MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i))", "'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio,", "'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10,", "y14 = [] x15 = [] y15 = [] x16 = [] y16", "linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15,", "x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker", "1 return np.mean(res) def Gmeanratio(results, baseline): res = [] if baseline == 0:", "3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline =", "wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio,", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio,", "6 TDAbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST ==", "atitle == 'Gmeanratio': if MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline ))", "elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker =", "100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100,", "100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100,", "'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4,", "2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30,", "'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o',", "1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "y11, y12, y13, y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5,", "x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if", "#CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline", "wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio,", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean,", "y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g =", "s, MST, btype = 'N', mode = 'REP'): init() typ.replace(\"'\", '') if MST", "label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17,", "ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode ==", "100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1,", "tmpRes14 = [] tmpRes15 = [] tmpRes16 = [] tmpRes17 = [] for", "0 <count < s*2: if count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline", "atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode ==", "x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i)", "100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S')", "'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L',", "y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num):", "2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30,", "linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12,", "continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8)", "prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100,", "max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g = 6 if atitle ==", ")) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g = 6 if", "marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot( x1,", "for i in getResPerUtili(resTotal14,s, num): #when g = 6 if atitle == 'Ameanratio'", "0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0)", "1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio',", "== 'Gmeanratio': if MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i))", "[] x8 = [] y8 = [] x9 = [] y9 = []", "plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of", "else: if mode == 'REP': if num < 30: ax.plot( x4, y4, '-',", "np import matplotlib.pyplot as plt import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf", "atitle == 'Gmeanratio': if MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline ))", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100,", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y13.append(way(i, num)) else:", "arguments is 6. def wayofMean(way, num, atitle, typ, s, MST, btype = 'N',", "g = 6 TDAbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if", "#wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio,", "'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L',", "1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1)", "100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "6 CTbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST ==", "#ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry", "100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100,", "y13 = [] x14 = [] y14 = [] x15 = [] y15", "resTotal16, resTotal17 x1 = [] y1 = [] x2 = [] y2 =", "= marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0)", "[] resTotal5 = [] resTotal6 = [] resTotal7 = [] resTotal8 = []", "#wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio,", "y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if", "'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode)", ")) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline", "1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10,", "plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16)", "'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M',", "= [] f1 = open(var1+\".txt\", 'r') count = -1 flag = 0 tmpRes1", "= [] tmpRes12 = [] tmpRes13 = [] tmpRes14 = [] tmpRes15 =", "1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now assume", "x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker", "elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0)", "-1 mode = args[1] #after this, 6 sets of methods are prepared '''", "elif num == 30: readyres = [[] for i in range(7)] else: readyres", "means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric", "10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20,", "elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target =", "linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode", "num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s,", "g = 1 def main(): args = sys.argv if len(args) < 1 or", "100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y11.append(way(i, num)) else: y11.append(way(i,", "utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work", "1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1)", "or atitle == 'Gmeanratio': if MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline", "y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16,", "40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L')", "import sys import numpy as np import matplotlib.pyplot as plt import itertools from", "mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot(", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio',", "linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12,", "> 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after", "0: res.append(1) elif i < 0: continue elif baseline >= i : if", "'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S',", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num):", "= marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0)", "'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif", "= marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot(", "y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num):", "ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7,", "'o', 's', 'v')) try: if MST == 0: if mode == 'REP': if", "100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100,", "100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100,", "10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L')", "x12, x13, x14, x15, x16, x17 global y1, y2, y3, y4, y5, y6,", "'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') #", "wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean,", "num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1,", "#ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock", "'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M',", "'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M',", "marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot(", "= 6 if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST ==", "x3 = [] y3 = [] x4 = [] y4 = [] x5", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y9.append(way(i, num)) else:", "linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15,", "0 for i in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if atitle", "marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)',", "y10 = [] x11 = [] y11 = [] x12 = [] y12", "num == 30: readyres = [[] for i in range(7)] else: readyres =", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y3.append(way(i,", "MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i", "100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100,", "10 an 20 utililist = [] if num == 40: readyres = [[]", "[] tmpRes14 = [] tmpRes15 = [] tmpRes16 = [] tmpRes17 = []", "'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100,", "2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100,", "ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-',", "#wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y4.append(way(i,", "else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if atitle", "== 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7", "label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if num < 30: ax.plot( x4,", "= strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo,", "0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s,", "else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g = 6 if atitle", "tmpRes9 = [] tmpRes10 = [] tmpRes11 = [] tmpRes12 = [] tmpRes13", "'') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target", "filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean", "1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1)", "[] count = 0 if num == 40: icount = (icount+1)%6 elif num", "= [] y3 = [] x4 = [] y4 = [] x5 =", "wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio,", "i in getResPerUtili(resTotal3,s, num): #when g = 6 if atitle == 'Ameanratio' or", "[] def init(): global x1, x2, x3, x4, x5, x6, x7, x8, x9,", "'-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(),", "#when g = 6 ILPbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker", "wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean,", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode ==", "= \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode == 'ILP':", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else:", "fileName + '.pdf') if btype != 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')'", "6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g = 1 def main():", "[] def fileInput(var1, group, s): fileidx = 0 utililist = [] flag =", "in getResPerUtili(resTotal6,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10,", "100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100,", "atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num): #when g", "= 'plots/' g = 1 def main(): args = sys.argv if len(args) <", "marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot(", "linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(),", "= [] tmpRes6 = [] tmpRes7 = [] tmpRes8 = [] tmpRes9 =", ")) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g = 6 if", "Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g = 6", "for i in results: if i == 0: res.append(1) elif i < 0:", "x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M',", "y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker =", "# wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "#ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04,", "label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode", "wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean,", "pp = PdfPages(folder + fileName + '.pdf') if btype != 'N': atitle =", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio,", "0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100,", "label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7, y7, '-', marker =", "'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M',", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "= [] tmpRes3 = [] tmpRes4 = [] tmpRes5 = [] tmpRes6 =", "x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-',", "40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2,", "atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\",", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean',", "marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot(", "resTotal9 = [] resTotal10 = [] resTotal11 = [] resTotal12 = [] resTotal13", "Gmean if 0 <count < s*2: if count%2==1: strline = line.replace('[','') strline =", "'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "init() typ.replace(\"'\", '') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST ==", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100,", "global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12,", "= [] y13 = [] x14 = [] y14 = [] x15 =", "ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-',", "atitle == 'Gmeanratio': if MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline ))", "linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7,", "marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-',", "'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio',", "< 1 or len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1", "x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5,", "atitle == 'Gmeanratio': if MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else:", "10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10,", "fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num): #when g = 6", "'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L',", "'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode)", "or atitle == 'Gmeanratio': if MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline", "typ, s, MST, btype = 'N', mode = 'REP'): init() typ.replace(\"'\", '') if", "= marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0)", "#MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1)", "30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30,", "== 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in", "global y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12,", "if MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline =", "== 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i", "wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean,", "'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1)", "in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when", "'Gmeanratio': if MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i))", "= marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker", "10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2,", "from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1 = [] y1 =", "= [] resTotal3 = [] resTotal4 = [] resTotal5 = [] resTotal6 =", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100,", "tmpRes8 = [] tmpRes9 = [] tmpRes10 = [] tmpRes11 = [] tmpRes12", "20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30,", "'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio',", "'S', 100, 0) # Now assume all the results are for Limited-preemptive scheduling", "0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0)", "100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100,", "'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10,", "ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-',", "wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean,", "'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10,", "= marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0)", "2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30,", "'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio,", "ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP':", "for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i)", "= [] resTotal13 = [] resTotal14 = [] resTotal15 = [] resTotal16 =", "1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1)", "40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio,", "= [] x3 = [] y3 = [] x4 = [] y4 =", "#ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-',", "20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30,", "'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode)", "methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean',", "'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean',", "linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot( x1, y1, '-',", "10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10,", "40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40,", "y7 = [] x8 = [] y8 = [] x9 = [] y9", "wayofMean(way, num, atitle, typ, s, MST, btype = 'N', mode = 'REP'): init()", "plt import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats", "100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100,", "== 'Gmeanratio': if MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else:", "== 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in", "'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean',", "y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot(", "'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L',", "= [] if num == 40: readyres = [[] for i in range(6)]", "1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1)", "linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)',", "ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock,", "'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio',", "for i in getResPerUtili(resTotal8,s, num): #when g = 6 if atitle == 'Ameanratio'", "'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L',", "'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i in", "for i in getResPerUtili(resTotal2,s, num): #when g = 6 if atitle == 'Ameanratio'", "y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if atitle", "ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-',", "\"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure", "100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1,", "x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker", "'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M',", "'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L',", "20 utililist = [] if num == 40: readyres = [[] for i", "'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L',", "[[] for i in range(8)] count = 0 for ind, i in enumerate(res):", "in enumerate(res): #each file #print \"\" #print i #print len(i) tmp = []", "marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif", "#ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-',", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y13.append(way(i, num))", "100, 0) # Now assume all the results are for Limited-preemptive scheduling so", "== 'Gmeanratio': if MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else:", "linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17,", "'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "mpatches import random import math import sys import numpy as np import matplotlib.pyplot", "sys.argv if len(args) < 1 or len(args) > 2: print \"Usage: python mean_printer.py", "mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this, 6 sets of methods", "y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g = 6 if atitle ==", "0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 =", "'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: #print i, num #print", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y3.append(way(i, num)) else: y3.append(way(i,", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y17.append(way(i, num))", "for i in getResPerUtili(resTotal17,s, num): #when g = 6 if atitle == 'Ameanratio'", "20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20,", "100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100,", "30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30,", "icount = 0 count = 0 for i in readyres: utililist.append(i) return utililist", "Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20)", "10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio',", "#ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6])", "for i in getResPerUtili(resTotal3,s, num): #when g = 6 if atitle == 'Ameanratio'", "'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6", "num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in pdf pp =", "0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0)", "== 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline", "wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio,", "0: #print i, num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline ))", "'-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(),", "[] tmpRes3 = [] tmpRes4 = [] tmpRes5 = [] tmpRes6 = []", "'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M',", "PdfPages from scipy.stats.mstats import gmean x1 = [] y1 = [] x2 =", "def getResPerUtili(res, numinSets, num): #work for tasks 10 an 20 utililist = []", "return 1 for i in results: if i == 0: res.append(1) elif baseline", "Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\",", "#Content to get Arithmetic mean and Gmean if 0 <count < s*2: if", "else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g", "'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean',", "# wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0)", "x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype", "'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S',", "10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30,", "\"\" #print i #print len(i) tmp = [] icount = 0 for j", "40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40,", "1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1)", "# wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10,", "x = 0-16 y1.append(float(strline[0])) ''' count = -1 continue count += 1 f1.close()", "elif MST == 2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title", "x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker", "of methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10,", "y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker =", "marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)',", "tmpRes3 = [] tmpRes4 = [] tmpRes5 = [] tmpRes6 = [] tmpRes7", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M',", "[] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s,", "y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17 global resTotal1,", "else: res.append(1) else: res.append(1) if len(results) == 0: return 1 return gmean(res) #", "#when g = 6 if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if", "== 0: return 1 for i in results: if i == 0: res.append(1)", "== 'Gmeanratio': if MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i))", "ILPbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0:", "0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0)", "transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show()", "mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "== 3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit'", "Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g = 6", "'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y12.append(way(i, num)) else: y12.append(way(i,", "2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y16.append(way(i, num)) else: y16.append(way(i,", "'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio',", "marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass", "tmpRes6 = [] tmpRes7 = [] tmpRes8 = [] tmpRes9 = [] tmpRes10", "0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s,", "= marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0)", "y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17", "1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100,", "strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print", "'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M',", "2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30,", "= [] resTotal14 = [] resTotal15 = [] resTotal16 = [] resTotal17 =", "ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle ==", "return np.mean(res) def Gmeanratio(results, baseline): res = [] if baseline == 0: return", "'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L',", "+= 1 return utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks", "0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100,", "100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100,", "0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0)", "'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio',", "40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40,", "for i in range(8)] count = 0 for ind, i in enumerate(res): #each", "\"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf()", "1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio',", "#Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit", "fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle", "y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = []", "y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if atitle ==", "wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean,", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y16.append(way(i, num)) else:", "'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode)", "y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker", "'-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(),", "10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2,", "'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio,", "plt.clf() plt.show() pp.close() folder = 'plots/' g = 1 def main(): args =", "'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M',", "0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0)", "num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when", "[] y10 = [] x11 = [] y11 = [] x12 = []", "'-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num <", "[] x6 = [] y6 = [] x7 = [] y7 = []", "= marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot(", "'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "= [] resTotal10 = [] resTotal11 = [] resTotal12 = [] resTotal13 =", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i))", "label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot(", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100,", "def init(): global x1, x2, x3, x4, x5, x6, x7, x8, x9, x10,", "plt.show() pp.close() folder = 'plots/' g = 1 def main(): args = sys.argv", "MST == 0: if mode == 'REP': if num < 30: ax.plot( x4,", "x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker", "x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName", "100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "random import math import sys import numpy as np import matplotlib.pyplot as plt", "'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "resTotal7 = [] resTotal8 = [] resTotal9 = [] resTotal10 = [] resTotal11", "y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num):", "100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100,", "plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g = 1", "'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10,", "'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10,", "0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0)", ")) else: y17.append(way(i)) # plot in pdf pp = PdfPages(folder + fileName +", "label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot( x1, y1,", "[] resTotal15 = [] resTotal16 = [] resTotal17 = [] def init(): global", "= marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker", "'-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(),", "100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100,", "resTotal17 = [] def fileInput(var1, group, s): fileidx = 0 utililist = []", "wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean,", "'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M',", "= marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)',", "< group: tmpUtil = [] f1 = open(var1+\".txt\", 'r') count = -1 flag", "x14 = [] y14 = [] x15 = [] y15 = [] x16", "else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g = 6 if atitle", "'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M',", "1 for i in results: if i == 0: res.append(1) elif baseline >=", "'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "if i == 0: res.append(1) elif i < 0: continue elif baseline >=", "if MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else: y6.append(way(i)) for", "= [] x17 = [] y17 = [] resTotal1 = [] resTotal2 =", "'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean',", "marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block',", "'-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(),", "utilization tmp.append(j) count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = []", "x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker", "'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio',", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1,", "#wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio,", "mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot(", "#[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline,", "10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20,", "i in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res = [] if", "y5 = [] x6 = [] y6 = [] x7 = [] y7", "100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100,", "x16.append(i) x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2:", "'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot(", "num, atitle, typ, s, MST, btype = 'N', mode = 'REP'): init() typ.replace(\"'\",", "y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker =", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean',", "g = 6 CTbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if", "y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker =", "y3 = [] x4 = [] y4 = [] x5 = [] y5", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode == 'ILP': title =", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i))", "pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g = 1 def main(): args", "#wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio,", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode ==", "marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot(", "each utilization tmp.append(j) count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp =", "= marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)',", "Mbaseline )) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g = 6", "linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print", "for i in getResPerUtili(resTotal6,s, num): #when g = 6 if atitle == 'Ameanratio'", "baseline): res = [] if baseline ==0: return 1 for i in results:", "y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g = 6 if atitle ==", "1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1)", "10, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100,", "for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13)", "getResPerUtili(resTotal2,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype", "100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "40: icount = (icount+1)%6 elif num == 30: icount = (icount+1)%7 else: icount", "0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if atitle == 'Ameanratio'", "'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S',", "marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except", "tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11]))", "elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili =", "100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100,", "for i in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if atitle ==", "100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2,", "0) #MST wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100,", "'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean',", "x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST ==", "max(y7) tmpy7 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for", "= 0 count = 0 for i in readyres: utililist.append(i) return utililist def", "tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count", "[] x13 = [] y13 = [] x14 = [] y14 = []", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100,", "'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100,", "strline = strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0]))", "resTotal4 = [] resTotal5 = [] resTotal6 = [] resTotal7 = [] resTotal8", "CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo", "= [] x9 = [] y9 = [] x10 = [] y10 =", "== 'Gmeanratio': if MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else:", "wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean,", "y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g =", "'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S',", "= 'N', mode = 'REP'): init() typ.replace(\"'\", '') if MST == 3: target", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y10.append(way(i, num)) else:", "btype != 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1:", "x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker", "<reponame>kuanhsunchen/Suspension import matplotlib matplotlib.use('Agg') import matplotlib.patches as mpatches import random import math import", "MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i", "'-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(),", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100,", "tmpUtil = [] f1 = open(var1+\".txt\", 'r') count = -1 flag = 0", "x2 = [] y2 = [] x3 = [] y3 = [] x4", "res.append(1) else: res.append(1) if len(results) == 0: return 1 return gmean(res) # wayofMean(np.mean,", "100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100,", "readyres = [[] for i in range(6)] elif num == 30: readyres =", "def fileInput(var1, group, s): fileidx = 0 utililist = [] flag = 0", "fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100,", "y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num", "100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100,", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio',", "for each utilization tmp.append(j) count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp", "marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)',", "= [] x13 = [] y13 = [] x14 = [] y14 =", "tmpy4 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i", "x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14,", "wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0)", "label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError:", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio',", "= 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i", "x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if", "'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "0 for i in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res =", "2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif", "x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit,", "= [] icount = 0 for j in i: #every numinSets input for", "2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio,", "y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker =", "100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean',", "label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(),", "are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S',", "y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num):", "label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17,", "'Gmeanratio': if MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i))", "100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100,", "numpy as np import matplotlib.pyplot as plt import itertools from matplotlib import rcParams", "'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio,", "== 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in", "20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20,", "2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio,", "open(var1+\".txt\", 'r') count = -1 flag = 0 tmpRes1 = [] tmpRes2 =", "i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) == 0: return", "== 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13", "1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1)", "= 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i", "10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10,", "tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10]))", "label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6,", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y11.append(way(i, num)) else:", "'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio,", "[] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s,", "MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype", "'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M',", "2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100,", "figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g = 1 def", "MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7)", "30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1,", "num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when", "30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30,", "0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0)", "marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30:", "atitle == 'Gmeanratio': if MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline ))", "wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio,", "tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g = 6", "res.append(1) if len(results) == 0: return 1 return np.mean(res) def Gmeanratio(results, baseline): res", "'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "tmpRes1 = [] tmpRes2 = [] tmpRes3 = [] tmpRes4 = [] tmpRes5", "1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1)", "from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1,", "marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation',", "MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype", "marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot(", "print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this, 6", "Mbaseline )) else: y17.append(way(i)) # plot in pdf pp = PdfPages(folder + fileName", "= [] y12 = [] x13 = [] y13 = [] x14 =", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y12.append(way(i, num))", "line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean if 0", "10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20,", "= 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype", "''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0)", "[] resTotal11 = [] resTotal12 = [] resTotal13 = [] resTotal14 = []", "(icount+1)%6 elif num == 30: icount = (icount+1)%7 else: icount = (icount+1)%8 icount", "marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7, y7, '-', marker", "'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "x11 = [] y11 = [] x12 = [] y12 = [] x13", "== 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if", "tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16]))", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')'", "10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2,", "in getResPerUtili(resTotal9,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S',", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode == 'ILP':", "getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if atitle == 'Ameanratio' or atitle", "i, num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i))", "max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g = 6 if atitle ==", "num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when", "return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now assume all", "y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g =", "x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST ==", "1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1)", "= 0 tmpRes1 = [] tmpRes2 = [] tmpRes3 = [] tmpRes4 =", "'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30,", "resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17)", "= 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i in utili[0]: x1.append(i) x2.append(i)", "[] resTotal10 = [] resTotal11 = [] resTotal12 = [] resTotal13 = []", "ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-',", "10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20,", "'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "elif i < 0: continue elif baseline >= i : if i/baseline <=", "30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40,", "'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3:", "y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker =", "'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean',", "0 for j in i: #every numinSets input for each utilization tmp.append(j) count+=1", "'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode)", "y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g = 6 if atitle ==", "resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6 def", "20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20,", "y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14,", "label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if", "tmpRes4 = [] tmpRes5 = [] tmpRes6 = [] tmpRes7 = [] tmpRes8", "2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20,", "'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S',", "'-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(),", "marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)',", "'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode)", "'Gmeanratio': if MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline", "'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S',", "[] if num == 40: readyres = [[] for i in range(6)] elif", "MST, btype = 'N', mode = 'REP'): init() typ.replace(\"'\", '') if MST ==", "[] x17 = [] y17 = [] resTotal1 = [] resTotal2 = []", "y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker =", "fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName", "resTotal11 = [] resTotal12 = [] resTotal13 = [] resTotal14 = [] resTotal15", "0) # Now assume all the results are for Limited-preemptive scheduling so #", "'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio',", "0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s,", "< 0: continue elif baseline >= i : if i/baseline <= 1: res.append(float(i)/float(baseline))", "wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean,", "30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30,", "2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10,", "2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio,", "import matplotlib.pyplot as plt import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import", "#wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio,", "#wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio,", "1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1)", "else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g", "linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\",", "getResPerUtili(resTotal11,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline ==", "'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10,", "0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s,", "'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') #", "100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP':", "max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g = 6 if atitle ==", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y17.append(way(i, num)) else:", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio,", "= [[] for i in range(6)] elif num == 30: readyres = [[]", "wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now assume all the results are", "marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)',", "0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s,", "40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L')", "100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName =", "y2 = [] x3 = [] y3 = [] x4 = [] y4", "'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline", "y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker =", "1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1)", "or len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode =", "[] y16 = [] x17 = [] y17 = [] resTotal1 = []", "utili = fileInput(target, g, s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i)", "wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean,", "x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker", "'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M',", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0)", "[] x4 = [] y4 = [] x5 = [] y5 = []", "2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20,", "= 6 CTbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST", "100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100,", "2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10,", "num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for", "'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M',", "= [] tmpRes10 = [] tmpRes11 = [] tmpRes12 = [] tmpRes13 =", "40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2,", "= marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0)", "elif mode == 'ILP': if num < 30: ax.plot( x1, y1, '-', marker", "[] resTotal17 = [] def init(): global x1, x2, x3, x4, x5, x6,", "import gmean x1 = [] y1 = [] x2 = [] y2 =", "x10 = [] y10 = [] x11 = [] y11 = [] x12", "ind, i in enumerate(res): #each file #print \"\" #print i #print len(i) tmp", "= [[] for i in range(7)] else: readyres = [[] for i in", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')'", "atitle == 'Gmeanratio': if MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline ))", "wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean,", "[] y13 = [] x14 = [] y14 = [] x15 = []", "1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1)", "btype = 'N', mode = 'REP'): init() typ.replace(\"'\", '') if MST == 3:", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio,", "def Gmeanratio(results, baseline): res = [] if baseline == 0: return 1 for", "return 1 return np.mean(res) def Gmeanratio(results, baseline): res = [] if baseline ==", "0 for ind, i in enumerate(res): #each file #print \"\" #print i #print", "i in getResPerUtili(resTotal15,s, num): #when g = 6 if atitle == 'Ameanratio' or", "y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num):", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y10.append(way(i, num)) else: y10.append(way(i,", "#print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline =", "g, s) for i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i)", "wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean,", "wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean,", "resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6 def getResPerUtili(res, numinSets,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y15.append(way(i, num)) else: y15.append(way(i,", "i in getResPerUtili(resTotal12,s, num): #when g = 6 if atitle == 'Ameanratio' or", "x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker", "Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g = 6", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i))", "'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if", "40: readyres = [[] for i in range(6)] elif num == 30: readyres", "ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-',", "40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40,", "'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode)", "#Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10,", "'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L',", "else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g = 6 if atitle", "get Arithmetic mean and Gmean if 0 <count < s*2: if count%2==1: strline", "marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo',", "'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M',", "[] resTotal4 = [] resTotal5 = [] resTotal6 = [] resTotal7 = []", "'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M',", "atitle == 'Gmeanratio': if MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline ))", "y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g =", "#ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0,", "linewidth=2.0) #ax.plot( x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3,", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both',", "100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100,", "resTotal15, resTotal16, resTotal17 x1 = [] y1 = [] x2 = [] y2", "= marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0)", "'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean',", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y16.append(way(i, num))", "marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot(", "'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode)", "else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s,", "num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when", "linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)',", "'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2,", "math import sys import numpy as np import matplotlib.pyplot as plt import itertools", "= [] x8 = [] y8 = [] x9 = [] y9 =", "''' count = -1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4)", "'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2,", "1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1)", "MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot", "if 0 <count < s*2: if count%2==1: strline = line.replace('[','') strline = strline.replace(']','')", "x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot(", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100,", "'Gmeanratio': if MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i))", "if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST", "#TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit", "for i in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if atitle ==", "'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L',", "mode == 'REP': if num < 30: ax.plot( x4, y4, '-', marker =", "import PdfPages from scipy.stats.mstats import gmean x1 = [] y1 = [] x2", "res = [] if baseline ==0: return 1 for i in results: if", "30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L')", "ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-',", "0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0)", "10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10,", "else: readyres = [[] for i in range(8)] count = 0 for ind,", "[] y12 = [] x13 = [] y13 = [] x14 = []", "Gmeanratio(results, baseline): res = [] if baseline == 0: return 1 for i", "y17.append(way(i)) # plot in pdf pp = PdfPages(folder + fileName + '.pdf') if", "getResPerUtili(resTotal12,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100,", "0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in pdf", "#wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2,", "2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio,", "1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') ''' if __name__ ==", "10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio',", "strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock,", "if MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for", "'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "1 def main(): args = sys.argv if len(args) < 1 or len(args) >", "[] tmpRes13 = [] tmpRes14 = [] tmpRes15 = [] tmpRes16 = []", "#CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line", "#when g = 6 Inflation if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "x17 = [] y17 = [] resTotal1 = [] resTotal2 = [] resTotal3", "'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L',", "marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)',", "2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40,", "label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16,", "== 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in", "import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import", "[] resTotal1 = [] resTotal2 = [] resTotal3 = [] resTotal4 = []", "tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num):", "range(7)] else: readyres = [[] for i in range(8)] count = 0 for", "x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i)", "len(results) == 0: return 1 return np.mean(res) def Gmeanratio(results, baseline): res = []", "i in getResPerUtili(resTotal8,s, num): #when g = 6 if atitle == 'Ameanratio' or", "= itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST == 0: if mode", "100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100,", "# wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13)", "< 30: ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2,", "ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-',", "resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks 10 an 20 utililist =", "= marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0)", "'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean',", "= [] tmpRes8 = [] tmpRes9 = [] tmpRes10 = [] tmpRes11 =", "'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode)", "ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP':", "'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L',", "'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean',", "0: continue elif baseline >= i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else:", "'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8,", "wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean,", "100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100,", "'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio',", "== 'ILP': if num < 30: ax.plot( x1, y1, '-', marker = marker.next(),", "'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S',", "20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20,", "y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker =", "[] y2 = [] x3 = [] y3 = [] x4 = []", "resTotal12 = [] resTotal13 = [] resTotal14 = [] resTotal15 = [] resTotal16", "20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2,", "import matplotlib.patches as mpatches import random import math import sys import numpy as", "resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14,", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y4.append(way(i, num))", "enumerate(res): #each file #print \"\" #print i #print len(i) tmp = [] icount", "tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13]))", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M',", "x7 = [] y7 = [] x8 = [] y8 = [] x9", "x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16,", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode == 'ILP': title =", "x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17 global y1,", "'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S',", "atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0:", "res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) == 0: return 1 return gmean(res)", "Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if", "#print len(i) tmp = [] icount = 0 for j in i: #every", "y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker =", "\"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this, 6 sets", "marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot(", "else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g", "== 2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit'", "strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation,", "y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker =", "return -1 mode = args[1] #after this, 6 sets of methods are prepared", "f1 = open(var1+\".txt\", 'r') count = -1 flag = 0 tmpRes1 = []", "#after this, 6 sets of methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S',", "PdfPages(folder + fileName + '.pdf') if btype != 'N': atitle = \"Limited-\"+atitle title", "2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20,", "folder = 'plots/' g = 1 def main(): args = sys.argv if len(args)", "num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when", "if MST == 1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title", "= marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7, y7, '-',", "100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100,", "#print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i", "1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1)", "= max(y7) tmpy7 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15,", "1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1)", "x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker", "'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L',", "marker.next(), label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0)", "[] x12 = [] y12 = [] x13 = [] y13 = []", "100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode)", "x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best", "num): #when g = 6 ILPbaseline if atitle == 'Ameanratio' or atitle ==", "x8, x9, x10, x11, x12, x13, x14, x15, x16, x17 global y1, y2,", "if MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) #", "x12 = [] y12 = [] x13 = [] y13 = [] x14", "ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST", "'-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(),", "pp.close() folder = 'plots/' g = 1 def main(): args = sys.argv if", "2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40,", "10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2,", "[] x7 = [] y7 = [] x8 = [] y8 = []", "0 count = 0 for i in readyres: utililist.append(i) return utililist def Ameanratio(results,", "2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40,", "i == 0: res.append(1) elif i < 0: continue elif baseline >= i", "linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10,", "y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num):", "[] y15 = [] x16 = [] y16 = [] x17 = []", "= [] resTotal5 = [] resTotal6 = [] resTotal7 = [] resTotal8 =", "else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g = 6 if atitle", "'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return 1 return np.mean(res) def Gmeanratio(results,", "if count == s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','')", "marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot(", "y8, y9, y10, y11, y12, y13, y14, y15, y16, y17 global resTotal1, resTotal2,", "== 'Gmeanratio': if MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else:", "scheduling so # of arguments is 6. def wayofMean(way, num, atitle, typ, s,", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle == 'Amean':", "marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot(", "y8 = [] x9 = [] y9 = [] x10 = [] y10", "Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio':", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)',", "Mbaseline = max(y13) tmpy13 = [] if atitle == 'Ameanratio' or atitle ==", "-1 flag = 0 tmpRes1 = [] tmpRes2 = [] tmpRes3 = []", "30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30,", "30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30,", "TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock", "y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker =", "10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10,", "wayofMean(np.mean, 10, 'Amean', 'S', 100, 1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean,", "prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/'", "#TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix", "'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S')", "x9 = [] y9 = [] x10 = [] y10 = [] x11", "count = 0 for i in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline):", "results are for Limited-preemptive scheduling so # of arguments is 6. def wayofMean(way,", "'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "elif mode == 'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0)", "or atitle == 'Gmeanratio': if MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0))", "wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio", "in getResPerUtili(resTotal1,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "'Gmeanratio': if MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i))", "= 'REP'): init() typ.replace(\"'\", '') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif", "6 if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0:", "y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g =", "readyres = [[] for i in range(8)] count = 0 for ind, i", "6 Inflation if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST ==", "for i in getResPerUtili(resTotal12,s, num): #when g = 6 if atitle == 'Ameanratio'", "#way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle ==", "'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean',", "marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)',", "0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0)", "#every numinSets input for each utilization tmp.append(j) count+=1 #print icount if count >", "so # of arguments is 6. def wayofMean(way, num, atitle, typ, s, MST,", "#Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30,", "'Gmeanratio': if MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline", "30, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30,", "TDAbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0:", "num): #when g = 6 TDAbaseline if atitle == 'Ameanratio' or atitle ==", "100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100,", "for j in i: #every numinSets input for each utilization tmp.append(j) count+=1 #print", "= 0 for j in i: #every numinSets input for each utilization tmp.append(j)", "'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M',", "= [] if baseline == 0: return 1 for i in results: if", "i in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if atitle == 'Ameanratio'", "2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20,", "mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g =", "y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if atitle", "i in getResPerUtili(resTotal10,s, num): #when g = 6 if atitle == 'Ameanratio' or", "else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y11.append(way(i, num))", "in getResPerUtili(resTotal14,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "x6 = [] y6 = [] x7 = [] y7 = [] x8", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y4.append(way(i, num)) else:", "== 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline", "[] resTotal13 = [] resTotal14 = [] resTotal15 = [] resTotal16 = []", "'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean',", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100,", "else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if atitle == 'Ameanratio' or", "in getResPerUtili(resTotal10,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2,", "= [] resTotal11 = [] resTotal12 = [] resTotal13 = [] resTotal14 =", "tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print", "i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results)", "ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-',", "100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S',", "1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2)", "y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if atitle == 'Ameanratio' or atitle", "marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-',", "[] x9 = [] y9 = [] x10 = [] y10 = []", "= line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x]", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot()", "'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean',", "'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20,", "'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio',", "wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 1)", "in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13) for i", "100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100,", "#strline[x] x = 0-16 y1.append(float(strline[0])) ''' count = -1 continue count += 1", "target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target =", "else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if atitle == 'Ameanratio' or", "Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g = 6", "100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100,", "resTotal17 = [] def init(): global x1, x2, x3, x4, x5, x6, x7,", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100,", "== 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in", "i in results: if i == 0: res.append(1) elif baseline >= i :", "'L', 100, 0) wayofMean(np.mean, 30, 'Amean', 'S', 100, 0) wayofMean(gmean, 30, 'Gmean', 'S',", "CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline", "2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40,", "= [] y14 = [] x15 = [] y15 = [] x16 =", "MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i", "wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio,", "marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif", "y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6, y6, '-', marker =", "ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT':", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y9.append(way(i, num)) else: y9.append(way(i,", "40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2,", "y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if atitle == 'Ameanratio' or atitle", "30: readyres = [[] for i in range(7)] else: readyres = [[] for", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode == 'ILP':", "100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode)", "'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S',", "numinSets input for each utilization tmp.append(j) count+=1 #print icount if count > numinSets-1:", "#print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0", "1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s)", "num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when", "strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count = -1 continue", "readyres = [[] for i in range(7)] else: readyres = [[] for i", "= 0 utililist = [] flag = 0 while fileidx < group: tmpUtil", "(%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST ==", "wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean,", "10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10,", "'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S',", "= [] y2 = [] x3 = [] y3 = [] x4 =", "'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio',", "10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20,", "resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 =", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y1.append(way(i,", "getResPerUtili(resTotal10,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "return 1 for i in results: if i == 0: res.append(1) elif i", "100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100,", "'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "x8 = [] y8 = [] x9 = [] y9 = [] x10", "'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10,", "= [] y9 = [] x10 = [] y10 = [] x11 =", "if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if num", "size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf()", "resTotal6 = [] resTotal7 = [] resTotal8 = [] resTotal9 = [] resTotal10", "'r') count = -1 flag = 0 tmpRes1 = [] tmpRes2 = []", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y5.append(way(i, num)) else:", "= [] resTotal1 = [] resTotal2 = [] resTotal3 = [] resTotal4 =", "'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L',", "'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') '''", "(icount+1)%7 else: icount = (icount+1)%8 icount = 0 count = 0 for i", "'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M',", "for i in results: if i == 0: res.append(1) elif baseline >= i", "'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M',", "100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean if 0 <count <", "= max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g = 6 if atitle", "30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40,", "2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio,", "20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20,", "#wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio,", "1) wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1)", "utililist.append(i) return utililist def Ameanratio(results, baseline): res = [] if baseline ==0: return", "MST == 0: #print i, num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i,", "MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for i", "MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y15.append(way(i, num)) else:", "ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-',", "'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio',", "2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target", "'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio',", "'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio,", "= marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0)", "40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40,", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100,", "pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12,", "'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio',", "TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1]))", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y17.append(way(i,", "x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17", "== 'REP': if num < 30: ax.plot( x4, y4, '-', marker = marker.next(),", "= [] x14 = [] y14 = [] x15 = [] y15 =", "100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100,", "ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization", "-1: #filename to get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to", "CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3]))", "1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio',", "atitle == 'Gmeanratio': if MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline ))", "atitle == 'Gmeanratio': if MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline ))", "getResPerUtili(resTotal6,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline',", "Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g = 6", "wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean,", "linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode ==", "in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if atitle == 'Ameanratio' or", "'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode)", "100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "for i in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if atitle ==", "else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode == 'ILP': title", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else:", "scipy.stats.mstats import gmean x1 = [] y1 = [] x2 = [] y2", "init(): global x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11,", "s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','')", "utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i)", "0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0)", "1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1)", "== 'Gmeanratio': if MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else:", "matplotlib.patches as mpatches import random import math import sys import numpy as np", "[] if baseline ==0: return 1 for i in results: if i ==", "'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean',", "'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M',", "y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if atitle == 'Ameanratio' or atitle", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M',", "'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio,", "marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)',", "resTotal16 = [] resTotal17 = [] def init(): global x1, x2, x3, x4,", "marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot(", "'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode)", "y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g =", "atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0:", "or atitle == 'Gmeanratio': if MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline", "'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30,", "x4 = [] y4 = [] x5 = [] y5 = [] x6", "'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode)", "for i in getResPerUtili(resTotal11,s, num): #when g = 6 if atitle == 'Ameanratio'", "'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean,", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2,", "matplotlib.use('Agg') import matplotlib.patches as mpatches import random import math import sys import numpy", "= max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g = 6 if atitle", "'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean',", "'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1)", "'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean',", "'-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(),", "'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y8.append(way(i, num))", "'Gmean', 'S', 100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean',", "''' #print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline", "num == 30: icount = (icount+1)%7 else: icount = (icount+1)%8 icount = 0", "'-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(),", "num == 40: icount = (icount+1)%6 elif num == 30: icount = (icount+1)%7", "count = -1 flag = 0 tmpRes1 = [] tmpRes2 = [] tmpRes3", "MST == 3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title =", "+ fileName + '.pdf') if btype != 'N': atitle = \"Limited-\"+atitle title =", "== 'Gmeanratio': if MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline )) else:", "40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean,", "else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g = 6 if atitle", "mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio',", "itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST == 0: if mode ==", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y7.append(way(i, num)) else:", "i in range(8)] count = 0 for ind, i in enumerate(res): #each file", "x15, x16, x17 global y1, y2, y3, y4, y5, y6, y7, y8, y9,", "in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if atitle == 'Ameanratio' or", "marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot(", "num): #when g = 6 if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "utililist def Ameanratio(results, baseline): res = [] if baseline ==0: return 1 for", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1,", "y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g =", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y2.append(way(i, num)) else: y2.append(way(i,", "'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean',", "x2, y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker", "'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean',", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100,", "10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S')", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio,", "resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil)", "== 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if", "g = 6 ILPbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if", "== 1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit'", "== 'Gmeanratio': if MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else:", "[] resTotal2 = [] resTotal3 = [] resTotal4 = [] resTotal5 = []", "mean and Gmean if 0 <count < s*2: if count%2==1: strline = line.replace('[','')", "TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry, CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit", "'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S',", "[] resTotal7 = [] resTotal8 = [] resTotal9 = [] resTotal10 = []", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20)", "= marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0)", "marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35,", "'-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1,", "[] resTotal14 = [] resTotal15 = [] resTotal16 = [] resTotal17 = []", "x16, x17 global y1, y2, y3, y4, y5, y6, y7, y8, y9, y10,", "marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)',", "'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "[] y8 = [] x9 = [] y9 = [] x10 = []", "marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot(", "marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot(", "size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized", "== 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in", "marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot(", "if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20)", "30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30,", "atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D',", "40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40,", "y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker =", "len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1]", "resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1", "elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return", "[] y14 = [] x15 = [] y15 = [] x16 = []", "'N', mode = 'REP'): init() typ.replace(\"'\", '') if MST == 3: target =", "or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline ==", ")) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g = 6 if", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y8.append(way(i, num)) else:", "20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1,", "== 'Gmeanratio': if MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else:", "== 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8,", "0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g = 6", "'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean', 'S',", "100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio,", "MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName", "'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio',", "wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean,", "'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100,", "2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20,", "linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17,", "s*2: if count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline", "else: y1.append(way(i)) for i in getResPerUtili(resTotal2,s, num): #when g = 6 if atitle", "20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S')", "= strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x = 0-16", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "for i in getResPerUtili(resTotal9,s, num): #when g = 6 if atitle == 'Ameanratio'", "or atitle == 'Gmeanratio': if MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline", "'ILP': if num < 30: ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry',", "= 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST ==", "x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker", "= [] x4 = [] y4 = [] x5 = [] y5 =", "marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)',", "==0: return 1 for i in results: if i == 0: res.append(1) elif", "or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4)", "Mbaseline )) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g = 6", "is 6. def wayofMean(way, num, atitle, typ, s, MST, btype = 'N', mode", "MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i", "or atitle == 'Gmeanratio': if MST == 0: y7.append(way(i, num)) else: y7.append(way(i, 0))", "atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for", "= [] x10 = [] y10 = [] x11 = [] y11 =", "'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L',", "#CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: '''", "'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S',", "= max(y4) tmpy4 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode", "100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode)", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode", "2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100,", "'d', 'o', 's', 'v')) try: if MST == 0: if mode == 'REP':", "linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode ==", "from scipy.stats.mstats import gmean x1 = [] y1 = [] x2 = []", "'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean',", "CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5]))", "atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric", "'.pdf') if btype != 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST", "'-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(),", "resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print", "linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13,", "'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode)", ")) else: y6.append(way(i)) for i in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline", "if Mbaseline == 0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when", "y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11,", "assume all the results are for Limited-preemptive scheduling so # of arguments is", "mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i", "'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S', mode)", "== 40: icount = (icount+1)%6 elif num == 30: icount = (icount+1)%7 else:", "0: y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 =", "6. def wayofMean(way, num, atitle, typ, s, MST, btype = 'N', mode =", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y16.append(way(i,", "10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10,", "'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio',", "'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode)", "'s', 'v')) try: if MST == 0: if mode == 'REP': if num", "'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L',", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M',", "0: return 1 return np.mean(res) def Gmeanratio(results, baseline): res = [] if baseline", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M',", "marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)',", "in pdf pp = PdfPages(folder + fileName + '.pdf') if btype != 'N':", "resTotal5 = [] resTotal6 = [] resTotal7 = [] resTotal8 = [] resTotal9", "30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2,", "1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio,", "mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True)", "'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') #", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y2.append(way(i, num)) else:", "marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)',", "num): #work for tasks 10 an 20 utililist = [] if num ==", "'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L',", "x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker", "'Gmeanratio': if MST == 0: y9.append(way(i, num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i))", "Limited-preemptive scheduling so # of arguments is 6. def wayofMean(way, num, atitle, typ,", "python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this, 6 sets of", "30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y11.append(way(i,", "10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'L')", "matplotlib.pyplot as plt import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages", "20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20,", "= [] x7 = [] y7 = [] x8 = [] y8 =", "x9, x10, x11, x12, x13, x14, x15, x16, x17 global y1, y2, y3,", "numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if num == 40: icount", "readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res = [] if baseline ==0:", "30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2,", "= (icount+1)%6 elif num == 30: icount = (icount+1)%7 else: icount = (icount+1)%8", "Arithmetic mean and Gmean if 0 <count < s*2: if count%2==1: strline =", "'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio,", "res.append(1) elif i < 0: continue elif baseline >= i : if i/baseline", "marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot(", "100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100,", "else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y3.append(way(i, num)) else:", "40, 'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "'-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num <", "[] y9 = [] x10 = [] y10 = [] x11 = []", "'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "[] icount = 0 for j in i: #every numinSets input for each", "marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)',", "MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName", "x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST", "'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean', 'S', 100, 1) wayofMean(gmean, 30, 'Gmean',", "continue elif baseline >= i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1)", "= args[1] #after this, 6 sets of methods are prepared ''' wayofMean(np.mean, 10,", "= [] tmpRes15 = [] tmpRes16 = [] tmpRes17 = [] for line", "[] resTotal3 = [] resTotal4 = [] resTotal5 = [] resTotal6 = []", "linewidth=2.0) else: if mode == 'REP': if num < 30: ax.plot( x4, y4,", ")) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g = 6 if", "'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if", "== 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd',", "100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100,", "= strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x =", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: #print i,", "mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M',", "or atitle == 'Gmeanratio': if MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline", "resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1 =", "# wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now assume all the results", "import matplotlib matplotlib.use('Agg') import matplotlib.patches as mpatches import random import math import sys", "y1.append(float(strline[0])) ''' count = -1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3)", "0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0)", "100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100,", "typ.replace(\"'\", '') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2:", "= 0 if num == 40: icount = (icount+1)%6 elif num == 30:", "x5 = [] y5 = [] x6 = [] y6 = [] x7", "= [] y4 = [] x5 = [] y5 = [] x6 =", "'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean',", "30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30,", ": res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return 1 return np.mean(res) def", "'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio',", "strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count", "'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10,", "'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',')", "== 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in", "[] resTotal6 = [] resTotal7 = [] resTotal8 = [] resTotal9 = []", "target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g, s) for i in utili[0]: x1.append(i)", "= [] y15 = [] x16 = [] y16 = [] x17 =", "= 0 for i in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res", "or atitle == 'Gmeanratio': if MST == 0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline", "x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2, '-', marker", "100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100,", "1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "getResPerUtili(resTotal14,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "= atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num): #when", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif MST == 2: if mode == 'ILP': title =", "40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2,", "2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100,", "'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio',", "tmp = [] count = 0 if num == 40: icount = (icount+1)%6", "label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif", "20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20,", "marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if num < 30: ax.plot( x1,", "1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40, 'Amean', 'L', 100, 1)", "10, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 10,", "if len(results) == 0: return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S',", "'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10,", "0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s,", "20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L')", "[] y6 = [] x7 = [] y7 = [] x8 = []", "10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 10,", "main(): args = sys.argv if len(args) < 1 or len(args) > 2: print", "40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio,", "except ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes,", "= strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count = -1", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y8.append(way(i, num)) else: y8.append(way(i,", "100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "#ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock", "[] resTotal16 = [] resTotal17 = [] def fileInput(var1, group, s): fileidx =", "gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now assume all the", "num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if", "< 30: ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x6,", "10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20,", "'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio',", "size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v')) try: if MST == 0:", "strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x", "3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title,", "'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40, 'Amean',", "size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close()", "in getResPerUtili(resTotal17,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else:", "30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40,", "100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean',", "wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio", "x15 = [] y15 = [] x16 = [] y16 = [] x17", "resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17", "= [] resTotal15 = [] resTotal16 = [] resTotal17 = [] def init():", "'-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(),", "10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20,", "num == 40: readyres = [[] for i in range(6)] elif num ==", "i : res.append(float(i)/float(baseline)) else: res.append(1) if len(results) == 0: return 1 return np.mean(res)", "== 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i in", "'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10,", "= [] tmpRes11 = [] tmpRes12 = [] tmpRes13 = [] tmpRes14 =", "Mbaseline == 0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g", "[] tmpRes7 = [] tmpRes8 = [] tmpRes9 = [] tmpRes10 = []", "plot in pdf pp = PdfPages(folder + fileName + '.pdf') if btype !=", "'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean',", "#wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio,", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "= [] tmpRes13 = [] tmpRes14 = [] tmpRes15 = [] tmpRes16 =", "Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g = 6 if", "and Gmean if 0 <count < s*2: if count%2==1: strline = line.replace('[','') strline", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y12.append(way(i, num)) else:", "0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14})", "10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 30,", "0 while fileidx < group: tmpUtil = [] f1 = open(var1+\".txt\", 'r') count", "marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)',", "1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "== 0: return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0)", "10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2,", "[] resTotal9 = [] resTotal10 = [] resTotal11 = [] resTotal12 = []", "if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) == 0:", "pass elif mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)',", "'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio,", "30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'L')", "40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40,", "'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L',", "marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)',", "= marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if num < 30:", "marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot(", "#work for tasks 10 an 20 utililist = [] if num == 40:", "or atitle == 'Gmeanratio': if MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0))", "100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "in f1: if count == -1: #filename to get utilization: filename = line.split('_')", "linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17,", "100, 1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100,", "baseline ==0: return 1 for i in results: if i == 0: res.append(1)", "!= 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if", "'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "[] tmpRes2 = [] tmpRes3 = [] tmpRes4 = [] tmpRes5 = []", "#wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio,", "fileidx = 0 utililist = [] flag = 0 while fileidx < group:", "s): fileidx = 0 utililist = [] flag = 0 while fileidx <", "this, 6 sets of methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100,", "1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "Mbaseline = max(y7) tmpy7 = [] if atitle == 'Ameanratio' or atitle ==", "label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker = marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17,", "CTblock, CTjit, CTmix] #ILPcarry tmpRes1.append(int(strline[0])) #ILPblock tmpRes2.append(int(strline[1])) #ILPjit tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4]))", "0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig()", "'Amean', 'S', 100, 0) # Now assume all the results are for Limited-preemptive", "'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode)", "#worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0", "linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13,", "'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode)", "wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio,", "y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10,", "tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12]))", "0) wayofMean(gmean, 30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0)", "resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1 = [] x2", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y1.append(way(i, num))", "tmpRes11 = [] tmpRes12 = [] tmpRes13 = [] tmpRes14 = [] tmpRes15", "in results: if i == 0: res.append(1) elif i < 0: continue elif", "#when g = 6 CTbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13) for", "100, 0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100,", "'S', 100, 1) wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M',", "'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2,", "= atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)',", "for i in getResPerUtili(resTotal1,s, num): #when g = 6 if atitle == 'Ameanratio'", "y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17 global", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2,", "20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30,", "utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and", "for ind, i in enumerate(res): #each file #print \"\" #print i #print len(i)", "Mbaseline == 0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g", "'-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(),", "resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1", "resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16)", "30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30,", "'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 20, 'Amean', 'L',", "numinSets, num): #work for tasks 10 an 20 utililist = [] if num", "if count == -1: #filename to get utilization: filename = line.split('_') #print filename", "i in getResPerUtili(resTotal11,s, num): #when g = 6 if atitle == 'Ameanratio' or", "in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res = [] if baseline", "'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean',", "ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-',", "g = 6 Inflation if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if", "num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if", "== 0: if mode == 'REP': if num < 30: ax.plot( x4, y4,", "transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16", "= plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g =", "[] x14 = [] y14 = [] x15 = [] y15 = []", "== 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\",", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100,", "'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M',", "MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for i", "of arguments is 6. def wayofMean(way, num, atitle, typ, s, MST, btype =", "label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10,", "0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0)", "= [] resTotal4 = [] resTotal5 = [] resTotal6 = [] resTotal7 =", "#best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else:", "or atitle == 'Gmeanratio': if MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline", "[] tmpRes12 = [] tmpRes13 = [] tmpRes14 = [] tmpRes15 = []", "num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if", "mode = args[1] #after this, 6 sets of methods are prepared ''' wayofMean(np.mean,", "ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-',", "100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "= [] tmpRes2 = [] tmpRes3 = [] tmpRes4 = [] tmpRes5 =", "np.mean(res) def Gmeanratio(results, baseline): res = [] if baseline == 0: return 1", "label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15,", "y9 = [] x10 = [] y10 = [] x11 = [] y11", "ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-',", "wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y13.append(way(i,", "strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry,", "= marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0)", "0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0)", "10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio',", "0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if atitle == 'Ameanratio'", "def wayofMean(way, num, atitle, typ, s, MST, btype = 'N', mode = 'REP'):", "num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when", "args[1] #after this, 6 sets of methods are prepared ''' wayofMean(np.mean, 10, 'Amean',", "100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M',", "or atitle == 'Gmeanratio': if MST == 0: #print i, num #print way(i,", "100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100,", "'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "== 0: #print i, num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline", "'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30,", "[] tmpRes6 = [] tmpRes7 = [] tmpRes8 = [] tmpRes9 = []", "tmpRes10 = [] tmpRes11 = [] tmpRes12 = [] tmpRes13 = [] tmpRes14", "0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0)", "resTotal17 x1 = [] y1 = [] x2 = [] y2 = []", "import math import sys import numpy as np import matplotlib.pyplot as plt import", "== 0: Mbaseline = max(tmpy7) for i in getResPerUtili(resTotal8,s, num): #when g =", "40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 40,", "y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker =", "100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean', 'L', 100,", "= 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock,", "strline.split(',') #prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA,", "1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1)", "'M', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L',", "wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean,", "marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if num < 30: ax.plot(", "label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10,", "sets of methods are prepared ''' wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) wayofMean(gmean,", "if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST", "label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12,", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio,", "20, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100,", "else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g", "ValueError: print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16", "x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17 global", "= [] tmpRes14 = [] tmpRes15 = [] tmpRes16 = [] tmpRes17 =", "'-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(),", "'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode)", "count == -1: #filename to get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1]))", "100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100,", "if len(results) == 0: return 1 return np.mean(res) def Gmeanratio(results, baseline): res =", "'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40,", "all the results are for Limited-preemptive scheduling so # of arguments is 6.", "num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when", "'-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(),", "strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x = 0-16", "# wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10,", "= strline.replace('\\n','') strline = strline.split(',') print strline #strline[x] x = 0-16 y1.append(float(strline[0])) '''", "in results: if i == 0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline))", "x13, x14, x15, x16, x17 global y1, y2, y3, y4, y5, y6, y7,", "= marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0)", ">= i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if", "'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 20, 'Amean',", "flag = 0 tmpRes1 = [] tmpRes2 = [] tmpRes3 = [] tmpRes4", "10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20,", "'S', 100, 0) wayofMean(gmean, 10, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M',", "y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker =", "#wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) '''", "'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode)", "'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio,", "'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'M',", "size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker", "30: ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot( x2, y2,", "= marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0)", "= [] resTotal7 = [] resTotal8 = [] resTotal9 = [] resTotal10 =", "itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean", "0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0)", "'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio',", "'-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(),", "'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean',", "print strline #strline[x] x = 0-16 y1.append(float(strline[0])) ''' count = -1 continue count", ")) else: y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g = 6 if", "wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean,", "mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1", "MST == 1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName =", "'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M',", "getResPerUtili(resTotal16,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "#print i, num #print way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else:", "for i in readyres: utililist.append(i) return utililist def Ameanratio(results, baseline): res = []", "'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "def main(): args = sys.argv if len(args) < 1 or len(args) > 2:", "title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax =", "y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g = 6 if atitle ==", "if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\",", "= [] def init(): global x1, x2, x3, x4, x5, x6, x7, x8,", "'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20,", "i in range(6)] elif num == 30: readyres = [[] for i in", "#wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio,", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y3.append(way(i, num))", "100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio,", "[] x11 = [] y11 = [] x12 = [] y12 = []", "= [] resTotal17 = [] def fileInput(var1, group, s): fileidx = 0 utililist", "atitle == 'Gmeanratio': if MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline ))", "elif mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0)", "'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40,", "= marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9, '-', marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0)", "'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S')", "1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1)", "100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100,", "20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100,", "[] y11 = [] x12 = [] y12 = [] x13 = []", "marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)',", "100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S',", "wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y7.append(way(i,", "40, 'Amean', 'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio,", "tmpRes3.append(int(strline[2])) #Inflation tmpRes4.append(int(strline[3])) #ILPbaseline tmpRes5.append(int(strline[4])) #Combo tmpRes6.append(int(strline[5])) #TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8]))", "i in getResPerUtili(resTotal9,s, num): #when g = 6 if atitle == 'Ameanratio' or", "100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100,", "tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num):", "'Gmeanratio': if MST == 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i))", "icount = (icount+1)%6 elif num == 30: icount = (icount+1)%7 else: icount =", "== 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif", "#print i #print len(i) tmp = [] icount = 0 for j in", "linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12,", "'S', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'M',", "plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20)", "j in i: #every numinSets input for each utilization tmp.append(j) count+=1 #print icount", "x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i)", "getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7) for i in", "'-', marker = marker.next(), label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(),", "marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot(", "== 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric", "'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S',", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal13,s, num):", "100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode) '''", "i in getResPerUtili(resTotal2,s, num): #when g = 6 if atitle == 'Ameanratio' or", "'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4, resTotal5, resTotal6, resTotal7, resTotal8,", "if baseline ==0: return 1 for i in results: if i == 0:", "len(results) == 0: return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100,", "= [] resTotal15 = [] resTotal16 = [] resTotal17 = [] def fileInput(var1,", "'Gmeanratio': if MST == 0: y17.append(way(i, num)) else: y17.append(way(i, Mbaseline )) else: y17.append(way(i))", "linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9,", "'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode)", "'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L',", "y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-', marker =", "y16 = [] x17 = [] y17 = [] resTotal1 = [] resTotal2", "resTotal4, resTotal5, resTotal6, resTotal7, resTotal8, resTotal9, resTotal10, resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16,", "mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M',", "100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "1: fileName = 'First-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif", "elif num == 30: icount = (icount+1)%7 else: icount = (icount+1)%8 icount =", "max(y4) tmpy4 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for", "i in getResPerUtili(resTotal6,s, num): #when g = 6 if atitle == 'Ameanratio' or", "pass elif mode == 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)',", "range(6)] elif num == 30: readyres = [[] for i in range(7)] else:", "figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder = 'plots/' g", "marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif", "'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode)", "resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1 = [] x2 = []", "20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20,", "rcParams from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.mstats import gmean x1 = [] y1", "0) wayofMean(np.mean, 40, 'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0)", "0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0)", "transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\", transform=ax.transAxes, size=16 ) ax.legend(loc=0, prop={'size':14}) figure =", "readyres[icount]=readyres[icount]+tmp tmp = [] count = 0 if num == 40: icount =", "atitle, typ, s, MST, btype = 'N', mode = 'REP'): init() typ.replace(\"'\", '')", "resTotal11, resTotal12, resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1 = []", "else: y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in pdf pp = PdfPages(folder", "if baseline == 0: return 1 for i in results: if i ==", "resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist #print resTotal6 def getResPerUtili(res, numinSets, num):", "'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M',", "0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'M', 100, 0)", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100,", "marker = marker.next(), label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-BF-TDA(Jit)',", "ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-',", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7) for i", "1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio',", "if count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline =", "100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100,", "if i == 0: res.append(1) elif baseline >= i : res.append(float(i)/float(baseline)) else: res.append(1)", "tmpRes12 = [] tmpRes13 = [] tmpRes14 = [] tmpRes15 = [] tmpRes16", "= (icount+1)%7 else: icount = (icount+1)%8 icount = 0 count = 0 for", "num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s,", "return utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks 10 an", "'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40, 'Amean', 'L',", "else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = [] if atitle", "elif MST == 3: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title", "tmpRes5 = [] tmpRes6 = [] tmpRes7 = [] tmpRes8 = [] tmpRes9", "if MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for", "0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0)", "1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100, 1)", "y6 = [] x7 = [] y7 = [] x8 = [] y8", "x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y1.append(way(i, num)) else: y1.append(way(i,", "atitle == 'Gmeanratio': if MST == 0: #print i, num #print way(i, num)", "len(args) < 1 or len(args) > 2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return", "[] resTotal16 = [] resTotal17 = [] def init(): global x1, x2, x3,", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100,", "'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10,", "label='ILP-Combo', linewidth=2.0) pass ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot(", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y13.append(way(i, num)) else: y13.append(way(i,", "'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M',", "print \"ValueError\" #ax.vlines(0.5, 0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 )", "ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry, TDAblock, TDAjit, TDAjitblock, TDAmix, CTbaseline, CTcarry,", "'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if MST == 1: if mode", "else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g", "30, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100,", "0 if num == 40: icount = (icount+1)%6 elif num == 30: icount", "30, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2,", "[] tmpRes4 = [] tmpRes5 = [] tmpRes6 = [] tmpRes7 = []", "= marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0)", "< s*2: if count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','')", "mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M',", "MST == 0: y5.append(way(i, num)) else: y5.append(way(i, Mbaseline )) else: y5.append(way(i)) for i", "'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean, 10, 'Gmean', 'M',", "tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line strline", "100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100,", "= -1 flag = 0 tmpRes1 = [] tmpRes2 = [] tmpRes3 =", "== 0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in", "'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S',", "[] resTotal12 = [] resTotal13 = [] resTotal14 = [] resTotal15 = []", "num): #when g = 6 CTbaseline if atitle == 'Ameanratio' or atitle ==", "x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0) ax.plot( x4, y4, '-', marker", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y15.append(way(i, num))", "= [] tmpRes7 = [] tmpRes8 = [] tmpRes9 = [] tmpRes10 =", "resTotal13, resTotal14, resTotal15, resTotal16, resTotal17 x1 = [] y1 = [] x2 =", "'-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(),", "'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode)", "if MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for", "y11.append(way(i)) for i in getResPerUtili(resTotal12,s, num): #when g = 6 if atitle ==", "x17 global y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11,", "y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker =", "to get utilization: filename = line.split('_') #print filename tmpUtil.append(int(filename[1])) #Content to get Arithmetic", "30: icount = (icount+1)%7 else: icount = (icount+1)%8 icount = 0 count =", "ax.plot( x17, y17, '-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode ==", "10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 20, 'Gmeanratio',", "g = 6 if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST", "'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S',", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y15.append(way(i,", "40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y17.append(way(i, num)) else: y17.append(way(i,", "'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2, 'L',", "'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean',", "getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if atitle == 'Ameanratio' or atitle", "'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio',", "y17 = [] resTotal1 = [] resTotal2 = [] resTotal3 = [] resTotal4", "0) wayofMean(gmean, 10, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 10, 'Amean', 'L', 100, 0)", "i in getResPerUtili(resTotal7,s, num): #when g = 6 TDAbaseline if atitle == 'Ameanratio'", "if Mbaseline == 0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when", "20, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20,", "1: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-First-Fit' elif", "marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot(", "'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "40, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2,", "getResPerUtili(resTotal8,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "= [] y6 = [] x7 = [] y7 = [] x8 =", "ax.plot( x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-',", "y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g =", "resTotal15 = [] resTotal16 = [] resTotal17 = [] def init(): global x1,", "'M', 100, 0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L',", "fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print fileName Mbaseline = 0 for", "icount = 0 for j in i: #every numinSets input for each utilization", "== 0: res.append(1) elif i < 0: continue elif baseline >= i :", "'-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA': ax.plot( x7,", "label='PST-FF-TDA(Block)', linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11,", "[] for line in f1: if count == -1: #filename to get utilization:", "atitle == 'Gmeanratio': if MST == 0: y15.append(way(i, num)) else: y15.append(way(i, Mbaseline ))", "'-', marker = marker.next(), label='PST-FF-CT(Mixed)', linewidth=2.0) else: if mode == 'REP': if num", "x7, y7, '-', marker = marker.next(), label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x12, y12, '-', marker", "'M', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L',", "2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30,", "'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S',", "'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L',", "== 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: #print i, num", "= [] resTotal8 = [] resTotal9 = [] resTotal10 = [] resTotal11 =", "x16 = [] y16 = [] x17 = [] y17 = [] resTotal1", "mode = 'REP'): init() typ.replace(\"'\", '') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype", "ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-',", "if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target =", "ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle", "for i in getResPerUtili(resTotal16,s, num): #when g = 6 if atitle == 'Ameanratio'", "= PdfPages(folder + fileName + '.pdf') if btype != 'N': atitle = \"Limited-\"+atitle", "or atitle == 'Gmeanratio': if MST == 0: y6.append(way(i, num)) else: y6.append(way(i, Mbaseline", "in getResPerUtili(resTotal11,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100,", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio,", "= max(y13) tmpy13 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0)", "1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1)", "'L', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 20, 'Ameanratio', 'S',", "'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle", "resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx += 1 return utililist", "#TDAbaseline tmpRes7.append(int(strline[6])) #TDAcarry tmpRes8.append(int(strline[7])) #TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline", "y7.append(way(i, num)) else: y7.append(way(i, 0)) else: y7.append(way(i)) Mbaseline = max(y7) tmpy7 = []", "= line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') print strline", "[] flag = 0 while fileidx < group: tmpUtil = [] f1 =", "tmpUtil.append(int(filename[1])) #Content to get Arithmetic mean and Gmean if 0 <count < s*2:", "ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic", "utililist = [] flag = 0 while fileidx < group: tmpUtil = []", "100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio,", "= marker.next(), label='PST-BF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0)", "label='PST-BF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9,", "fileInput(var1, group, s): fileidx = 0 utililist = [] flag = 0 while", "20, 'Amean', 'S', 100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20,", "'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode)", "num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g =", "0: y11.append(way(i, num)) else: y11.append(way(i, Mbaseline )) else: y11.append(way(i)) for i in getResPerUtili(resTotal12,s,", "1) wayofMean(np.mean, 30, 'Amean', 'M', 100, 1) wayofMean(gmean, 30, 'Gmean', 'M', 100, 1)", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1,", "group: tmpUtil = [] f1 = open(var1+\".txt\", 'r') count = -1 flag =", "CTbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0:", "2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10,", "30, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 30, 'Amean', 'M', 100, 0) wayofMean(gmean, 30,", "else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3: if mode == 'ILP': title", "[] y17 = [] resTotal1 = [] resTotal2 = [] resTotal3 = []", "Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g = 6", "x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) elif mode == 'ILP': if", "20, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30,", "#wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio,", "== 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Best-Fit' elif MST == 3:", "0) wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 0)", "'Amean', 'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10,", "'Gmeanratio', 'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'S',", "label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100,", "which='major',labelsize=16) #way of means if atitle == 'Amean': ax.set_ylabel(\"Arithmetic Mean\", size=20) elif atitle", "= open(var1+\".txt\", 'r') count = -1 flag = 0 tmpRes1 = [] tmpRes2", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y9.append(way(i, num))", "30, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30,", "'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y5.append(way(i, num)) else: y5.append(way(i,", "gmean x1 = [] y1 = [] x2 = [] y2 = []", "#TDAblock tmpRes9.append(int(strline[8])) #TDAjit tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock", "'plots/' g = 1 def main(): args = sys.argv if len(args) < 1", "file #print \"\" #print i #print len(i) tmp = [] icount = 0", "20, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20,", "#wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 1) #wayofMean(Ameanratio,", "== 'TDA': ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8,", "args = sys.argv if len(args) < 1 or len(args) > 2: print \"Usage:", "else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num): #when g = 6 if atitle", "100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100,", "y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g = 6 if atitle ==", "10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 10,", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100,", "20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30,", "if num < 30: ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation', linewidth=2.0)", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y2.append(way(i,", "icount = (icount+1)%8 icount = 0 count = 0 for i in readyres:", "label='PST-BF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker = marker.next(), label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12,", "= [] for line in f1: if count == -1: #filename to get", "as plt import itertools from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages from", "100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100,", "elif baseline >= i : if i/baseline <= 1: res.append(float(i)/float(baseline)) else: res.append(1) else:", "resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7) resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15)", "40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40,", "in range(7)] else: readyres = [[] for i in range(8)] count = 0", "40, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2,", "i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7) for", "'L', 100, 1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio',", "ax.plot( x17, y17, '-', marker = marker.next(), label='PST-BF-CT(Mixed)', linewidth=2.0) except ValueError: print \"ValueError\"", "linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6,", "[] x5 = [] y5 = [] x6 = [] y6 = []", "[] x15 = [] y15 = [] x16 = [] y16 = []", "x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i) x12.append(i) x13.append(i) x14.append(i) x15.append(i) x16.append(i) x17.append(i) if MST", "linewidth=2.0) ax.plot( x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11,", "resTotal16 = [] resTotal17 = [] def fileInput(var1, group, s): fileidx = 0", "num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when", "'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 30, 'Amean',", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100,", "'REP'): init() typ.replace(\"'\", '') if MST == 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST", "30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2,", "40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 40,", "else: y13.append(way(i)) Mbaseline = max(y13) tmpy13 = [] if atitle == 'Ameanratio' or", "'Gmeanratio': for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline =", "'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio',", "== 30: icount = (icount+1)%7 else: icount = (icount+1)%8 icount = 0 count", "'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'S')", "atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')-Worst-Fit' plt.title(title, fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20)", "100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'S', mode)", "2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20,", "getResPerUtili(resTotal9,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "Geometric Mean\", size=20) ax.set_xlabel(\"Utilization (%)\", size=20) marker = itertools.cycle(('D', 'd', 'o', 's', 'v'))", "'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 10, 'Ameanratio',", "= 6 TDAbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST", "elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20) elif atitle == 'Gmeanratio': ax.set_ylabel(\"Normalized", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio,", "linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-BF-TDA(Carry)', linewidth=2.0) #ax.plot( x9, y9,", "'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S',", "== 0: Mbaseline = max(tmpy13) for i in getResPerUtili(resTotal14,s, num): #when g =", "0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 =", "30, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30,", "line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking #strline[x] x", "6 ILPbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST ==", "'Amean', 'L', 100, 0) wayofMean(gmean, 20, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 30, 'Amean',", "Mbaseline )) else: y10.append(way(i)) for i in getResPerUtili(resTotal11,s, num): #when g = 6", "0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0)", "100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio,", "wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean, 40, 'Gmean', 'S', 100, 0) wayofMean(np.mean,", "'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1) wayofMean(gmean, 20, 'Gmean', 'M',", "10, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2,", "0: y12.append(way(i, num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s,", "wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1,", "y14.append(way(i)) for i in getResPerUtili(resTotal15,s, num): #when g = 6 if atitle ==", "0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 20, 'Amean', 'S', 100, 0)", "0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 0)", "= 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName =", "i in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i)", "1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100, 1)", "10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio',", "if MST == 0: y13.append(way(i, num)) else: y13.append(way(i, 0)) else: y13.append(way(i)) Mbaseline =", "'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio',", "[] y4 = [] x5 = [] y5 = [] x6 = []", "'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio',", "'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean,", "return 1 return gmean(res) # wayofMean(np.mean, 10, 'Amean', 'S', 100, 0) # Now", "y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num):", "MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for i", "= [] y8 = [] x9 = [] y9 = [] x10 =", "getResPerUtili(resTotal17,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle ==", "else: res.append(1) if len(results) == 0: return 1 return gmean(res) # wayofMean(np.mean, 10,", "'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'L',", "in range(6)] elif num == 30: readyres = [[] for i in range(7)]", "'Gmeanratio': if MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else: y16.append(way(i))", "40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 40,", "'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 40,", "'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14,", "MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target,", "wayofMean(np.mean, 40, 'Amean', 'M', 100, 1) wayofMean(gmean, 40, 'Gmean', 'M', 100, 1) wayofMean(np.mean,", "40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40,", "max(y13) tmpy13 = [] if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for", "100, 0) wayofMean(gmean, 20, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100,", "100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100,", "+ '.pdf') if btype != 'N': atitle = \"Limited-\"+atitle title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' if", "y17.append(way(i, Mbaseline )) else: y17.append(way(i)) # plot in pdf pp = PdfPages(folder +", "= marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(), label='ILP-Jit', linewidth=2.0)", "40, 'Gmeanratio', 'S', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 2,", "1) wayofMean(gmean, 40, 'Gmean', 'L', 100, 1) #ratio #wayofMean(Ameanratio, 10, 'Ameanratio', 'S', 100,", "100, 0) wayofMean(np.mean, 20, 'Amean', 'M', 100, 0) wayofMean(gmean, 20, 'Gmean', 'M', 100,", "linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17,", "<count < s*2: if count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline =", "y8.append(way(i)) for i in getResPerUtili(resTotal9,s, num): #when g = 6 if atitle ==", "[] tmpRes9 = [] tmpRes10 = [] tmpRes11 = [] tmpRes12 = []", "'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 30,", "elif MST == 2: #best fileName = 'Best-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype elif MST == 3: #worst", "'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L',", "[] f1 = open(var1+\".txt\", 'r') count = -1 flag = 0 tmpRes1 =", "tmpRes7 = [] tmpRes8 = [] tmpRes9 = [] tmpRes10 = [] tmpRes11", "40, 'Gmean', 'S', 100, 0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40,", "MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else: y3.append(way(i)) for i", "'L', 100, 0) wayofMean(gmean, 40, 'Gmean', 'L', 100, 0) #ratio wayofMean(Ameanratio, 10, 'Ameanratio',", "label='PST-FF-TDA(Jitblock)', linewidth=2.0) ax.plot( x12, y12, '-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode", "1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L',", "num)) else: y12.append(way(i, Mbaseline )) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when", "tmpRes10.append(int(strline[9])) #TDAjitblock tmpRes11.append(int(strline[10])) #TDAmix tmpRes12.append(int(strline[11])) #CTbaseline tmpRes13.append(int(strline[12])) #CTbarry tmpRes14.append(int(strline[13])) #CTblock tmpRes15.append(int(strline[14])) #CTjit tmpRes16.append(int(strline[15]))", "10, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2,", "'-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(),", "2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L', mode) ''' #Limited-preemptive", "import random import math import sys import numpy as np import matplotlib.pyplot as", "#ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0) ax.plot( x16, y16, '-',", "= [] x15 = [] y15 = [] x16 = [] y16 =", "y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker =", "100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean', 'S',", "else: y4.append(way(i, 0)) else: y4.append(way(i)) Mbaseline = max(y4) tmpy4 = [] if atitle", "try: if MST == 0: if mode == 'REP': if num < 30:", "'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 3) #wayofMean(Ameanratio, 30, 'Ameanratio',", "in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if atitle == 'Ameanratio' or", "or atitle == 'Gmeanratio': if MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline", "= [] y1 = [] x2 = [] y2 = [] x3 =", "'Gmeanratio': for i in getResPerUtili(resTotal13,s, num): tmpy13.append(np.mean(i)) if Mbaseline == 0: Mbaseline =", "'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 2, 'L',", "#prechecking #strline[x] x = 0-16 #[ILPcarry, ILPblock, ILPjit, Inflation, ILPbaseline, Combo, TDA, TDAcarry,", "= 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1:", "'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'M',", "100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100,", "fontsize=20) plt.grid(True) #plt.ylabel('Geometric Mean', fontsize=20) #plt.xlabel('Approaches($U^*$)', fontsize=20) ax = plt.subplot() ax.tick_params(axis='both', which='major',labelsize=16) #way", "'M', 100, 1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L',", "== 30: readyres = [[] for i in range(7)] else: readyres = [[]", "#when g = 6 TDAbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio':", "'REP': if num < 30: ax.plot( x4, y4, '-', marker = marker.next(), label='ILP-Inflation',", "resTotal8.append(tmpRes8) resTotal9.append(tmpRes9) resTotal10.append(tmpRes10) resTotal11.append(tmpRes11) resTotal12.append(tmpRes12) resTotal13.append(tmpRes13) resTotal14.append(tmpRes14) resTotal15.append(tmpRes15) resTotal16.append(tmpRes16) resTotal17.append(tmpRes17) utililist.append(tmpUtil) fileidx +=", "y12, '-', marker = marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13,", "'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio',", "if MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i)) for", "'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L',", "in utili[0]: x1.append(i) x2.append(i) x3.append(i) x4.append(i) x5.append(i) x6.append(i) x7.append(i) x8.append(i) x9.append(i) x10.append(i) x11.append(i)", "1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1)", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y2.append(way(i, num))", "wayofMean(np.mean, 10, 'Amean', 'L', 100, 0) wayofMean(gmean, 10, 'Gmean', 'L', 100, 0) wayofMean(np.mean,", "atitle == 'Gmeanratio': if MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline ))", "marker.next(), label='ILP-Inflation', linewidth=2.0) ax.plot( x5, y5, '-', marker = marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot(", "strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',') #prechecking", "'Gmean', 'S', 100, 0) wayofMean(np.mean, 10, 'Amean', 'M', 100, 0) wayofMean(gmean, 10, 'Gmean',", "in getResPerUtili(resTotal15,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100,", "if MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else: y8.append(way(i)) for", "resTotal10 = [] resTotal11 = [] resTotal12 = [] resTotal13 = [] resTotal14", "= 6 ILPbaseline if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST", "0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 0)", "y2, '-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker =", "''' #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S',", "= marker.next(), label='ILP-Baseline', linewidth=2.0) ax.plot( x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0)", "100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 20, 'Amean', 'M', 100,", "# plot in pdf pp = PdfPages(folder + fileName + '.pdf') if btype", "y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker =", "30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 40,", "'Gmeanratio': for i in getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in", "== 'Gmeanratio': if MST == 0: y3.append(way(i, num)) else: y3.append(way(i, Mbaseline )) else:", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100,", "10, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1,", "#wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2) #wayofMean(Gmeanratio,", "== 3: target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif", "#CTjit tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line strline =", "0) wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0)", "y11 = [] x12 = [] y12 = [] x13 = [] y13", "'-', marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13,", "'L', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "2: print \"Usage: python mean_printer.py [representative/ILP/TDA/CT]\" return -1 mode = args[1] #after this,", "100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #", "fileidx < group: tmpUtil = [] f1 = open(var1+\".txt\", 'r') count = -1", "'L', 10, 1, 'L') # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio,", "'Amean', 'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean',", "= [] resTotal9 = [] resTotal10 = [] resTotal11 = [] resTotal12 =", "'Gmeanratio': if MST == 0: y2.append(way(i, num)) else: y2.append(way(i, Mbaseline )) else: y2.append(way(i))", "= [] tmpRes17 = [] for line in f1: if count == -1:", "'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S',", "== 'Gmeanratio': if MST == 0: y16.append(way(i, num)) else: y16.append(way(i, Mbaseline )) else:", "for i in getResPerUtili(resTotal15,s, num): #when g = 6 if atitle == 'Ameanratio'", "wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S', 100, 0) wayofMean(gmean,", "x14, y14, '-', marker = marker.next(), label='PST-FF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker", "label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-', marker = marker.next(), label='PST-FF-TDA(Carry)', linewidth=2.0) #ax.plot( x9,", "2, 'L', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 40,", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1, 'S') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1,", "20, 'Gmeanratio', 'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 2,", "10, 1, 'S') wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 10, 1, 'L') ''' if __name__", "y5.append(way(i)) for i in getResPerUtili(resTotal6,s, num): #when g = 6 if atitle ==", "0) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 10, 'Ameanratio', 'L', 100, 0)", "ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-',", "1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1)", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y9.append(way(i,", "target = 'worst/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 2: target = 'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST ==", "'M', 100, 2, 'L', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'S', mode)", "100, 0) wayofMean(Ameanratio, 30, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 100,", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 10, 1,", "'S', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio',", "tmpRes16.append(int(strline[15])) #CTmix tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','')", "count+=1 #print icount if count > numinSets-1: readyres[icount]=readyres[icount]+tmp tmp = [] count =", "wayofMean(np.mean, 40, 'Amean', 'M', 100, 0) wayofMean(gmean, 40, 'Gmean', 'M', 100, 0) wayofMean(np.mean,", "baseline): res = [] if baseline == 0: return 1 for i in", "10, 'Amean', 'S', 100, 0) # Now assume all the results are for", "[] tmpRes10 = [] tmpRes11 = [] tmpRes12 = [] tmpRes13 = []", "'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 10,", "count == s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline = strline.replace(']','') strline", "tmpRes17.append(int(strline[16])) if count == s*2+1: ''' #print 'Gmean:'+line strline = line.replace('[','') strline =", "y3.append(way(i)) for i in getResPerUtili(resTotal5,s, num): #when g = 6 ILPbaseline if atitle", "y16.append(way(i)) for i in getResPerUtili(resTotal17,s, num): #when g = 6 if atitle ==", "'M', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio',", "marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot(", "in range(8)] count = 0 for ind, i in enumerate(res): #each file #print", "= [] resTotal16 = [] resTotal17 = [] def init(): global x1, x2,", "100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'L', 100,", "== 'Gmeanratio': if MST == 0: y8.append(way(i, num)) else: y8.append(way(i, Mbaseline )) else:", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'M', 100,", "'CT': ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14,", "utililist = [] if num == 40: readyres = [[] for i in", "Mbaseline )) else: y2.append(way(i)) for i in getResPerUtili(resTotal3,s, num): #when g = 6", "i in getResPerUtili(resTotal16,s, num): #when g = 6 if atitle == 'Ameanratio' or", "atitle == 'Gmeanratio': if MST == 0: y4.append(way(i, num)) else: y4.append(way(i, 0)) else:", "wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 0) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 0) wayofMean(Ameanratio,", "1: res.append(float(i)/float(baseline)) else: res.append(1) else: res.append(1) if len(results) == 0: return 1 return", "1) wayofMean(np.mean, 20, 'Amean', 'S', 100, 1) wayofMean(gmean, 20, 'Gmean', 'S', 100, 1)", "Mbaseline = 0 for i in getResPerUtili(resTotal4,s, num): #when g = 6 Inflation", "'-', marker = marker.next(), label='PST-FF-CT(Baseline)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(),", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100,", "0, 1, transform=ax.transAxes ) #ax.text(0.35, 0.04, \"$U^*=60\\%$\", transform=ax.transAxes, size=16 ) #ax.text(0.85, 0.04, \"$U^*=70\\%$\",", "20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S', 100, 0) wayofMean(Ameanratio, 20,", "wayofMean(np.mean, 20, 'Amean', 'L', 100, 1) wayofMean(gmean, 20, 'Gmean', 'L', 100, 1) wayofMean(np.mean,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': for i in getResPerUtili(resTotal4,s, num):", ")) else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline", "'-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(),", "else: icount = (icount+1)%8 icount = 0 count = 0 for i in", "marker = marker.next(), label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)',", "[] tmpRes15 = [] tmpRes16 = [] tmpRes17 = [] for line in", "x10, y10, '-', marker = marker.next(), label='PST-FF-TDA(Jit)', linewidth=2.0) #ax.plot( x11, y11, '-', marker", "== 40: readyres = [[] for i in range(6)] elif num == 30:", "1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'M', 100, 1)", "40, 'Gmeanratio', 'L', 100, 1) ''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L',", "else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when g", "'L', 100, 0) wayofMean(gmean, 30, 'Gmean', 'L', 100, 0) wayofMean(np.mean, 40, 'Amean', 'S',", "'best/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype elif MST == 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili", "sys import numpy as np import matplotlib.pyplot as plt import itertools from matplotlib", "= [] y10 = [] x11 = [] y11 = [] x12 =", "= [] y7 = [] x8 = [] y8 = [] x9 =", "#wayofMean(Ameanratio, 40, 'Ameanratio', 'S', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 100, 1) #wayofMean(Ameanratio,", "count%2==1: strline = line.replace('[','') strline = strline.replace(']','') strline = strline.replace('\\n','') strline = strline.split(',')", "0) wayofMean(gmean, 30, 'Gmean', 'M', 100, 0) wayofMean(np.mean, 30, 'Amean', 'L', 100, 0)", "wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'L', mode) # wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "elif MST == 3: #worst fileName = 'Worst-M'+atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype else: fileName = atitle+'-tasks'+repr(num)+'_stype_'+repr(typ)+'_btype'+btype print", "== 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic Mean\", size=20)", "'-', marker = marker.next(), label='ILP-Block', linewidth=2.0) ax.plot( x3, y3, '-', marker = marker.next(),", "num)) else: y9.append(way(i, Mbaseline )) else: y9.append(way(i)) for i in getResPerUtili(resTotal10,s, num): #when", "Now assume all the results are for Limited-preemptive scheduling so # of arguments", "if MST == 0: y1.append(way(i, num)) else: y1.append(way(i, Mbaseline )) else: y1.append(way(i)) for", "[] y7 = [] x8 = [] y8 = [] x9 = []", "in getResPerUtili(resTotal3,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "30, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 30, 'Amean', 'L', 100, 1) wayofMean(gmean, 30,", "else: y17.append(way(i)) # plot in pdf pp = PdfPages(folder + fileName + '.pdf')", "'Gmeanratio', 'M', 100, 1) #wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 1) #wayofMean(Gmeanratio, 40, 'Gmeanratio',", "'L', 100, 0) wayofMean(Ameanratio, 20, 'Ameanratio', 'S', 100, 0) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'S',", "label='PST-BF-CT(Baseline)', linewidth=2.0) ax.plot( x14, y14, '-', marker = marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15,", "0) wayofMean(Ameanratio, 40, 'Ameanratio', 'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0)", "getResPerUtili(resTotal4,s, num): #when g = 6 Inflation if atitle == 'Ameanratio' or atitle", "wayofMean(gmean, 10, 'Gmean', 'S', 100, 1) wayofMean(np.mean, 10, 'Amean', 'M', 100, 1) wayofMean(gmean,", "= marker.next(), label='PST-BF-CT(Carry)', linewidth=2.0) #ax.plot( x15, y15, '-', marker = marker.next(), label='PST-FF-CT(Block)', linewidth=2.0)", "count = 0 for ind, i in enumerate(res): #each file #print \"\" #print", "y15.append(way(i, num)) else: y15.append(way(i, Mbaseline )) else: y15.append(way(i)) for i in getResPerUtili(resTotal16,s, num):", "an 20 utililist = [] if num == 40: readyres = [[] for", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y10.append(way(i,", ") ax.legend(loc=0, prop={'size':14}) figure = plt.gcf() figure.set_size_inches([10, 6]) pp.savefig() plt.clf() plt.show() pp.close() folder", "atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y10.append(way(i, num))", "i #print len(i) tmp = [] icount = 0 for j in i:", "'L', 100, 1) wayofMean(np.mean, 40, 'Amean', 'S', 100, 1) wayofMean(gmean, 40, 'Gmean', 'S',", "return utililist def Ameanratio(results, baseline): res = [] if baseline ==0: return 1", "way(i, num) y14.append(way(i, num)) else: y14.append(way(i, Mbaseline )) else: y14.append(way(i)) for i in", "'v')) try: if MST == 0: if mode == 'REP': if num <", "'L', 100, 1) wayofMean(gmean, 10, 'Gmean', 'L', 100, 1) wayofMean(np.mean, 20, 'Amean', 'S',", "''' #wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 100, 2, 'L', mode) #Limited-preemptive wayofMean(Gmeanratio, 10, 'Gmeanratio',", "2, 'L', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'L', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10,", "[] tmpRes8 = [] tmpRes9 = [] tmpRes10 = [] tmpRes11 = []", "[] tmpRes5 = [] tmpRes6 = [] tmpRes7 = [] tmpRes8 = []", "= [] y11 = [] x12 = [] y12 = [] x13 =", "= [] tmpRes9 = [] tmpRes10 = [] tmpRes11 = [] tmpRes12 =", "for i in getResPerUtili(resTotal7,s, num): tmpy7.append(np.mean(i)) if Mbaseline == 0: Mbaseline = max(tmpy7)", "'L', 10, 1, 'S') wayofMean(Gmeanratio, 20, 'Gmeanratio', 'L', 10, 1, 'L') # wayofMean(Gmeanratio,", "if atitle == 'Ameanratio' or atitle == 'Gmeanratio': if MST == 0: y5.append(way(i,", "== 1: target = 'outputM_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype else: target = 'output_completed/Results-tasks'+repr(num)+'_stype'+typ+'_btype'+btype utili = fileInput(target, g,", "10, 1, 'L') # wayofMean(Gmeanratio, 40, 'Gmeanratio', 'S', 10, 1, 'S') wayofMean(Gmeanratio, 40,", "-1 continue count += 1 f1.close() resTotal1.append(tmpRes1) resTotal2.append(tmpRes2) resTotal3.append(tmpRes3) resTotal4.append(tmpRes4) resTotal5.append(tmpRes5) resTotal6.append(tmpRes6) resTotal7.append(tmpRes7)", "getResPerUtili(resTotal4,s, num): tmpy4.append(np.mean(i)) Mbaseline = max(tmpy4) for i in getResPerUtili(resTotal1,s, num): #when g", "marker = marker.next(), label='PST-BF-TDA(Mixed)', linewidth=2.0) ax.plot( x13, y13, '-', marker = marker.next(), label='PST-BF-CT(Baseline)',", "y10, y11, y12, y13, y14, y15, y16, y17 global resTotal1, resTotal2, resTotal3, resTotal4,", "resTotal2 = [] resTotal3 = [] resTotal4 = [] resTotal5 = [] resTotal6", "marker.next(), label='PST-FF-TDA(Mixed)', linewidth=2.0) elif mode == 'CT': ax.plot( x13, y13, '-', marker =", "else: y12.append(way(i)) for i in getResPerUtili(resTotal13,s, num): #when g = 6 CTbaseline if", "'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'L', mode)", "wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100, 2, 'M', mode) wayofMean(Gmeanratio, 30, 'Gmeanratio', 'L', 100,", "if mode == 'REP': if num < 30: ax.plot( x4, y4, '-', marker", "1) #wayofMean(Ameanratio, 30, 'Ameanratio', 'M', 100, 1) #wayofMean(Gmeanratio, 30, 'Gmeanratio', 'M', 100, 1)", "= [] resTotal12 = [] resTotal13 = [] resTotal14 = [] resTotal15 =", "wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100, 2, 'S', mode) wayofMean(Gmeanratio, 20, 'Gmeanratio', 'M', 100,", "if MST == 0: #print i, num #print way(i, num) y14.append(way(i, num)) else:", "if MST == 0: y10.append(way(i, num)) else: y10.append(way(i, Mbaseline )) else: y10.append(way(i)) for", "10, 1, 'S') wayofMean(Gmeanratio, 30, 'Gmeanratio', 'S', 10, 1, 'L') wayofMean(Gmeanratio, 30, 'Gmeanratio',", "'L', 100, 0) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'L', 100, 0) #MST wayofMean(np.mean, 10, 'Amean',", "in getResPerUtili(resTotal8,s, num): #when g = 6 if atitle == 'Ameanratio' or atitle", "for i in getResPerUtili(resTotal10,s, num): #when g = 6 if atitle == 'Ameanratio'", "ax.plot( x7, y7, '-', marker = marker.next(), label='PST-FF-TDA(Baseline)', linewidth=2.0) ax.plot( x8, y8, '-',", "utililist #print resTotal6 def getResPerUtili(res, numinSets, num): #work for tasks 10 an 20", "100, 1) wayofMean(gmean, 10, 'Gmean', 'M', 100, 1) wayofMean(np.mean, 10, 'Amean', 'L', 100,", "== 0: return 1 return np.mean(res) def Gmeanratio(results, baseline): res = [] if", "elif atitle == 'Gmean': ax.set_ylabel(\"Geometric Mean\", size=20) elif atitle == 'Ameanratio': ax.set_ylabel(\"Normalized Arithmetic", "'-', marker = marker.next(), label='PST-FF-CT(Jit)', linewidth=2.0) ax.plot( x17, y17, '-', marker = marker.next(),", "x6, y6, '-', marker = marker.next(), label='ILP-Combo', linewidth=2.0) pass elif mode == 'TDA':", "'Gmeanratio', 'M', 100, 2, 'M', mode) wayofMean(Gmeanratio, 40, 'Gmeanratio', 'M', 100, 2, 'L',", "'S', 100, 2, 'S', mode) wayofMean(Gmeanratio, 10, 'Gmeanratio', 'S', 100, 2, 'M', mode)", "num < 30: ax.plot( x1, y1, '-', marker = marker.next(), label='ILP-Carry', linewidth=2.0) #ax.plot(", "tmpRes16 = [] tmpRes17 = [] for line in f1: if count ==", "= [] tmpRes16 = [] tmpRes17 = [] for line in f1: if", "MST == 2: if mode == 'ILP': title = atitle+'-'+repr(num)+'Tasks-e('+typ+')-b('+btype+')' else: title =" ]
[ "in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with subtitles for", "vsr = temp for format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode =", "requested language, without subtitles r'VO{0}$'.format(l), # original version in requested language, with partial", "# non-original (dubbed) version in requested language, with subtitles for the deaf and", "% player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str:", "player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr':", "# original version in requested language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l),", "'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc", "different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with subtitles for the", "with subtitles for the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original", "not vsr: error = None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error", "import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang,", "lang_pref = -1 format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') ==", "requested language, with subtitles for the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l),", "} langcode = LANGS.get(lang, lang) formats = [] temp = {format_id : format_dict", "in requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested language,", "language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with subtitles for the deaf", "= 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats", "subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail':", "(f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType')", "ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA')", "if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext']", "format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url']", "x: x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if", "r'VO{0}-ST{0}$'.format(l), # original version in requested language, with subtitles for the deaf and", "'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return", ") for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) -", "error = 'Video %s is not available' % player_info.get('VID') or video_id raise ExtractorError(error,", "requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles for", "most to least priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES =", "subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version in requested language, with subtitles", ": format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp:", "qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de': 'A',", "# original version in requested language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l),", "subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested", "format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr", "with subtitles for the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original", "in requested language, with subtitles for the deaf and hard-of-hearing in requested language", "upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or", "title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x:", "language, with subtitles for the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), #", "- %s' % subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'),", "player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title += ' - %s' %", "player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str", "language, with subtitles for the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), #", "%s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), }", "for the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version", "= f.get('versionCode') l = re.escape(langcode) # Language preference from most to least priority", "r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language, without subtitles r'V{0}$'.format(l), # non-original", "expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or", "in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles", "# original version in different language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l),", "# Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version", "in requested language r'V{0}-STM{0}$'.format(l), # original version in requested language, with partial subtitles", "-1 format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else", "= info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict) if not vsr: error", "if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break else: lang_pref = -1", "if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'),", "in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with subtitles for", "if not error: error = 'Video %s is not available' % player_info.get('VID') or", "break else: lang_pref = -1 format = { 'format_id': format_id, 'preference': -10 if", "temp = {format_id : format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() ==", "len(PREFERENCES) - pref break else: lang_pref = -1 format = { 'format_id': format_id,", "format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp", "format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s,", "'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ',", "(dubbed) version in requested language, with subtitles for the deaf and hard-of-hearing in", "different language, with subtitles for the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l),", "lambda x: x['custom_msg']['msg'], compat_str) if not error: error = 'Video %s is not", "subtitle: title += ' - %s' % subtitle info_dict = { 'id': player_info['VID'],", "r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with subtitles for the deaf and", "# non-original (dubbed) version in requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed)", "# original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in", "r'V{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles partial subtitles in", "} if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url']", "from ..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str, ) from ..utils import", "language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles for the", "player_info.get('VSU', '').strip() if subtitle: title += ' - %s' % subtitle info_dict =", "raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or", "list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) # Language preference", "player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error: error = 'Video %s is", "and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with", "(player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title +=", "title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc =", "video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict) if not", "LANGS.get(lang, lang) formats = [] temp = {format_id : format_dict for format_id, format_dict", "= [] temp = {format_id : format_dict for format_id, format_dict in list(vsr.items()) if", "in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with subtitles for", "language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original", "'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]',", "'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ',", "in requested language, with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original", "%s' % subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date':", "'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note':", "partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version in requested language, with", "# Language preference from most to least priority # Reference: section 5.6.3 of", "if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp for format_id, format_dict in", "= -1 format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8'", "qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url,", "available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not", "lang, title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda", "and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language,", "version in requested language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original", "and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version in requested language, with", "'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] =", "= (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or title or", "version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language,", "error = None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error = try_get(", "in different language, with subtitles for the deaf and hard-of-hearing in requested language", "')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if", "..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id,", "with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language,", "lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')),", "player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title", "language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different", "format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode)", "deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES):", "with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in", "'%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')),", "else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height':", "== 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width':", "'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')),", "r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with partial subtitles in requested language", "partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language,", "format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp for", "(dubbed) version in requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in", "in different language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version", "f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats']", "requested language, with subtitles for the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l),", "% (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if", "unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info", "temp: vsr = temp for format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode", "lambda x: x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str)", "'').split(' ')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip()", "in requested language, without subtitles r'VO{0}$'.format(l), # original version in requested language, with", "x: x['custom_msg']['msg'], compat_str) if not error: error = 'Video %s is not available'", "= player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0]", "subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with partial subtitles in different", "not error: error = 'Video %s is not available' % player_info.get('VID') or video_id", "in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with", "utf-8 import re import base64 from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE", "the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version in requested", "qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' +", "and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if", "r'V{0}-STM{0}$'.format(l), # original version in requested language, with partial subtitles in different language", "r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES)", "= { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode =", "the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in", "non-original (dubbed) version in requested language, with subtitles partial subtitles in requested language", "# original version in different language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l),", "# encoding: utf-8 import re import base64 from ..utils import int_or_none from ..extractor.arte", "int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] =", "Language preference from most to least priority # Reference: section 5.6.3 of #", "section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in requested", "language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with partial subtitles", "non-original (dubbed) version in requested language, with subtitles for the deaf and hard-of-hearing", "+ f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats)", "int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None): info =", "formats = [] temp = {format_id : format_dict for format_id, format_dict in list(vsr.items())", "+= ' - %s' % subtitle info_dict = { 'id': player_info['VID'], 'title': title,", "= ( # original version in requested language, without subtitles r'VO{0}$'.format(l), # original", "player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), }", "different language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in", "'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp':", "format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return info_dict ArteTVBaseIE._extract_from_json_url", "= len(PREFERENCES) - pref break else: lang_pref = -1 format = { 'format_id':", "requested language r'VO{0}-ST{0}$'.format(l), # original version in requested language, with subtitles for the", "the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different", "temp for format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l", "p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break else:", "info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage')", "qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]',", "( compat_str, ) from ..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, )", "re import base64 from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat", "or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = {", "version in requested language, with subtitles for the deaf and hard-of-hearing in different", "hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without subtitles", "= (player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title", "try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id)", "if temp: vsr = temp for format_id, format_dict in list(vsr.items()): f = dict(format_dict)", "partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with", "else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return info_dict", "language r'V{0}-STM{0}$'.format(l), # original version in requested language, with partial subtitles in different", "priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original", "= {format_id : format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang}", "requested language r'V{0}-STM{0}$'.format(l), # original version in requested language, with partial subtitles in", "%s is not available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str =", "original version in requested language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), #", "for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr =", "language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different", "int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer']", "# http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in requested language, without subtitles", "'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else:", "'').strip() if subtitle: title += ' - %s' % subtitle info_dict = {", "f.get('versionCode') l = re.escape(langcode) # Language preference from most to least priority #", "language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with partial subtitles in requested", "from ..compat import ( compat_str, ) from ..utils import ( ExtractorError, int_or_none, qualities,", "enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break else: lang_pref =", "= player_info.get('VSU', '').strip() if subtitle: title += ' - %s' % subtitle info_dict", "from ..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url,", "f = dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) # Language preference from", "f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') ==", "subtitles r'VO{0}$'.format(l), # original version in requested language, with partial subtitles in requested", "original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different", "deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language,", "with subtitles for the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original", "# non-original (dubbed) version in requested language, with subtitles partial subtitles in requested", "subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with subtitles", "without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles partial", "original version in requested language, without subtitles r'VO{0}$'.format(l), # original version in requested", "in requested language r'VO{0}-ST{0}$'.format(l), # original version in requested language, with subtitles for", "in different language, with subtitles for the deaf and hard-of-hearing in different language", "format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format)", "} qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de':", "r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles for the deaf", "http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in requested language, without subtitles r'VO{0}$'.format(l),", "# original version in different language, with subtitles for the deaf and hard-of-hearing", "= None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error = try_get( player_info,", "language, without subtitles r'VO{0}$'.format(l), # original version in requested language, with partial subtitles", "requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language, without subtitles r'V{0}$'.format(l),", "hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version in requested language, with partial", "language, with subtitles for the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), #", "least priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( #", "different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with partial", "r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with partial subtitles in different language", "int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url']", "without subtitles r'VO{0}$'.format(l), # original version in requested language, with partial subtitles in", "= re.escape(langcode) # Language preference from most to least priority # Reference: section", "( # original version in requested language, without subtitles r'VO{0}$'.format(l), # original version", "'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats", "' - %s' % subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description':", "in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language, without subtitles", "= f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return info_dict ArteTVBaseIE._extract_from_json_url =", "or '').split(' ')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU',", "compat_str, ) from ..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def", "versionCode = f.get('versionCode') l = re.escape(langcode) # Language preference from most to least", "PREFERENCES = ( # original version in requested language, without subtitles r'VO{0}$'.format(l), #", "different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref", "language r'VO{0}-ST{0}$'.format(l), # original version in requested language, with subtitles for the deaf", "version in different language, with subtitles for the deaf and hard-of-hearing in different", "in requested language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version", "'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats = [] temp = {format_id", "deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version in requested language,", "is not available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate')", "or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title += ' - %s'", "vsr = try_get(player_info, lambda x: x['VSR'], dict) if not vsr: error = None", "import ( compat_str, ) from ..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate,", "(dubbed) version in requested language, with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l),", "partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with", "encoding: utf-8 import re import base64 from ..utils import int_or_none from ..extractor.arte import", "dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp for format_id, format_dict in list(vsr.items()):", "f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')),", "'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),", "language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with subtitles for the deaf", "'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS", "in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode):", "not available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if", "vsr: error = None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error =", "requested language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in", "not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI')", "info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict) if not vsr: error =", "player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ',", "language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with subtitles for the deaf", "'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang)", "'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es':", "json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr =", "hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with partial", "x: x['VSR'], dict) if not vsr: error = None if try_get(player_info, lambda x:", "versionCode): lang_pref = len(PREFERENCES) - pref break else: lang_pref = -1 format =", "list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp for format_id, format_dict", "f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] =", "if not vsr: error = None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error':", "for the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in", "= { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference':", "ArteTVBaseIE from ..compat import ( compat_str, ) from ..utils import ( ExtractorError, int_or_none,", "original version in requested language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), #", "error: error = 'Video %s is not available' % player_info.get('VID') or video_id raise", "to least priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = (", "== 'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error:", "'SQ']) LANGS = { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', }", "compat_str) if not error: error = 'Video %s is not available' % player_info.get('VID')", "with subtitles for the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for", "requested language, with subtitles for the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l),", "LANGS = { 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode", "'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats = []", "r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with subtitles for the deaf and", "language, with subtitles for the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), #", "= temp for format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode')", "for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref", "version in different language, with subtitles for the deaf and hard-of-hearing in requested", "import re import base64 from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from", "in requested language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version", "with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version in requested language,", "dict) if not vsr: error = None if try_get(player_info, lambda x: x['custom_msg']['type']) ==", "'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path']", "-10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' %", "x['VSR'], dict) if not vsr: error = None if try_get(player_info, lambda x: x['custom_msg']['type'])", "subtitles for the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref,", "'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id)", "deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language,", "or video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str =", "in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if temp: vsr = temp for format_id,", "title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title += ' -", "with subtitles for the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original", "requested language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version in", "_extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr", "x['custom_msg']['msg'], compat_str) if not error: error = 'Video %s is not available' %", "or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle", "of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in requested language, without", "different language, with subtitles for the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l),", "'quality': qfunc(f.get('quality')), } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:'", "original version in different language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), #", "{ 'fr': 'F', 'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang,", "x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not", "'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats = [] temp =", "original version in different language, with subtitles for the deaf and hard-of-hearing in", "5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in requested language,", "else: lang_pref = -1 format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat')", "requested language, with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed)", "video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info,", "in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) # Language", "self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict) if", "langcode = LANGS.get(lang, lang) formats = [] temp = {format_id : format_dict for", "= dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) # Language preference from most", "= { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or", "{ 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU',", "= try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error: error = 'Video", "player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict) if not vsr:", "'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error: error", "different language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in", "re.escape(langcode) # Language preference from most to least priority # Reference: section 5.6.3", "language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref =", "language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles", "upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split('", "f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] = f['url']", "'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr':", "'Video %s is not available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True) upload_date_str", "..compat import ( compat_str, ) from ..utils import ( ExtractorError, int_or_none, qualities, try_get,", "different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with subtitles for the", "'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s'", "if subtitle: title += ' - %s' % subtitle info_dict = { 'id':", "lang} if temp: vsr = temp for format_id, format_dict in list(vsr.items()): f =", "subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version in requested language, with", "= f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] =", "import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str, ) from", "lambda x: x['VSR'], dict) if not vsr: error = None if try_get(player_info, lambda", "language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original version in requested", "r'VO{0}$'.format(l), # original version in requested language, with partial subtitles in requested language", "original version in different language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), #", "with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language,", "for format_id, format_dict in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l =", "version in different language, with partial subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original", ") def _extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info =", "different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with partial subtitles in", "language, with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), # non-original (dubbed) version", "try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error: error = 'Video %s", "and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without", "or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title += '", "pref, p in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break", "version in requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested", "language, with subtitles for the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), )", "upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or title", "{ 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref,", ") from ..utils import ( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self,", "the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different", "for the deaf and hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p", "..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str, ) from ..utils import (", "subtitles for the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version", "int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str, ) from ..utils", "r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with subtitles for the deaf and", "original version in requested language, with subtitles for the deaf and hard-of-hearing in", "= 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats,", "subtitles in requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with subtitles", "without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version in different language, with partial subtitles in", "non-original (dubbed) version in requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version", "'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality':", "preference from most to least priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf", "# original version in requested language, with subtitles for the deaf and hard-of-hearing", "from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str,", "if not upload_date_str: upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title =", "'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats = [] temp", "for the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version in", "def _extract_from_json_url(self, json_url, video_id, lang, title=None): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer']", "subtitles for the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed)", "import base64 from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import", "version in requested language, with subtitles for the deaf and hard-of-hearing in requested", "requested language, without subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested language, with", "for the deaf and hard-of-hearing in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in", "l = re.escape(langcode) # Language preference from most to least priority # Reference:", "video_id raise ExtractorError(error, expected=True) upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = (player_info.get('VRA')", "requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), #", "f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return info_dict ArteTVBaseIE._extract_from_json_url = _extract_from_json_url", "= self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'], dict)", "title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle = player_info.get('VSU', '').strip() if subtitle:", "None if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda", "the deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in", "== lang} if temp: vsr = temp for format_id, format_dict in list(vsr.items()): f", "import ArteTVBaseIE from ..compat import ( compat_str, ) from ..utils import ( ExtractorError,", "version in requested language, without subtitles r'VO{0}$'.format(l), # original version in requested language,", "== 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv'", "(player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip()", "base64 from ..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import (", "error = try_get( player_info, lambda x: x['custom_msg']['msg'], compat_str) if not error: error =", "in requested language r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l),", "try_get(player_info, lambda x: x['VSR'], dict) if not vsr: error = None if try_get(player_info,", "ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None): info", "requested language r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l), # original version in different language, with subtitles for the", "format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] =", "{}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F',", "re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break else: lang_pref = -1 format", "( ExtractorError, int_or_none, qualities, try_get, unified_strdate, ) def _extract_from_json_url(self, json_url, video_id, lang, title=None):", "= qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS = { 'fr': 'F', 'de': 'A', 'en':", "try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda x: x['custom_msg']['msg'],", "language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language, without subtitles r'V{0}$'.format(l), #", "hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested language, without", "version in requested language, with subtitles partial subtitles in requested language r'V{0}-ST{0}$'.format(l), #", "with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language,", "None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')),", "player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) LANGS =", "[] temp = {format_id : format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower()", "subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested language, with subtitles", "# original version in requested language, without subtitles r'VO{0}$'.format(l), # original version in", "r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l), # original version in different language, without subtitles r'VO(?:(?!{0}))?$'.format(l), # original version", "info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] vsr = try_get(player_info, lambda x: x['VSR'],", "..utils import int_or_none from ..extractor.arte import ArteTVBaseIE from ..compat import ( compat_str, )", "format_dict in list(vsr.items()): f = dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) #", "subtitles for the deaf and hard-of-hearing in requested language r'V{0}-STM{0}$'.format(l), # original version", "'de': 'A', 'en': 'E[ANG]', 'es': 'E[ESP]', } langcode = LANGS.get(lang, lang) formats =", "pref break else: lang_pref = -1 format = { 'format_id': format_id, 'preference': -10", "hard-of-hearing in different language r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l), ) for pref, p in enumerate(PREFERENCES): if re.match(p,", "lang) formats = [] temp = {format_id : format_dict for format_id, format_dict in", "= try_get(player_info, lambda x: x['VSR'], dict) if not vsr: error = None if", "subtitle = player_info.get('VSU', '').strip() if subtitle: title += ' - %s' % subtitle", "version in different language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original", "{format_id : format_dict for format_id, format_dict in list(vsr.items()) if dict(format_dict).get('versionShortLibelle').lower() == lang} if", "from most to least priority # Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES", "subtitles r'V{0}$'.format(l), # non-original (dubbed) version in requested language, with subtitles partial subtitles", "lang_pref = len(PREFERENCES) - pref break else: lang_pref = -1 format = {", "title += ' - %s' % subtitle info_dict = { 'id': player_info['VID'], 'title':", "'E[ESP]', } langcode = LANGS.get(lang, lang) formats = [] temp = {format_id :", "dict(format_dict) versionCode = f.get('versionCode') l = re.escape(langcode) # Language preference from most to", "version in requested language, with partial subtitles in requested language r'VO{0}-ST{0}$'.format(l), # original", "in different language, with partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version", "in requested language, with subtitles for the deaf and hard-of-hearing in different language", "partial subtitles in different language r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l), # original version in different language, with", "format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None,", "Reference: section 5.6.3 of # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf PREFERENCES = ( # original version in", "in enumerate(PREFERENCES): if re.match(p, versionCode): lang_pref = len(PREFERENCES) - pref break else: lang_pref", "subtitles for the deaf and hard-of-hearing in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version", "language, with partial subtitles in different language r'VO{0}-ST(?!{0}).+?$'.format(l), # original version in requested", "in different language r'VO{0}-STM(?!{0}).+?$'.format(l), # original version in different language, with partial subtitles", "= LANGS.get(lang, lang) formats = [] temp = {format_id : format_dict for format_id,", "if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error': error = try_get( player_info, lambda x:", "player_info.get('VDA') or '').split(' ')[0] title = (player_info.get('VTI') or title or player_info['VID']).strip() subtitle =", "unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ'])", "deaf and hard-of-hearing in requested language r'VO{0}-STM{0}$'.format(l), # non-original (dubbed) version in requested", "- pref break else: lang_pref = -1 format = { 'format_id': format_id, 'preference':", "= 'Video %s is not available' % player_info.get('VID') or video_id raise ExtractorError(error, expected=True)", "% subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str)," ]
[ "= np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1", "np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2)", "150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D)", "data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix = spdiags(data,", "sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar", "matplotlib.pyplot as plt from scipy import stats np.random.seed(1) # 设置随机种子 D = 150", "from scipy import stats np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs", "D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01]", "laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ###", "xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index]", "1, D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号", "np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs", "[-1]*D]) diags = np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D, D).toarray() L", "= 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2 =", "'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D) # for", "np from functools import reduce from scipy.sparse import spdiags import matplotlib.pyplot as plt", "obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu", "1, 2]) all_matrix = spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) #", "### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar", "plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index]", "= np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix = spdiags(data, diags,", "f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index],", "= perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] #", "i in range(3): fs = np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index]", "plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D)", "postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index],", "L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index =", "# 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index =", "10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D)", "L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:, obs_index] laml1 =", "= np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1)", "import stats np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10", "xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro',", "color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in", "f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for", "for i in range(3): fs = np.zeros(D) # for j, single_index in enumerate(hid_index):", "np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1,", "= 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0, 1,", "np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)]", "# 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs =", "= lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T,", "定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index)))", "#观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data", "- 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12)", "functools import reduce from scipy.sparse import spdiags import matplotlib.pyplot as plt from scipy", "= L[:, hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 =", "np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index]", "= (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar +", "plt from scipy import stats np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值)", "D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0,", "lambda_index = 0 L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:,", "laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu =", "= np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0,", "= spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas", "xbar + 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index],", "numpy as np from functools import reduce from scipy.sparse import spdiags import matplotlib.pyplot", "j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index] = x_obs.flatten() plt.plot(xs,", "np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L)", "+ 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu,", "= xbar + 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8))", "import reduce from scipy.sparse import spdiags import matplotlib.pyplot as plt from scipy import", "D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index", "'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma", "plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index]))", "# 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D])", "plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] =", "plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D) # for j, single_index in", "np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 =", "all_matrix = spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差", "diags = np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D, D).toarray() L =", "= np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号", "import matplotlib.pyplot as plt from scipy import stats np.random.seed(1) # 设置随机种子 D =", "绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2 = xbar - 2*sigma", "2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2)", "in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index] = x_obs.flatten() plt.plot(xs, fs,'k-',linewidth=1) plt.show()", "scipy import stats np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs =", "postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten()", "xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 #", "生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix =", "= [30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1 = L[:, hid_index]", "= np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] =", "xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index", "sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot')", "= 10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm =", "laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12)", "perm = np.random.permutation(D) # 索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) #", "D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index", "= np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1),", "plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D)", "# 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2 = xbar -", "obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis]", "f1 = xbar + 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2, f1,", "hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data =", "np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5", "<filename>mlapp/MLAPP_CODE/MLAPP-C4-Code/GaussInterpDemo.py<gh_stars>0 \"\"\"根据已有观察值,对函数进行插值处理\"\"\" import numpy as np from functools import reduce from scipy.sparse import", "lambdas = [30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1 = L[:,", "markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D) # for j,", "fs = np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma,", "lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1)", "plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] =", "linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index]", "(np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma", "markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma =", "as plt from scipy import stats np.random.seed(1) # 设置随机种子 D = 150 #", "linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs =", "f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i", "postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs", "x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D) #", "range(3): fs = np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(),", "0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2 =", "# for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index] =", "索引号打乱 obs_index = perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:,", "hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2)", "= np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu,", "print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0 L =", "[30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2", "= x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带", "= np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2]", "L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1)", "[2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D, D).toarray()", "sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2", "np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D,", "#plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D) # for j, single_index", "L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs))", "= postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] =", "reduce from scipy.sparse import spdiags import matplotlib.pyplot as plt from scipy import stats", "import spdiags import matplotlib.pyplot as plt from scipy import stats np.random.seed(1) # 设置随机种子", "plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3):", "= np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图", "x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0 # 绘制边缘后验分布的标准误差带 plt.figure()", "perm[range(10)] #观测值的索引号 hid_index = np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值", "2]) all_matrix = spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda", "postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index] = 0", "plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5]) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) for i in range(3): fs = np.zeros(D)", "L[:, hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T,", "L1 = L[:, hid_index] L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2", "= np.array(list(set(perm)-set(obs_index))) # 未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D,", "in range(3): fs = np.zeros(D) # for j, single_index in enumerate(hid_index): fs[hid_index] =", "x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags =", "先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1", "= xbar - 2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs,", "spdiags(data, diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas =", "stats np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 #", "as np from functools import reduce from scipy.sparse import spdiags import matplotlib.pyplot as", "np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix = spdiags(data, diags, D,", "未观测值的索引号 x_obs = np.random.randn(n_obs)[:, np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags", "# 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs", "数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集", "# 观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D) #", "0 L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:, obs_index] laml1", "# 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L", "2*sigma plt.fill_between(xs, f2, f1, color=(0.8,0.8,0.8)) plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) #plt.ylim([-5,5])", "import numpy as np from functools import reduce from scipy.sparse import spdiags import", "for j, single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index] = x_obs.flatten()", "plt.style.use('ggplot') f1 = xbar + 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs, f2,", "single_index in enumerate(hid_index): fs[hid_index] = stats.multivariate_normal.rvs(postdist_mu.flatten(), postdist_sigma, 1) fs[obs_index] = x_obs.flatten() plt.plot(xs, fs,'k-',linewidth=1)", "仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0 L = lambdas[lambda_index]*L L1 =", "np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2,", "= np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱 obs_index =", "L2 = L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma", "= 0 L = lambdas[lambda_index]*L L1 = L[:, hid_index] L2 = L[:, obs_index]", "from scipy.sparse import spdiags import matplotlib.pyplot as plt from scipy import stats np.random.seed(1)", "diags, D, D).toarray() L = (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30,", "x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index]))", "= reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs,", "np.random.seed(1) # 设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量", "x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar = np.zeros(D) xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten()", "plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2 = xbar - 2*sigma plt.fill_between(xs,", "xbar[hid_index] = postdist_mu.flatten() xbar[obs_index] = x_obs.flatten() sigma = np.zeros(D) sigma[hid_index] = (np.diag(postdist_sigma))**0.5 sigma[obs_index]", "np.dot(L1.T, L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure()", "设置随机种子 D = 150 # 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs =", "\"\"\"根据已有观察值,对函数进行插值处理\"\"\" import numpy as np from functools import reduce from scipy.sparse import spdiags", "# 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2]) all_matrix", "# 数据的总量(含观测和未观测到的值) n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D) #", "postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index],", "= (1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0", "np.newaxis] # 生成n_obs个观测值 data = np.array([[-1]*D, [2]*D, [-1]*D]) diags = np.array([0, 1, 2])", "绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro', markersize=12) plt.title(r'$\\lambda$={}'.format(lambdas[lambda_index])) xbar =", "= L[:, obs_index] laml1 = np.dot(L1.T, L1) laml2 = np.dot(L1.T, L2) postdist_sigma =", "0 # 绘制边缘后验分布的标准误差带 plt.figure() plt.style.use('ggplot') f1 = xbar + 2*sigma f2 = xbar", "(1/2)*all_matrix[0:D-2] print(L) # 先验精度值lambda 仅仅影响方差 lambdas = [30, 0.01] lambda_index = 0 L", "reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot') plt.plot(xs[hid_index], postdist_mu, linewidth=2) plt.plot(xs[obs_index], x_obs, 'ro',", "n_obs = 10 # 观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm", "观测到的样本点的数量 xs = np.linspace(0, 1, D) # 定义函数的支撑集 perm = np.random.permutation(D) # 索引号打乱", "scipy.sparse import spdiags import matplotlib.pyplot as plt from scipy import stats np.random.seed(1) #", "L2) postdist_sigma = np.linalg.inv(laml1) postdist_mu = reduce(np.dot,(-np.linalg.inv(laml1), laml2, x_obs)) ### 绘图 plt.figure() plt.style.use('ggplot')", "from functools import reduce from scipy.sparse import spdiags import matplotlib.pyplot as plt from", "spdiags import matplotlib.pyplot as plt from scipy import stats np.random.seed(1) # 设置随机种子 D" ]
[ "main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ] for", "configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\",", "os ls=[\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\",", "\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ] for l in ls:", "--configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs", "configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ] for l in", "import os ls=[\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs", "--configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ] for l", "--configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs", "main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py", "ls=[\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python", "main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ] for l in ls: os.system(l)", "\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python", "\"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\", ]", "configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_3_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_4_CoarseDropout.yml\",", "main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_0_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_1_CoarseDropout.yml\", \"python main.py --configs configs/eval_covid20cases_unetplusplus_timm-regnetx_002_2_CoarseDropout.yml\", \"python main.py" ]
[ "parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\")", "from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import", "domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size),", "dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' %", "need to transfer the image and labels to polar coordinates: MICCAI version is", "PIL import Image import matplotlib.pyplot as plt import cv2 from skimage.transform import rotate", "for i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array of the", "Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str,", "enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col", "np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L')", "is yellow 0, 0 , 0 # index 3 is orange ] zero_pad", "one_name)) if __name__ == '__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path", ", 0 # index 3 is orange ] zero_pad = 256 * 3", "import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as plt import", "parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step", "import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as", "= one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__':", "torch.utils import data from models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES =", "the evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save)", "and start the evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu if not", "import cv2 from skimage.transform import rotate import torch from torch.autograd import Variable import", "(including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE,", "output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__': main() results_folder = SAVE_PATH gt_folder", "name = batch if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output", "all the arguments provided from the CLI. Returns: A list of parsed arguments.", "args = get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3,", "get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict", "images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL =", "index) image, label, _, _, name = batch if args.model == 'Unet': _,_,_,_,", "= output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__': main() results_folder =", "= nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if index % 100", "# mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask", "(args.save, one_name)) if __name__ == '__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/'", "the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str,", "def main(): \"\"\"Create the model and start the evaluation process.\"\"\" args = get_arguments()", "gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If", "type=int, default=BATCH_SIZE, help=\"Number of images sent to the network in one step.\") parser.add_argument(\"--gpu\",", "= '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar = False #If need", "type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of", "UNet from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 # Number", "to polar coordinates: MICCAI version is False ROI_size = 700 #ROI size from", "= '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar =", "3 - len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy", "of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice", "parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to the network in one step.\")", "import argparse import numpy as np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"", "os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader =", "in enumerate(testloader): if index % 100 == 0: print('%d processd' % index) image,", "= args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from)", "for idx, one_name in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred =", "os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader", "classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\")", "parser.parse_args() def main(): \"\"\"Create the model and start the evaluation process.\"\"\" args =", "one_name in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2),", "as np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import", "def colorize_mask(mask): # mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette)", "for Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the", "set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1", "import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 # Number of images in", "0, 0, 0, # index 2 is yellow 0, 0 , 0 #", "batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True)", "is_polar = False #If need to transfer the image and labels to polar", "0, 0 , 0 # index 3 is orange ] zero_pad = 256", "index % 100 == 0: print('%d processd' % index) image, label, _, _,", "the image and labels to polar coordinates: MICCAI version is False ROI_size =", "pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1]", "of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all", "args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx,", "R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model and start the evaluation process.\"\"\"", "type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in", "image and labels to polar coordinates: MICCAI version is False ROI_size = 700", "of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters", "numpy as np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL", "] zero_pad = 256 * 3 - len(palette) for i in range(zero_pad): palette.append(0)", "return new_mask def get_arguments(): \"\"\"Parse all the arguments provided from the CLI. Returns:", "0 # index 3 is orange ] zero_pad = 256 * 3 -", "numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments():", "image, label, _, _, name = batch if args.model == 'Unet': _,_,_,_, output2", "= False #If need to transfer the image and labels to polar coordinates:", "MICCAI version is False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import *", "parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\")", "== 0: print('%d processd' % index) image, label, _, _, name = batch", "mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader):", "is False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[", "provided from the CLI. Returns: A list of parsed arguments. \"\"\" parser =", "_, name = batch if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0))", "matplotlib.pyplot as plt import cv2 from skimage.transform import rotate import torch from torch.autograd", "new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the arguments provided", "help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar coordinate.", "processd' % index) image, label, _, _, name = batch if args.model ==", "step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save", "the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE", "index 3 is orange ] zero_pad = 256 * 3 - len(palette) for", "data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size,", "\"\"\"Create the model and start the evaluation process.\"\"\" args = get_arguments() gpu0 =", "0: print('%d processd' % index) image, label, _, _, name = batch if", "= output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred)", "validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE =", "if __name__ == '__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path =", "= 1 is_polar = False #If need to transfer the image and labels", "if index % 100 == 0: print('%d processd' % index) image, label, _,", "\"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int,", "to transfer the image and labels to polar coordinates: MICCAI version is False", "parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images", "shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else:", "transfer the image and labels to polar coordinates: MICCAI version is False ROI_size", "Returns: A list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str,", "nn from torch.utils import data from models.unet import UNet from dataset.refuge import REFUGE", "save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar coordinate. MICCAI version", "zero_pad = 256 * 3 - len(palette) for i in range(zero_pad): palette.append(0) def", "NUM_CLASSES = 3 NUM_STEPS = 512 # Number of images in the validation", "argparse import numpy as np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\"", "of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of R2U_Net or R2AttU_Net')", "background 128, 128, 128, # index 1 is red 0, 0, 0, #", "background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number", "one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to", "128, 128, 128, # index 1 is red 0, 0, 0, # index", "images in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of", "import torch.nn as nn from torch.utils import data from models.unet import UNet from", "idx, one_name in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred,", "3 is orange ] zero_pad = 256 * 3 - len(palette) for i", "default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of R2U_Net", "version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t", "import torch from torch.autograd import Variable import torch.nn as nn from torch.utils import", "the CLI. Returns: A list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\")", "to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar coordinate. MICCAI", "help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False,", "model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'):", "parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to", "start the evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu if not os.path.exists(args.save):", "= torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True)", "batch in enumerate(testloader): if index % 100 == 0: print('%d processd' % index)", "volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred = output[idx] pred", "= 256 * 3 - len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask):", "#If need to transfer the image and labels to polar coordinates: MICCAI version", "from skimage.transform import rotate import torch from torch.autograd import Variable import torch.nn as", "256 * 3 - len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask): #", "if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for", "SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar = False #If", "index, batch in enumerate(testloader): if index % 100 == 0: print('%d processd' %", "parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to the network in", "= 'Unet' BATCH_SIZE = 1 is_polar = False #If need to transfer the", "default=BATCH_SIZE, help=\"Number of images sent to the network in one step.\") parser.add_argument(\"--gpu\", type=int,", "testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp", "of R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model and start", "torch.autograd import Variable import torch.nn as nn from torch.utils import data from models.unet", "batch if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy()", "help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model", "in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path", "= argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number", "gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table = True evaluate_segmentation_results(results_folder, gt_folder, output_path, export_table)", "in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8)", "as nn from torch.utils import data from models.unet import UNet from dataset.refuge import", "'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in", "help=\"Number of images sent to the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0,", "print('%d processd' % index) image, label, _, _, name = batch if args.model", "type=bool, default=False, help=\"If proceed images in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\",", "2 is yellow 0, 0 , 0 # index 3 is orange ]", "images sent to the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu", "return parser.parse_args() def main(): \"\"\"Create the model and start the evaluation process.\"\"\" args", "os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as plt import cv2 from skimage.transform", "= pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name =", "pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col", "BATCH_SIZE = 1 is_polar = False #If need to transfer the image and", "# Number of images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH =", "results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table = True evaluate_segmentation_results(results_folder,", "is orange ] zero_pad = 256 * 3 - len(palette) for i in", "0, # index 2 is yellow 0, 0 , 0 # index 3", "step of R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model and", "print(RESTORE_FROM) palette=[ 255, 255, 255, # black background 128, 128, 128, # index", "proceed images in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size", "to the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\",", "default=False, help=\"If proceed images in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int,", "the arguments provided from the CLI. Returns: A list of parsed arguments. \"\"\"", "default=NUM_CLASSES, help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore", "colorize_mask(mask): # mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return", "get_arguments(): \"\"\"Parse all the arguments provided from the CLI. Returns: A list of", "help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including background).\")", "process.\"\"\" args = get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model =", "from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to the network in one", "red 0, 0, 0, # index 2 is yellow 0, 0 , 0", "= nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index,", "A list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL,", "false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent", "polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t',", "range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array of the mask new_mask =", "print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__", "Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the arguments provided from the", "model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False,", "is red 0, 0, 0, # index 2 is yellow 0, 0 ,", "os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as plt import cv2", "interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if index %", "evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model", "from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 # Number of", "model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred = output[idx]", "main(): \"\"\"Create the model and start the evaluation process.\"\"\" args = get_arguments() gpu0", "= UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST',", "ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in", "parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of", "128, # index 1 is red 0, 0, 0, # index 2 is", "__name__ == '__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder", "torch from torch.autograd import Variable import torch.nn as nn from torch.utils import data", "arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\",", "dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 # Number of images", "255, 255, 255, # black background 128, 128, 128, # index 1 is", "index 2 is yellow 0, 0 , 0 # index 3 is orange", "list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model", "orange ] zero_pad = 256 * 3 - len(palette) for i in range(zero_pad):", "array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse", "plt import cv2 from skimage.transform import rotate import torch from torch.autograd import Variable", "model and start the evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu if", "from models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS =", "model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to the network", "ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if index % 100 == 0:", "Image import matplotlib.pyplot as plt import cv2 from skimage.transform import rotate import torch", "# index 1 is red 0, 0, 0, # index 2 is yellow", "128, 128, # index 1 is red 0, 0, 0, # index 2", "512 # Number of images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH", "len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array of", "labels to polar coordinates: MICCAI version is False ROI_size = 700 #ROI size", "interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0) pred", "rotate import torch from torch.autograd import Variable import torch.nn as nn from torch.utils", "pred = output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col =", "index 1 is red 0, 0, 0, # index 2 is yellow 0,", "CLI. Returns: A list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\",", "axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp'", "new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the arguments provided from the CLI.", "one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__': main()", "0 , 0 # index 3 is orange ] zero_pad = 256 *", "version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear')", "parser = argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES,", "255, 255, # black background 128, 128, 128, # index 1 is red", "% index) image, label, _, _, name = batch if args.model == 'Unet':", "output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save,", "torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if", "if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp =", "NUM_STEPS = 512 # Number of images in the validation set. RESTORE_FROM =", "output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred", "as plt import cv2 from skimage.transform import rotate import torch from torch.autograd import", "% 100 == 0: print('%d processd' % index) image, label, _, _, name", "torch.nn as nn from torch.utils import data from models.unet import UNet from dataset.refuge", ">= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size),", "black background 128, 128, 128, # index 1 is red 0, 0, 0,", "* 3 - len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask:", "version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size,", "parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar coordinate. MICCAI version is false\")", "gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict =", "% (args.save, one_name)) if __name__ == '__main__': main() results_folder = SAVE_PATH gt_folder =", "the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the", "MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3,", "else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if index", "import rotate import torch from torch.autograd import Variable import torch.nn as nn from", "and labels to polar coordinates: MICCAI version is False ROI_size = 700 #ROI", "MODEL = 'Unet' BATCH_SIZE = 1 is_polar = False #If need to transfer", "model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >=", "size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255, # black background", "type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images", "colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if", "is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear',", "3 NUM_STEPS = 512 # Number of images in the validation set. RESTORE_FROM", "import * print(RESTORE_FROM) palette=[ 255, 255, 255, # black background 128, 128, 128,", "help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of R2U_Net or", "R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model and start the", "if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0)", "mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the arguments", "new_mask def get_arguments(): \"\"\"Parse all the arguments provided from the CLI. Returns: A", "from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255, # black background 128,", "Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes", "output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred = output[idx] pred =", "type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict", "for index, batch in enumerate(testloader): if index % 100 == 0: print('%d processd'", "sent to the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\")", "== '__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table", "False #If need to transfer the image and labels to polar coordinates: MICCAI", "= np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col =", "_,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name):", "version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as plt", "# index 3 is orange ] zero_pad = 256 * 3 - len(palette)", "is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int, default=3, help='t for", "= model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred =", "in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\")", "pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp", "import Image import matplotlib.pyplot as plt import cv2 from skimage.transform import rotate import", "restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to the", "from the CLI. Returns: A list of parsed arguments. \"\"\" parser = argparse.ArgumentParser(description=\"Unet", "'/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar = False", "UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True),", "coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460, help=\"Size of ROI.\") parser.add_argument('--t', type=int,", "import UNet from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 #", "Number of images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/'", "#ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255, # black", "import numpy as np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from", "nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if index % 100 ==", "== 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output = interp(output2).cpu().data.numpy() for idx, one_name", "default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including", "mode='bilinear') for index, batch in enumerate(testloader): if index % 100 == 0: print('%d", "np from packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image", "help='t for Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create", "'/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar = False #If need to", "= get_arguments() gpu0 = args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes)", "coordinates: MICCAI version is False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import", "REFUGE NUM_CLASSES = 3 NUM_STEPS = 512 # Number of images in the", "to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\",", "100 == 0: print('%d processd' % index) image, label, _, _, name =", "default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool,", "_, _, name = batch if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image,", "type=int, default=3, help='t for Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args() def", "\"\"\"Parse all the arguments provided from the CLI. Returns: A list of parsed", "models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS = 512", "model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__)", "import matplotlib.pyplot as plt import cv2 from skimage.transform import rotate import torch from", "Variable import torch.nn as nn from torch.utils import data from models.unet import UNet", "= batch if args.model == 'Unet': _,_,_,_, output2 = model(Variable(image, volatile=True).cuda(gpu0)) output =", "version is False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM)", "from torch.autograd import Variable import torch.nn as nn from torch.utils import data from", "False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255,", "in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet'", "yellow 0, 0 , 0 # index 3 is orange ] zero_pad =", "os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot as plt import cv2 from", "- len(palette) for i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array", "not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train()", "Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model", "= interp(output2).cpu().data.numpy() for idx, one_name in enumerate(name): pred = output[idx] pred = pred.transpose(1,2,0)", "= Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def get_arguments(): \"\"\"Parse all the arguments provided from", "device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed", "packaging import version import os os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2,3\" from PIL import Image import matplotlib.pyplot", "palette=[ 255, 255, 255, # black background 128, 128, 128, # index 1", "polar coordinates: MICCAI version is False ROI_size = 700 #ROI size from evaluation.evaluation_segmentation", "'__main__': main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table =", "import Variable import torch.nn as nn from torch.utils import data from models.unet import", "parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args()", "saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False,", "help=\"If proceed images in polar coordinate. MICCAI version is false\") parser.add_argument(\"--ROI_size\", type=int, default=460,", "the model and start the evaluation process.\"\"\" args = get_arguments() gpu0 = args.gpu", "in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array of the mask new_mask", "= 3 NUM_STEPS = 512 # Number of images in the validation set.", "interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for", "of images sent to the network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose", "RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL = 'Unet' BATCH_SIZE = 1 is_polar", "n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict) model.cuda(gpu0) model.train() testloader = data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size,", "type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where", "align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch in enumerate(testloader): if", "# index 2 is yellow 0, 0 , 0 # index 3 is", "palette.append(0) def colorize_mask(mask): # mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P')", "= 700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255,", "cv2 from skimage.transform import rotate import torch from torch.autograd import Variable import torch.nn", "pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size) one_name", "= 512 # Number of images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth'", "nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear', align_corners=True) else: interp = nn.Upsample(size=(ROI_size, ROI_size), mode='bilinear') for index, batch", "* print(RESTORE_FROM) palette=[ 255, 255, 255, # black background 128, 128, 128, #", "i in range(zero_pad): palette.append(0) def colorize_mask(mask): # mask: numpy array of the mask", "import data from models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES = 3", "one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ ==", "1 is_polar = False #If need to transfer the image and labels to", "1 is red 0, 0, 0, # index 2 is yellow 0, 0", "type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\",", "= colorize_mask(pred) print(output_col.size) one_name = one_name.split('/')[-1] output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name))", "255, # black background 128, 128, 128, # index 1 is red 0,", "= data.DataLoader(REFUGE(False, domain='REFUGE_TEST', is_transform=True), batch_size=args.batch_size, shuffle=False, pin_memory=True) if version.parse(torch.__version__) >= version.parse('0.4.0'): interp =", "help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent to", "ROI_size = 700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255,", "arguments provided from the CLI. Returns: A list of parsed arguments. \"\"\" parser", "argparse.ArgumentParser(description=\"Unet Network\") parser.add_argument(\"--model\", type=str, default=MODEL, help=\"Model Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of", "= SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table = True evaluate_segmentation_results(results_folder, gt_folder,", "of images in the validation set. RESTORE_FROM = '/home/charlietran/CADA_Tutorial/Model_Weights/Trial1/UNet1000_v18_weightedclass.pth' SAVE_PATH = '/home/charlietran/CADA_Tutorial/result/Trial1/' MODEL", "# black background 128, 128, 128, # index 1 is red 0, 0,", "enumerate(testloader): if index % 100 == 0: print('%d processd' % index) image, label,", "'Unet' BATCH_SIZE = 1 is_polar = False #If need to transfer the image", "ROI.\") parser.add_argument('--t', type=int, default=3, help='t for Recurrent step of R2U_Net or R2AttU_Net') return", "predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int,", "default=3, help='t for Recurrent step of R2U_Net or R2AttU_Net') return parser.parse_args() def main():", "evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255, # black background 128, 128,", "data from models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES = 3 NUM_STEPS", "args.gpu if not os.path.exists(args.save): os.makedirs(args.save) model = UNet(3, n_classes=args.num_classes) saved_state_dict = torch.load(args.restore_from) model.load_state_dict(saved_state_dict)", "SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table = True evaluate_segmentation_results(results_folder, gt_folder, output_path,", "output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__': main() results_folder = SAVE_PATH", "from PIL import Image import matplotlib.pyplot as plt import cv2 from skimage.transform import", "output[idx] pred = pred.transpose(1,2,0) pred = np.asarray(np.argmax(pred, axis=2), dtype=np.uint8) output_col = colorize_mask(pred) print(output_col.size)", "network in one step.\") parser.add_argument(\"--gpu\", type=int, default=0, help=\"choose gpu device.\") parser.add_argument(\"--save\", type=str, default=SAVE_PATH,", "main() results_folder = SAVE_PATH gt_folder = '/DATA/charlie/AWC/CADA_Tutorial_Image/Target_Test/mask/' output_path = results_folder export_table = True", "default=RESTORE_FROM, help=\"Where restore model parameters from.\") parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE, help=\"Number of images sent", "from torch.utils import data from models.unet import UNet from dataset.refuge import REFUGE NUM_CLASSES", "or R2AttU_Net') return parser.parse_args() def main(): \"\"\"Create the model and start the evaluation", "default=SAVE_PATH, help=\"Path to save result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar", "0, 0, # index 2 is yellow 0, 0 , 0 # index", "parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM,", "label, _, _, name = batch if args.model == 'Unet': _,_,_,_, output2 =", "output_col = output_col.convert('L') output_col.save('%s/%s.bmp' % (args.save, one_name)) if __name__ == '__main__': main() results_folder", "result.\") parser.add_argument(\"--is_polar\", type=bool, default=False, help=\"If proceed images in polar coordinate. MICCAI version is", "700 #ROI size from evaluation.evaluation_segmentation import * print(RESTORE_FROM) palette=[ 255, 255, 255, #", "def get_arguments(): \"\"\"Parse all the arguments provided from the CLI. Returns: A list", "mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def", "skimage.transform import rotate import torch from torch.autograd import Variable import torch.nn as nn", "Choice Unet.\") parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES, help=\"Number of classes to predict (including background).\") parser.add_argument(\"--restore-from\"," ]
[ "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last ==", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last", "== os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in", "\"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12):", "range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12):", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def", "self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i", "m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self):", "def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "\"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2)", "\"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with", "== os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in", "m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname,", "in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\",", "as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\"))", "test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i))))", "as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in", "i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last ==", "\"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname,", "== os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i", "import os import unittest import subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def", "for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with", "def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i))))", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last ==", "\"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6,", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\")", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname,", "test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname,", "== os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname,", "range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "== os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target = \"paper2tmb/tests/testdata/out.pdf\" m.out(target)", "i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname,", "os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12):", "m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with", "def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target = \"paper2tmb/tests/testdata/out.pdf\" m.out(target) self.assertTrue(os.path.exists(target)) subprocess.call([\"rm\", target])", "m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\"))", "range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\")", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def", "os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\")))", "self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2)", "i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "import subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as", "\"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\"))", "2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self):", "class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in", "test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last", "for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with", "as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last ==", "os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname,", "os import unittest import subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self):", "m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def", "\"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\")))", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\")))", "as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self):", "self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for", "m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def", "for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with", "paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def", "i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target = \"paper2tmb/tests/testdata/out.pdf\" m.out(target) self.assertTrue(os.path.exists(target))", "import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self):", "m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with", "in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i))))", "== os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname,", "m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last", "\"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname,", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname,", "density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self):", "m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\"))", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last ==", "for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with", "from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname))", "m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self):", "test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\")", "TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\")", "\"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname,", "density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last", "\"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last", "self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target = \"paper2tmb/tests/testdata/out.pdf\"", "self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i", "def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last ==", "in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i))))", "with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for", "as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname,", "as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\"))", "range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m:", "import unittest import subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with", "\"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\")", "def test_pdf2png_both_trim_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname,", "def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last", "test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png()", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\")", "subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m:", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname,", "self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname,", "m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"stack.png\")) def", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname,", "\"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(density=\"20\") for", "\"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4,", "Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\"))", "os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\")))", "\"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target =", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\",", "m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i in range(12):", "self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png()", "m.pdf2png() for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_trim(self):", "\"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\")", "m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self):", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"400x240\", density=\"300x300\") m.top(\"60%\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"top_60%-0.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"top_60%-0.png\"))", "in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def test_pdf2png_density(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "m.pdf2png(trim=\"300x300\", density=\"10\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last == os.path.join(m.dirname, \"pdf2png.png\")) def", "Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() for i", "def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png() m.stack(4, 2) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_0.png\"))) self.assertTrue(os.path.exists(os.path.join(m.dirname, \"stack_row_1.png\")))", "as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def", "Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf') as m: self.assertTrue(os.path.isdir(m.dirname)) def test_pdf2png(self): with", "with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x100\") for i in range(12): self.assertTrue(os.path.exists(os.path.join(m.dirname, \"pdf2png-{}.png\".format(i)))) self.assertTrue(m._last ==", "2) m.resize(\"x400\") self.assertTrue(os.path.exists(os.path.join(m.dirname, \"resize_x400.png\"))) self.assertTrue(m._last == os.path.join(m.dirname, \"resize_x400.png\")) def test_top(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as", "== os.path.join(m.dirname, \"stack.png\")) def test_stack(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: m.pdf2png(trim=\"100x60\") m.stack(6, 2) m.resize(\"x400\")", "\"top_60%-0.png\")) def test_out(self): with Manipulator(\"paper2tmb/tests/testdata/1412.6785v2.pdf\") as m: target = \"paper2tmb/tests/testdata/out.pdf\" m.out(target) self.assertTrue(os.path.exists(target)) subprocess.call([\"rm\",", "unittest import subprocess from paper2tmb.manipulator import Manipulator class TestManipulator(unittest.TestCase): def test_init(self): with Manipulator('test.pdf')" ]
[ "message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\")", "= message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname", "\"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create =", "into actual classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy to", "define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint =", "init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y} {rot})\")", "= message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x}", "# TODO(MESSAGES) Turn into actual classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes", "def message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name}", "message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y}", "message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y} {rot})\") say =", "message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1}", "message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize =", "return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint", "effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint =", "classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def", "easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\")", "message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\")", "return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return", "message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init", "{ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum", "(unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y} {rot})\") say = message_factory(\"(say", "can return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs)", "actual classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\"", "= message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init =", "= message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize", "hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init", "TODO(MESSAGES) Turn into actual classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages", "synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam", "def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message", "messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene", "= message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y} {rot})\") say", "create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\")", "return message create = message_factory(\"(scene {filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name", "to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create = message_factory(\"(scene {filename})\") hinge_joint", "parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return", "message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs): return effector_string.format(**kwargs) return message create", "Turn into actual classes the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy", "{filename})\") hinge_joint = message_factory(\"({name} {ax1})\") universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\")", "the parse_preceptors can return def message_factory(effector_string): \"\"\"Makes messages easy to define\"\"\" def message(**kwargs):", "{ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam =", "{ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber}) (teamname {teamname}))\") beam", "{playernumber}) (teamname {teamname}))\") beam = message_factory(\"(beam {x} {y} {rot})\") say = message_factory(\"(say {message})\")", "<gh_stars>1-10 # TODO(MESSAGES) Turn into actual classes the parse_preceptors can return def message_factory(effector_string):", "universal_joint = message_factory(\"({name {ax1} {ax2}})\") synchronize = message_factory(\"(syn)\") init = message_factory(\"(init (unum {playernumber})" ]
[ "Chem def mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms):", "tmp_mol def unique_mols(sequence): seen = set() return [x for x in sequence if", "def mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber',", "mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def", "atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return", "unique_mols(sequence): seen = set() return [x for x in sequence if not (tuple(x)", "return tmp_mol def unique_mols(sequence): seen = set() return [x for x in sequence", "for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set()", "tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set() return [x for x", "tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence):", "seen = set() return [x for x in sequence if not (tuple(x) in", "range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set() return [x for", "import Chem def mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in", "Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen =", "idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set() return", "rdkit import Chem def mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx", "set() return [x for x in sequence if not (tuple(x) in seen or", "mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx()))", "def unique_mols(sequence): seen = set() return [x for x in sequence if not", "from rdkit import Chem def mol_with_atom_index(mol): atoms = mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for", "return [x for x in sequence if not (tuple(x) in seen or seen.add(tuple(x)))]", "= set() return [x for x in sequence if not (tuple(x) in seen", "= Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen", "in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set() return [x", "str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol def unique_mols(sequence): seen = set() return [x for x in", "= mol.GetNumAtoms() tmp_mol = Chem.Mol(mol) for idx in range(atoms): tmp_mol.GetAtomWithIdx(idx).SetProp('molAtomMapNumber', str(tmp_mol.GetAtomWithIdx(idx).GetIdx())) return tmp_mol" ]
[ "copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict)", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import collections import copy", "Copyright (c) 2012 <NAME> # # Permission is hereby granted, free of charge,", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "= getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper", "the Software without restriction, including without limitation the rights # to use, copy,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "person obtaining a copy # of this software and associated documentation files (the", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import", "dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "_iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "v in self.__dict__.items()))) return result def __hash__(self): if self._hash is None: h =", "key): item = self._dict[key] if isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif", "item = self._dict[key] = frozendict(**item) elif isinstance(item, list): item = self._dict[key] = tuple(item)", "above copyright notice and this permission notice shall be included in # all", "can be used as a drop-in replacement for dictionaries where immutability is desired.", "self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self):", "drop-in replacement for dictionaries where immutability is desired. \"\"\" dict_cls = dict def", "is hereby granted, free of charge, to any person obtaining a copy #", "as a drop-in replacement for dictionaries where immutability is desired. \"\"\" dict_cls =", "persons to whom the Software is # furnished to do so, subject to", "h = 0 for key, value in _iteritems(self._dict): h ^= hash((key, value)) self._hash", "conditions: # # The above copyright notice and this permission notice shall be", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "in self.__dict__.items()))) return result def __hash__(self): if self._hash is None: h = 0", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "documentation files (the \"Software\"), to deal # in the Software without restriction, including", "compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that implements the complete", "the following license: # # Copyright (c) 2012 <NAME> # # Permission is", "(self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] =", "to permit persons to whom the Software is # furnished to do so,", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "notice and this permission notice shall be included in # all copies or", "of charge, to any person obtaining a copy # of this software and", "key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict)", "dict_cls = dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash =", "isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif isinstance(item, list): item = self._dict[key]", "and this permission notice shall be included in # all copies or substantial", "frozendict is originally available under the following license: # # Copyright (c) 2012", "len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls", "hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self, key): return", "def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return", "so, subject to the following conditions: # # The above copyright notice and", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that", "copy # of this software and associated documentation files (the \"Software\"), to deal", "def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self,", "__contains__(self, key): return key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def", "to the following conditions: # # The above copyright notice and this permission", "included in # all copies or substantial portions of the Software. # #", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import collections", "replacement for dictionaries where immutability is desired. \"\"\" dict_cls = dict def __init__(self,", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "**add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return '<%s", "= self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return", "The frozendict is originally available under the following license: # # Copyright (c)", "and associated documentation files (the \"Software\"), to deal # in the Software without", "(c) 2012 <NAME> # # Permission is hereby granted, free of charge, to", "is None: h = 0 for key, value in _iteritems(self._dict): h ^= hash((key,", "return key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return", "under the following license: # # Copyright (c) 2012 <NAME> # # Permission", "the complete :py:class:`collections.Mapping` interface. It can be used as a drop-in replacement for", "# SOFTWARE. import collections import copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "elif isinstance(item, set): item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item,", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "is originally available under the following license: # # Copyright (c) 2012 <NAME>", "sublicense, and/or sell # copies of the Software, and to permit persons to", "Software is # furnished to do so, subject to the following conditions: #", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "# The frozendict is originally available under the following license: # # Copyright", "item = self._dict[key] if isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif isinstance(item,", "interface. It can be used as a drop-in replacement for dictionaries where immutability", "elif isinstance(item, list): item = self._dict[key] = tuple(item) elif isinstance(item, set): item =", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "# copies of the Software, and to permit persons to whom the Software", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "return item def __contains__(self, key): return key in self._dict def copy(self, **add_or_replace): return", "= self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for", "= frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item def", "for key, value in _iteritems(self._dict): h ^= hash((key, value)) self._hash = h return", "this permission notice shall be included in # all copies or substantial portions", "It can be used as a drop-in replacement for dictionaries where immutability is", "collections import copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping):", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "software and associated documentation files (the \"Software\"), to deal # in the Software", "memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v,", "return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self):", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "list): item = self._dict[key] = tuple(item) elif isinstance(item, set): item = self._dict[key] =", "around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can be used as", "and to permit persons to whom the Software is # furnished to do", "self._dict[key] = frozendict(**item) elif isinstance(item, list): item = self._dict[key] = tuple(item) elif isinstance(item,", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the", "= self._dict[key] = tuple(item) elif isinstance(item, set): item = self._dict[key] = frozenset(item) elif", "the following conditions: # # The above copyright notice and this permission notice", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "# furnished to do so, subject to the following conditions: # # The", "the Software, and to permit persons to whom the Software is # furnished", "rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "None: h = 0 for key, value in _iteritems(self._dict): h ^= hash((key, value))", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "in # all copies or substantial portions of the Software. # # THE", "to do so, subject to the following conditions: # # The above copyright", "for dictionaries where immutability is desired. \"\"\" dict_cls = dict def __init__(self, *args,", "__repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__", "import collections import copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class", "isinstance(item, list): item = self._dict[key] = tuple(item) elif isinstance(item, set): item = self._dict[key]", "%r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls)", "def __contains__(self, key): return key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace)", "k, v in self.__dict__.items()))) return result def __hash__(self): if self._hash is None: h", "self.__dict__.items()))) return result def __hash__(self): if self._hash is None: h = 0 for", "OR OTHER DEALINGS IN THE # SOFTWARE. import collections import copy _iteritems =", "whom the Software is # furnished to do so, subject to the following", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "dictionaries where immutability is desired. \"\"\" dict_cls = dict def __init__(self, *args, **kwargs):", "__getitem__(self, key): item = self._dict[key] if isinstance(item, dict): item = self._dict[key] = frozendict(**item)", "free of charge, to any person obtaining a copy # of this software", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "= self._dict[key] if isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif isinstance(item, list):", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,", "= cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in", "dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can be used as a", "without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,", "frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface.", "is # furnished to do so, subject to the following conditions: # #", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "self._hash is None: h = 0 for key, value in _iteritems(self._dict): h ^=", "= self._dict[key] = frozendict(**item) elif isinstance(item, list): item = self._dict[key] = tuple(item) elif", "def __len__(self): return len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def", "def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls =", "to deal # in the Software without restriction, including without limitation the rights", "to any person obtaining a copy # of this software and associated documentation", "key): return key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self):", "permission notice shall be included in # all copies or substantial portions of", "result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return result def __hash__(self):", "result def __hash__(self): if self._hash is None: h = 0 for key, value", "None def __getitem__(self, key): item = self._dict[key] if isinstance(item, dict): item = self._dict[key]", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "= tuple(item) elif isinstance(item, set): item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__')", "self._dict[key] = tuple(item) elif isinstance(item, set): item = self._dict[key] = frozenset(item) elif hasattr(item,", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "OTHER DEALINGS IN THE # SOFTWARE. import collections import copy _iteritems = getattr(dict,", "# py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that implements", "= None def __getitem__(self, key): item = self._dict[key] if isinstance(item, dict): item =", "'<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__ result =", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "return len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo):", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def", "desired. \"\"\" dict_cls = dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs)", "Software, and to permit persons to whom the Software is # furnished to", "= frozendict(**item) elif isinstance(item, list): item = self._dict[key] = tuple(item) elif isinstance(item, set):", "self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item", "__len__(self): return len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self,", "__iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return '<%s %r>' %", "this software and associated documentation files (the \"Software\"), to deal # in the", "return '<%s %r>' % (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__ result", "shall be included in # all copies or substantial portions of the Software.", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "granted, free of charge, to any person obtaining a copy # of this", "return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__,", "An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can", "furnished to do so, subject to the following conditions: # # The above", "modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return '<%s %r>'", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "# Permission is hereby granted, free of charge, to any person obtaining a", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "% (self.__class__.__name__, self._dict) def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)]", "publish, distribute, sublicense, and/or sell # copies of the Software, and to permit", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "isinstance(item, set): item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'):", "be included in # all copies or substantial portions of the Software. #", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "without restriction, including without limitation the rights # to use, copy, modify, merge,", "complete :py:class:`collections.Mapping` interface. It can be used as a drop-in replacement for dictionaries", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import collections import", "# # Copyright (c) 2012 <NAME> # # Permission is hereby granted, free", "cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo))", "in the Software without restriction, including without limitation the rights # to use,", "result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return result def", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "__deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k,", "dict): item = self._dict[key] = frozendict(**item) elif isinstance(item, list): item = self._dict[key] =", "copies of the Software, and to permit persons to whom the Software is", "__hash__(self): if self._hash is None: h = 0 for key, value in _iteritems(self._dict):", "<NAME> # # Permission is hereby granted, free of charge, to any person", "used as a drop-in replacement for dictionaries where immutability is desired. \"\"\" dict_cls", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "return copy.copy(item) return item def __contains__(self, key): return key in self._dict def copy(self,", "memo)) for k, v in self.__dict__.items()))) return result def __hash__(self): if self._hash is", "self._dict) def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result", "obtaining a copy # of this software and associated documentation files (the \"Software\"),", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "'__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self, key): return key", "copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return result def __hash__(self): if self._hash", "USE OR OTHER DEALINGS IN THE # SOFTWARE. import collections import copy _iteritems", "copy.copy(item) return item def __contains__(self, key): return key in self._dict def copy(self, **add_or_replace):", "tuple(item) elif isinstance(item, set): item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or", "\"\"\" An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It", "immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can be", "and/or sell # copies of the Software, and to permit persons to whom", "available under the following license: # # Copyright (c) 2012 <NAME> # #", "# in the Software without restriction, including without limitation the rights # to", "iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._dict)", "= result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return result", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "item def __contains__(self, key): return key in self._dict def copy(self, **add_or_replace): return self.__class__(self,", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "set): item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return", "frozendict(**item) elif isinstance(item, list): item = self._dict[key] = tuple(item) elif isinstance(item, set): item", "any person obtaining a copy # of this software and associated documentation files", "# # The above copyright notice and this permission notice shall be included", "\"Software\"), to deal # in the Software without restriction, including without limitation the", "immutability is desired. \"\"\" dict_cls = dict def __init__(self, *args, **kwargs): self._dict =", "frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self,", "copyright notice and this permission notice shall be included in # all copies", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "a copy # of this software and associated documentation files (the \"Software\"), to", "deal # in the Software without restriction, including without limitation the rights #", "be used as a drop-in replacement for dictionaries where immutability is desired. \"\"\"", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "(the \"Software\"), to deal # in the Software without restriction, including without limitation", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "distribute, sublicense, and/or sell # copies of the Software, and to permit persons", "license: # # Copyright (c) 2012 <NAME> # # Permission is hereby granted,", "charge, to any person obtaining a copy # of this software and associated", "def __getitem__(self, key): item = self._dict[key] if isinstance(item, dict): item = self._dict[key] =", "item = self._dict[key] = tuple(item) elif isinstance(item, set): item = self._dict[key] = frozenset(item)", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "originally available under the following license: # # Copyright (c) 2012 <NAME> #", "hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self, key): return key in self._dict", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "to whom the Software is # furnished to do so, subject to the", "limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or", "def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict((", "elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self, key):", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "\"\"\" dict_cls = dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash", "copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED", "if isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif isinstance(item, list): item =", "*args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): item", "def __hash__(self): if self._hash is None: h = 0 for key, value in", "portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "do so, subject to the following conditions: # # The above copyright notice", "0 for key, value in _iteritems(self._dict): h ^= hash((key, value)) self._hash = h", "**add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def", "'__slots__'): return copy.copy(item) return item def __contains__(self, key): return key in self._dict def", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping`", "permit persons to whom the Software is # furnished to do so, subject", "is desired. \"\"\" dict_cls = dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args,", "Permission is hereby granted, free of charge, to any person obtaining a copy", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "**kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): item =", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "Software without restriction, including without limitation the rights # to use, copy, modify,", "getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around", "'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries", "# The above copyright notice and this permission notice shall be included in", "# of this software and associated documentation files (the \"Software\"), to deal #", "DEALINGS IN THE # SOFTWARE. import collections import copy _iteritems = getattr(dict, 'iteritems',", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "sell # copies of the Software, and to permit persons to whom the", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "= self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): item = self._dict[key] if", "# all copies or substantial portions of the Software. # # THE SOFTWARE", "2012 <NAME> # # Permission is hereby granted, free of charge, to any", "restriction, including without limitation the rights # to use, copy, modify, merge, publish,", "SOFTWARE. import collections import copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility", "self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): item = self._dict[key] if isinstance(item,", "cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items())))", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "self._hash = None def __getitem__(self, key): item = self._dict[key] if isinstance(item, dict): item", "# # Permission is hereby granted, free of charge, to any person obtaining", "all copies or substantial portions of the Software. # # THE SOFTWARE IS", "following license: # # Copyright (c) 2012 <NAME> # # Permission is hereby", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "__init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key):", "if self._hash is None: h = 0 for key, value in _iteritems(self._dict): h", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "return result def __hash__(self): if self._hash is None: h = 0 for key,", "files (the \"Software\"), to deal # in the Software without restriction, including without", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "= dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None", "item = self._dict[key] = frozenset(item) elif hasattr(item, '__dict__') or hasattr(item, '__slots__'): return copy.copy(item)", "self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): item = self._dict[key]", "the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "a drop-in replacement for dictionaries where immutability is desired. \"\"\" dict_cls = dict", "following conditions: # # The above copyright notice and this permission notice shall", "of the Software, and to permit persons to whom the Software is #", "The above copyright notice and this permission notice shall be included in #", "for k, v in self.__dict__.items()))) return result def __hash__(self): if self._hash is None:", "# Copyright (c) 2012 <NAME> # # Permission is hereby granted, free of", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "key, value in _iteritems(self._dict): h ^= hash((key, value)) self._hash = h return self._hash", "THE # SOFTWARE. import collections import copy _iteritems = getattr(dict, 'iteritems', dict.items) #", "or hasattr(item, '__slots__'): return copy.copy(item) return item def __contains__(self, key): return key in", "wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can be used", ":py:class:`collections.Mapping` interface. It can be used as a drop-in replacement for dictionaries where", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "including without limitation the rights # to use, copy, modify, merge, publish, distribute,", "IN THE # SOFTWARE. import collections import copy _iteritems = getattr(dict, 'iteritems', dict.items)", "that implements the complete :py:class:`collections.Mapping` interface. It can be used as a drop-in", "= 0 for key, value in _iteritems(self._dict): h ^= hash((key, value)) self._hash =", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "**kwargs) self._hash = None def __getitem__(self, key): item = self._dict[key] if isinstance(item, dict):", "associated documentation files (the \"Software\"), to deal # in the Software without restriction,", "self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return", "hereby granted, free of charge, to any person obtaining a copy # of", "of this software and associated documentation files (the \"Software\"), to deal # in", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "implements the complete :py:class:`collections.Mapping` interface. It can be used as a drop-in replacement", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return", "self.__class__ result = cls.__new__(cls) memo[id(self)] = result result.__dict__.update(dict(( (k, copy.deepcopy(v, memo)) for k,", "notice shall be included in # all copies or substantial portions of the", "py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An immutable wrapper around dictionaries that implements the", "(k, copy.deepcopy(v, memo)) for k, v in self.__dict__.items()))) return result def __hash__(self): if", "copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\" An", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "self._dict[key] if isinstance(item, dict): item = self._dict[key] = frozendict(**item) elif isinstance(item, list): item", "import copy _iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility class frozendict(collections.Mapping): \"\"\"", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of", "the Software is # furnished to do so, subject to the following conditions:", "subject to the following conditions: # # The above copyright notice and this", "where immutability is desired. \"\"\" dict_cls = dict def __init__(self, *args, **kwargs): self._dict" ]
[ "if current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling", "rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor:", "current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version", "'apps' in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name", "config (dict): Parsed configuration from conf/ \"\"\" rollback_all = 'all' in options.processor prefix", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "not updated') def rollback(options, config): \"\"\"Rollback the current production Lambda version(s) by 1.", "= lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen with", "# This won't happen with Terraform, but the alias could have been manually", "lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen with Terraform,", "_rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster in clusters: _rollback_production(client,", "with Terraform, but the alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing", "config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert'", "def rollback(options, config): \"\"\"Rollback the current production Lambda version(s) by 1. Args: options:", "alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of", "CONDITIONS OF ANY KIND, either express or implied. See the License for the", "$LATEST instead of a published version', function_name) return current_version = int(version) if current_version", "LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version", "rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor:", "OR CONDITIONS OF ANY KIND, either express or implied. See the License for", "OF ANY KIND, either express or implied. See the License for the specific", "back %s:production from version %d => %d', function_name, current_version, current_version - 1) try:", "to in writing, software distributed under the License is distributed on an \"AS", "the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST':", "in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader' in options.processor: _rollback_production(client, '{}_streamalert_threat_intel_downloader'.format(prefix))", "function_name): \"\"\"Rollback the production alias for the given function name.\"\"\" version = lambda_client.get_alias(", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Args: options: Argparse parsed options config (dict): Parsed configuration from conf/ \"\"\" rollback_all", "(dict): Parsed configuration from conf/ \"\"\" rollback_all = 'all' in options.processor prefix =", "Parsed configuration from conf/ \"\"\" rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix']", "won't happen with Terraform, but the alias could have been manually changed. LOGGER_CLI.error('%s:production", "not use this file except in compliance with the License. You may obtain", "governing permissions and limitations under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import", "License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "= boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or", "version', function_name) return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already", "config): \"\"\"Rollback the current production Lambda version(s) by 1. Args: options: Argparse parsed", "\"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client,", "except in compliance with the License. You may obtain a copy of the", "1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from", "FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the", "may not use this file except in compliance with the License. You may", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "= sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in options.processor:", "manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published version', function_name)", "== 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production", "\"\"\" Copyright 2017-present, Airbnb Inc. Licensed under the Apache License, Version 2.0 (the", "'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published version', function_name) return current_version", "version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name,", "from version %d => %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name,", "options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all", "current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1',", "rollback_all or 'apps' in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {})", "and limitations under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from", "options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config):", "rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor:", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback", "botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the given", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published version', function_name) return", "FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config):", "options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if", "= config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or", "= config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena'", "config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in", "Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen with Terraform, but the", "alias for the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version", "boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger'", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "the License for the specific language governing permissions and limitations under the License.", "Lambda version(s) by 1. Args: options: Argparse parsed options config (dict): Parsed configuration", "permissions and limitations under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3", "Airbnb Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def", "import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the given function", "is already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d", "ANY KIND, either express or implied. See the License for the specific language", "instead of a published version', function_name) return current_version = int(version) if current_version ==", "or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client,", "file except in compliance with the License. You may obtain a copy of", "'$LATEST': # This won't happen with Terraform, but the alias could have been", "Terraform, but the alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing to", "License for the specific language governing permissions and limitations under the License. \"\"\"", "conf/ \"\"\" rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters", "a published version', function_name) return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production", "Unless required by applicable law or agreed to in writing, software distributed under", "version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen", "return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at version", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,", "This won't happen with Terraform, but the alias could have been manually changed.", "for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client,", "2.0 (the \"License\"); you may not use this file except in compliance with", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if", "the alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead", "See the License for the specific language governing permissions and limitations under the", "%s:production from version %d => %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias(", "happen with Terraform, but the alias could have been manually changed. LOGGER_CLI.error('%s:production is", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "configuration from conf/ \"\"\" rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters", "1. Args: options: Argparse parsed options config (dict): Parsed configuration from conf/ \"\"\"", "Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not", "if version == '$LATEST': # This won't happen with Terraform, but the alias", "version %d => %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production',", "- 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the current", "to $LATEST instead of a published version', function_name) return current_version = int(version) if", "'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster", "the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", "import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias", "the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "=> %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version -", "language governing permissions and limitations under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI", "is pointing to $LATEST instead of a published version', function_name) return current_version =", "function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name, current_version, current_version", "License, Version 2.0 (the \"License\"); you may not use this file except in", "current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling back", "compliance with the License. You may obtain a copy of the License at", "int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return", "under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import", "production alias for the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if", "sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client,", "in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if", "if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in", "(the \"License\"); you may not use this file except in compliance with the", "for the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version ==", "this file except in compliance with the License. You may obtain a copy", "prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all", "for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader' in options.processor:", "or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for", "LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the current production Lambda version(s) by", "_rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or", "lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule'", "from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the", "\"License\"); you may not use this file except in compliance with the License.", "express or implied. See the License for the specific language governing permissions and", "function_name) return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at", "= int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name)", "current production Lambda version(s) by 1. Args: options: Argparse parsed options config (dict):", "the specific language governing permissions and limitations under the License. \"\"\" from stream_alert_cli.logger", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the given function name.\"\"\" version", "pointing to $LATEST instead of a published version', function_name) return current_version = int(version)", "return LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name, current_version, current_version -", "in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in", "sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all", "given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': #", "options: Argparse parsed options config (dict): Parsed configuration from conf/ \"\"\" rollback_all =", "you may not use this file except in compliance with the License. You", "if rollback_all or 'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster))", "= 'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client", "options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader' in", "the current production Lambda version(s) by 1. Args: options: Argparse parsed options config", "agreed to in writing, software distributed under the License is distributed on an", "cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader' in options.processor: _rollback_production(client,", "if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in", "updated') def rollback(options, config): \"\"\"Rollback the current production Lambda version(s) by 1. Args:", "if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in", "lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix))", "from conf/ \"\"\" rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters =", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for", "or 'apps' in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for", "options config (dict): Parsed configuration from conf/ \"\"\" rollback_all = 'all' in options.processor", "in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader'", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the", "LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production", "software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "by applicable law or agreed to in writing, software distributed under the License", "applicable law or agreed to in writing, software distributed under the License is", "implied. See the License for the specific language governing permissions and limitations under", "1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated')", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed", "could have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a", "apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License", "have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published", "lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options,", "in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster in", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This", "in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster in", "current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError:", "published version', function_name) return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is", "client = boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all", "except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the current production Lambda", "%d => %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version", "Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback", "parsed options config (dict): Parsed configuration from conf/ \"\"\" rollback_all = 'all' in", "_rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster in clusters: apps_config", "'{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster in clusters: apps_config =", "clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all", "'{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix,", "cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name)", "law or agreed to in writing, software distributed under the License is distributed", "%d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1))", "Copyright 2017-present, Airbnb Inc. Licensed under the Apache License, Version 2.0 (the \"License\");", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if", "== '$LATEST': # This won't happen with Terraform, but the alias could have", "in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda')", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix))", "already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d =>", "options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster in clusters:", "Version 2.0 (the \"License\"); you may not use this file except in compliance", "in compliance with the License. You may obtain a copy of the License", "limitations under the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions", "ClientError def _rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the given function name.\"\"\"", "the Apache License, Version 2.0 (the \"License\"); you may not use this file", "\"\"\"Rollback the current production Lambda version(s) by 1. Args: options: Argparse parsed options", "use this file except in compliance with the License. You may obtain a", "name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't", "version == '$LATEST': # This won't happen with Terraform, but the alias could", "KIND, either express or implied. See the License for the specific language governing", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "'{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps'", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use", "try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def", "rollback(options, config): \"\"\"Rollback the current production Lambda version(s) by 1. Args: options: Argparse", "1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the current production", "{}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor:", "\"\"\"Rollback the production alias for the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name,", "2017-present, Airbnb Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you", "in writing, software distributed under the License is distributed on an \"AS IS\"", "\"\"\" rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or", "_rollback_production(lambda_client, function_name): \"\"\"Rollback the production alias for the given function name.\"\"\" version =", "under the Apache License, Version 2.0 (the \"License\"); you may not use this", "the License. \"\"\" from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError", "1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name, current_version,", "or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix))", "Argparse parsed options config (dict): Parsed configuration from conf/ \"\"\" rollback_all = 'all'", "_rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or", "for the specific language governing permissions and limitations under the License. \"\"\" from", "writing, software distributed under the License is distributed on an \"AS IS\" BASIS,", "from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name):", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if", "rollback_all or 'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if", "either express or implied. See the License for the specific language governing permissions", "by 1. Args: options: Argparse parsed options config (dict): Parsed configuration from conf/", "specific language governing permissions and limitations under the License. \"\"\" from stream_alert_cli.logger import", "options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster in clusters:", "LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name, current_version, current_version - 1)", "or agreed to in writing, software distributed under the License is distributed on", "production Lambda version(s) by 1. Args: options: Argparse parsed options config (dict): Parsed", "'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or", "or 'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all", "for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client,", "- 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not", "function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except", "of a published version', function_name) return current_version = int(version) if current_version == 1:", "the production alias for the given function name.\"\"\" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion']", "ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): \"\"\"Rollback the current production Lambda version(s)", "clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in", "if rollback_all or 'apps' in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps',", "but the alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST", "version(s) by 1. Args: options: Argparse parsed options config (dict): Parsed configuration from", "Apache License, Version 2.0 (the \"License\"); you may not use this file except", "or implied. See the License for the specific language governing permissions and limitations", "FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen with Terraform, but", "with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client =", "required by applicable law or agreed to in writing, software distributed under the", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software", "rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters())", "at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d => %d',", "been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published version'," ]
[ "# assembly solver.Add(0.3 * wrenches + 0.5 * pliers <= 9000) # demand1", "def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0,", "iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) if __name__", "print('Slack steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 -", "<= 16000) print('Number of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches", "= solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables()) # constraints # steel", "molding solver.Add(1.0 * wrenches + pliers <= 21000) # assembly solver.Add(0.3 * wrenches", "demand2 solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13", "wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does not have an optimal", "ortools.linear_solver import pywraplp from ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity", "- wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does not have an", "pliers.solution_value())) else: print('The problem does not have an optimal solution.') print('Problem solved in", "wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers')", "solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 *", "print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value()", "pliers <= 27000) # molding solver.Add(1.0 * wrenches + pliers <= 21000) #", "# wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity,", "status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches", "print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) if __name__ == '__main__': main()", "pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables()) # constraints", "print('Number of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches + 0.10", "solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0,", "# pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables()) #", "wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number", "15000) # demand2 solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints()) # objective", "else: print('The problem does not have an optimal solution.') print('Problem solved in %f", "steel solver.Add(1.5 * wrenches + pliers <= 27000) # molding solver.Add(1.0 * wrenches", "pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables()) # constraints #", "21000) # assembly solver.Add(0.3 * wrenches + 0.5 * pliers <= 9000) #", "solved in %d iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound nodes' %", "constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches + 0.10 * pliers)", "solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches')", "solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value())", "* wrenches + 0.5 * pliers <= 9000) # demand1 solver.Add(wrenches <= 15000)", "(21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() +", "not have an optimal solution.') print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem", "<= 15000) # demand2 solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints()) #", "print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000", "of variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches + pliers", "demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does not have", "= solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers =", "* pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem", "assembly solver.Add(0.3 * wrenches + 0.5 * pliers <= 9000) # demand1 solver.Add(wrenches", "of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches + 0.10 *", "wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack", "print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does not have an optimal solution.')", "= pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') #", "import pywraplp from ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity =", "function solver.Maximize(0.13 * wrenches + 0.10 * pliers) status = solver.Solve() if status", "solved in %f milliseconds' % solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations())", "- (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5", "print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem solved in %d iterations' %", "problem does not have an optimal solution.') print('Problem solved in %f milliseconds' %", "== pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value())", "solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints())", "pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack", "- pliers.solution_value())) else: print('The problem does not have an optimal solution.') print('Problem solved", "print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack", "=', pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding',", "optimal solution.') print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem solved in %d", "have an optimal solution.') print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem solved", "solver.Add(1.0 * wrenches + pliers <= 21000) # assembly solver.Add(0.3 * wrenches +", "=', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches + 0.10 * pliers) status", "* wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value())))", "pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 -", "pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000", "value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 -", "print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel',", "+ pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000", "pliers <= 21000) # assembly solver.Add(0.3 * wrenches + 0.5 * pliers <=", "wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack", "<= 9000) # demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000) print('Number", "solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound", "demand2',(16000 - pliers.solution_value())) else: print('The problem does not have an optimal solution.') print('Problem", "% solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations()) print('Problem solved in %d", "from ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() #", "solver.Add(1.5 * wrenches + pliers <= 27000) # molding solver.Add(1.0 * wrenches +", "+ pliers <= 21000) # assembly solver.Add(0.3 * wrenches + 0.5 * pliers", "* pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =',", "in %d iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound nodes' % solver.nodes())", "wrenches + 0.10 * pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:')", "does not have an optimal solution.') print('Problem solved in %f milliseconds' % solver.wall_time())", "cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches =", "variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches + pliers <=", "objective function solver.Maximize(0.13 * wrenches + 0.10 * pliers) status = solver.Solve() if", "print('Slack molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 *", "0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The", "%f milliseconds' % solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations()) print('Problem solved", "print('Problem solved in %d iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound nodes'", "# constraints # steel solver.Add(1.5 * wrenches + pliers <= 27000) # molding", "# demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000) print('Number of constraints", "wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value()))", "(1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value() +", "* wrenches + pliers <= 27000) # molding solver.Add(1.0 * wrenches + pliers", "%d iterations' % solver.iterations()) print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) if", "print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value()))", "from ortools.linear_solver import pywraplp from ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP')", "27000) # molding solver.Add(1.0 * wrenches + pliers <= 21000) # assembly solver.Add(0.3", "status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =',", "an optimal solution.') print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem solved in", "wrenches + pliers <= 27000) # molding solver.Add(1.0 * wrenches + pliers <=", "9000) # demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000) print('Number of", "wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value())))", "pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value())", "solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5 *", "in %f milliseconds' % solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations()) print('Problem", "solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches + pliers <= 27000) #", "wrenches + pliers <= 21000) # assembly solver.Add(0.3 * wrenches + 0.5 *", "= solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of", "=', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5 * wrenches.solution_value() +", "(1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 *", "demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000) print('Number of constraints =',", "(27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0 *", "* wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value())))", "infinity, 'pliers') print('Number of variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5 *", "solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches + 0.10 * pliers) status =", "pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3", "+ pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000", "ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches", "= solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =',", "* pliers <= 9000) # demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <=", "milliseconds' % solver.wall_time()) print('Problem solved in %d iterations' % solver.iterations()) print('Problem solved in", "+ pliers <= 27000) # molding solver.Add(1.0 * wrenches + pliers <= 21000)", "'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables())", "pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers", "# steel solver.Add(1.5 * wrenches + pliers <= 27000) # molding solver.Add(1.0 *", "<= 27000) # molding solver.Add(1.0 * wrenches + pliers <= 21000) # assembly", "# molding solver.Add(1.0 * wrenches + pliers <= 21000) # assembly solver.Add(0.3 *", "<= 21000) # assembly solver.Add(0.3 * wrenches + 0.5 * pliers <= 9000)", "print('The problem does not have an optimal solution.') print('Problem solved in %f milliseconds'", "solver.Add(0.3 * wrenches + 0.5 * pliers <= 9000) # demand1 solver.Add(wrenches <=", "+ 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else:", "infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers", "* wrenches + pliers <= 21000) # assembly solver.Add(0.3 * wrenches + 0.5", "+ 0.10 * pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective", "solution.') print('Problem solved in %f milliseconds' % solver.wall_time()) print('Problem solved in %d iterations'", "=', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers =', pliers.solution_value()) print('Slack steel', (27000 - (1.5", "* wrenches + 0.10 * pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL:", "solver.IntVar(0.0, infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables", "# objective function solver.Maximize(0.13 * wrenches + 0.10 * pliers) status = solver.Solve()", "pywraplp from ortools.sat.python import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity()", "+ 0.5 * pliers <= 9000) # demand1 solver.Add(wrenches <= 15000) # demand2", "solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5", "wrenches + 0.5 * pliers <= 9000) # demand1 solver.Add(wrenches <= 15000) #", "molding', (21000 - (1.0 * wrenches.solution_value() + pliers.solution_value()))) print('Slack assembly',(9000 -(0.3 * wrenches.solution_value()", "-(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000", "=', solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches + pliers <= 27000)", "0.5 * pliers <= 9000) # demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers", "print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does not", "16000) print('Number of constraints =', solver.NumConstraints()) # objective function solver.Maximize(0.13 * wrenches +", "print('Number of variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches +", "solver.iterations()) print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) if __name__ == '__main__':", "# demand2 solver.Add(pliers <= 16000) print('Number of constraints =', solver.NumConstraints()) # objective function", "- (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0 * wrenches.solution_value()", "* wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 -", "main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches = solver.IntVar(0.0, infinity,", "import cp_model def main(): solver = pywraplp.Solver.CreateSolver('SCIP') infinity = solver.infinity() # wrenches wrenches", "pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack demand2',(16000 - pliers.solution_value())) else: print('The problem does", "'pliers') print('Number of variables =', solver.NumVariables()) # constraints # steel solver.Add(1.5 * wrenches", "constraints # steel solver.Add(1.5 * wrenches + pliers <= 27000) # molding solver.Add(1.0", "infinity, 'wrenches') # pliers pliers = solver.IntVar(0.0, infinity, 'pliers') print('Number of variables =',", "solver.Maximize(0.13 * wrenches + 0.10 * pliers) status = solver.Solve() if status ==", "assembly',(9000 -(0.3 * wrenches.solution_value() + 0.5 * pliers.solution_value()))) print('Slack demand1',(15000 - wrenches.solution_value())) print('Slack", "if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value =', solver.Objective().Value()) print('Wrenches =', wrenches.solution_value()) print('Pliers", "pliers <= 9000) # demand1 solver.Add(wrenches <= 15000) # demand2 solver.Add(pliers <= 16000)", "0.10 * pliers) status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print('Solution:') print('Objective value", "steel', (27000 - (1.5 * wrenches.solution_value() + pliers.solution_value()))) print('Slack molding', (21000 - (1.0", "% solver.iterations()) print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) if __name__ ==" ]
[ "views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips',", "[ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>',", "import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'),", "views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon,", "name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'),", "views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe), path('youtube_iframe/<str:youtube_id>', views.YoutubeIframe), path('vimeo_iframe/<str:vimeo_id>',", "= [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'),", "views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe,", "path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe), path('youtube_iframe/<str:youtube_id>', views.YoutubeIframe), path('vimeo_iframe/<str:vimeo_id>', views.VimeoIframe), ]", "name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe), path('youtube_iframe/<str:youtube_id>', views.YoutubeIframe), path('vimeo_iframe/<str:vimeo_id>', views.VimeoIframe),", "include from . import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'),", "path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist,", "name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe), path('youtube_iframe/<str:youtube_id>',", ". import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList,", "views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe),", "import path, include from . import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('',", "name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'),", "from django.urls import path, include from . import views urlpatterns = [ path('accounts/',", "from . import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags',", "path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe',", "path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>', views.SoundcloudIframe), path('youtube_iframe/<str:youtube_id>', views.YoutubeIframe),", "django.urls import path, include from . import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')),", "path, include from . import views urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage,", "path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload', views.UploadSon, name='UploadSon'), path('soundcloud_iframe/<str:soundcloud_id>',", "include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'),", "urlpatterns = [ path('accounts/', include('registration.backends.simple.urls')), path('', views.FrontPage, name='FrontPage'), path('tags', views.TagList, name='TagList'), path('clips', views.ClipList,", "path('tags', views.TagList, name='TagList'), path('clips', views.ClipList, name='ClipList'), path('playlist/<str:tag_title>', views.Playlist, name='Playlist'), path('subscribe', views.Subscribe, name='Subscribe'), path('upload'," ]
[ "for tok_sent in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent", "Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\";", "tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15:", "tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend)", "for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec", "in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y:", "tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in", "for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent", "range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i", "x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1:", "if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32)", "tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec = [model[w] for w in", "= gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i", "tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec = [model[w] for w", "in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for i in", "w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec = [model[w] for", "tok_y: sentvec = [model[w] for w in sent if w in model.vocab] vec_y.append(sentvec)", "= [model[w] for w in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for", "in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for", "for sent in tok_x: sentvec = [model[w] for w in sent if w", "in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) with open('conversation.pickle','w') as f:", "= [model[w] for w in sent if w in model.vocab] vec_y.append(sentvec) for tok_sent", "for sent in tok_y: sentvec = [model[w] for w in sent if w", "range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec = [model[w] for", "numpy as np from gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\");", "sentvec = [model[w] for w in sent if w in model.vocab] vec_y.append(sentvec) for", "import json import nltk import gensim import numpy as np from gensim import", "json import nltk import gensim import numpy as np from gensim import corpora,", "tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for i", "model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if", "import nltk import gensim import numpy as np from gensim import corpora, models,", "similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file)", "in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec", "in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for i in", "x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for", "gensim import numpy as np from gensim import corpora, models, similarities import pickle", "corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data", "i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec =", "model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for", "in tok_x: sentvec = [model[w] for w in sent if w in model.vocab]", "sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec = [model[w] for w in sent", "for tok_sent in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) with open('conversation.pickle','w')", "sent in tok_y: sentvec = [model[w] for w in sent if w in", "from gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin');", "vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) with open('conversation.pickle','w') as f: pickle.dump([vec_x,vec_y],f)", "gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in", "as np from gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model", "-*- import os import json import nltk import gensim import numpy as np", "if w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent", "i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in", "path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)):", "import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json');", "data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for j", "for i in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[]", "-*- coding: utf-8 -*- import os import json import nltk import gensim import", "j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[]", "sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec =", "model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec = [model[w] for w in", "gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\";", "= json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for j in", "in sent if w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend)", "tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for i", "for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in", "[model[w] for w in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent", "vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec = [model[w] for w in sent", "in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec = [model[w] for w", "w in sent if w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[]", "import numpy as np from gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep", "sentvec = [model[w] for w in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[]", "sent in tok_x: sentvec = [model[w] for w in sent if w in", "tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for", "cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for j in range(len(cor[i])): if", "coding: utf-8 -*- import os import json import nltk import gensim import numpy", "in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x:", "pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[]", "in tok_y: sentvec = [model[w] for w in sent if w in model.vocab]", "tok_x: sentvec = [model[w] for w in sent if w in model.vocab] vec_x.append(sentvec)", "in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower()))", "in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x: sentvec = [model[w]", "import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"];", "i in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[]", "tok_sent in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) with open('conversation.pickle','w') as", "w in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y:", "tok_sent in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in", "[model[w] for w in sent if w in model.vocab] vec_y.append(sentvec) for tok_sent in", "if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend)", "file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for", "range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if", "# -*- coding: utf-8 -*- import os import json import nltk import gensim", "j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)):", "for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for", "w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in", "models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data =", "vec_x=[] for sent in tok_x: sentvec = [model[w] for w in sent if", "y=[] path2=\"corpus\"; for i in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]);", "if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in tok_y: sentvec = [model[w]", "for w in sent if w in model.vocab] vec_x.append(sentvec) vec_y=[] for sent in", "tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) with", "len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for", "os import json import nltk import gensim import numpy as np from gensim", "in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y:", "os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model = gensim.models.Word2Vec.load('word2vec.bin'); path2=\"corpus\"; file=open(path2+'/conversation.json'); data = json.load(file) cor=data[\"conversations\"]; x=[] y=[]", "import os import json import nltk import gensim import numpy as np from", "nltk import gensim import numpy as np from gensim import corpora, models, similarities", "vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)):", "vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15:", "tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent in tok_x:", "vec_y=[] for sent in tok_y: sentvec = [model[w] for w in sent if", "y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower())) sentend=np.ones((300L,),dtype=np.float32) vec_x=[] for sent", "import gensim import numpy as np from gensim import corpora, models, similarities import", "vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend) for tok_sent in vec_y: tok_sent[14:]=[]", "utf-8 -*- import os import json import nltk import gensim import numpy as", "sent if w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for", "vec_y: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_y: if len(tok_sent)<15: for i in range(15-len(tok_sent)):", "range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]); tok_x=[] tok_y=[] for i in range(len(x)): tok_x.append(nltk.word_tokenize(x[i].lower())) tok_y.append(nltk.word_tokenize(y[i].lower()))", "for tok_sent in vec_x: tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for", "tok_sent[14:]=[] tok_sent.append(sentend) for tok_sent in vec_x: if len(tok_sent)<15: for i in range(15-len(tok_sent)): tok_sent.append(sentend)", "for w in sent if w in model.vocab] vec_y.append(sentvec) for tok_sent in vec_x:", "path2=\"corpus\"; for i in range(len(cor)): for j in range(len(cor[i])): if j<len(cor[i])-1: x.append(cor[i][j]); y.append(cor[i][j+1]);", "np from gensim import corpora, models, similarities import pickle os.chdir(\"D:\\semicolon\\Deep Learning\\chatbot\"); model =", "json.load(file) cor=data[\"conversations\"]; x=[] y=[] path2=\"corpus\"; for i in range(len(cor)): for j in range(len(cor[i])):" ]
[ "if len(sys.argv) <= 1: print(\"Set the number of container ID to send and", "import time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS']", "produced to indicate delivery result. Triggered by poll() or flush(). \"\"\" if err", "KeyError: print(\"The KAFKA_BROKERS environment variable needs to be set.\") exit try: KAFKA_APIKEY =", "the number of container ID to send and the event type\") NB_EVENTS =", "\"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\":", "for each message produced to indicate delivery result. Triggered by poll() or flush().", "def delivery_report(err, msg): \"\"\" Called once for each message produced to indicate delivery", "dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__ == '__main__': parseArguments() producer=prepareProducer() sendContainerEvent(producer,EVT_TYPE,NB_EVENTS)", "print(\"The KAFKA_BROKERS environment variable needs to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY']", "print(\"Set the number of container ID to send and the event type\") NB_EVENTS", "print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for", "'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx):", "except KeyError: print(\"The KAFKA_BROKERS environment variable needs to be set.\") exit try: KAFKA_APIKEY", "\"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if", "validate, events are published ''' import sys,os import time,json import signal,asyncio from confluent_kafka", "True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def", "os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume local deployment\") TOPIC_NAME", "KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume local deployment\") TOPIC_NAME = \"containers\"", "are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for each message", "or flush(). \"\"\" if err is not None: print('Message delivery failed: {}'.format(err)) else:", "number of container ID to send and the event type\") NB_EVENTS = int(sys.argv[1])", "\"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\",", "'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id':", "\"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__ == '__main__': parseArguments()", "producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\" + str(i) data", "not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition()))", "deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set the number", "\"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}}", "return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\" +", "''' import sys,os import time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer try:", "\"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush()", "TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set the number of", "delivery result. Triggered by poll() or flush(). \"\"\" if err is not None:", "\"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__ ==", "= int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err,", "published ''' import sys,os import time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer", "\"\"\" if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered", "Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs to", "set... assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <= 1:", "sys,os import time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS =", "EVT_TYPE = sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\"", "None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def", "cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr =", "1: print(\"Set the number of container ID to send and the event type\")", "err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {}", "len(sys.argv) <= 1: print(\"Set the number of container ID to send and the", "= sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called", "are published ''' import sys,os import time,json import signal,asyncio from confluent_kafka import KafkaError,", "if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to", "'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i", "\"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'),", "prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username':", "not set... assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <=", "exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not set...", "''' Trace container events to validate, events are published ''' import sys,os import", "environment variable not set... assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if", "'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer',", "sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\" + str(i) data = {\"timestamp\":", "signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The", "try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume", "data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\":", "{\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\":", "container events to validate, events are published ''' import sys,os import time,json import", "import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable", "KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs to be set.\")", "for i in range(0,idx,1): cid = \"c_\" + str(i) data = {\"timestamp\": int(time.time()),", "'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid =", "try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs to be", "int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\",", "Trace container events to validate, events are published ''' import sys,os import time,json", "100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__ == '__main__': parseArguments() producer=prepareProducer()", "ID to send and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2]", "from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS", "variable not set... assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv)", "arguments are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for each", "result. Triggered by poll() or flush(). \"\"\" if err is not None: print('Message", "delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options", "Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\" + str(i)", "= os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs to be set.\") exit", "send and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments", "str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid,", "\"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set the number of container ID", "[{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs',", "KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume local", "set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not", "'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request':", "KAFKA_BROKERS environment variable needs to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except", "the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \"", "flush(). \"\"\" if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message", "except KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume local deployment\") TOPIC_NAME =", "cid = \"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\":", "'0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for", "event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \" ,", "each message produced to indicate delivery result. Triggered by poll() or flush(). \"\"\"", "to validate, events are published ''' import sys,os import time,json import signal,asyncio from", "import sys,os import time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS", "\"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__", "import signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError:", "os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs to be set.\") exit try:", "def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\" + str(i) data =", "'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close'", "'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback':", "def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN',", "KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True,", "'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return", "'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', }", "int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err, msg):", "Triggered by poll() or flush(). \"\"\" if err is not None: print('Message delivery", "once for each message produced to indicate delivery result. Triggered by poll() or", "\"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\":", "{}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = {", "container ID to send and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE =", "\"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data)", "{\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr", "in range(0,idx,1): cid = \"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType,", "'/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' :", ": False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in", "to indicate delivery result. Triggered by poll() or flush(). \"\"\" if err is", "= {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\",", "time,json import signal,asyncio from confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except", ", str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for each message produced to", "KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment variable needs", "be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable", "+ str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\":", "variable needs to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The", "False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1):", "parseArguments(): if len(sys.argv) <= 1: print(\"Set the number of container ID to send", "\"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report) producer.flush() if __name__ == '__main__':", "{} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location':", "events to validate, events are published ''' import sys,os import time,json import signal,asyncio", "<= 1: print(\"Set the number of container ID to send and the event", "NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def", "\"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\": 100}} dataStr = json.dumps(data) producer.produce(TOPIC_NAME,dataStr.encode('utf-8'), callback=delivery_report)", "needs to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY", "str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for each message produced to indicate", "producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token',", "} return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid = \"c_\"", "to send and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The", "= os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment variable not set... assume local deployment\")", "KAFKA_APIKEY environment variable not set... assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments():", "indicate delivery result. Triggered by poll() or flush(). \"\"\" if err is not", "to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL',", "'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1',", "confluent_kafka import KafkaError, Consumer try: KAFKA_BROKERS = os.environ['KAFKA_BROKERS'] except KeyError: print(\"The KAFKA_BROKERS environment", "delivery_report(err, msg): \"\"\" Called once for each message produced to indicate delivery result.", "print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS,", "def parseArguments(): if len(sys.argv) <= 1: print(\"Set the number of container ID to", "{ 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>,", "assume local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set", "= \"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set the number of container", "'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options) def sendContainerEvent(producer,eventType,idx): for i in range(0,idx,1): cid", "is not None: print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(),", "type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are: \" , str(sys.argv))", "message produced to indicate delivery result. Triggered by poll() or flush(). \"\"\" if", "\"\"\" Called once for each message produced to indicate delivery result. Triggered by", "else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers':", "'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password': <PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False,", "range(0,idx,1): cid = \"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\",", "poll() or flush(). \"\"\" if err is not None: print('Message delivery failed: {}'.format(err))", "= { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'token', 'sasl.password':", "by poll() or flush(). \"\"\" if err is not None: print('Message delivery failed:", "i in range(0,idx,1): cid = \"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\":", "print(\"The KAFKA_APIKEY environment variable not set... assume local deployment\") TOPIC_NAME = \"containers\" def", "local deployment\") TOPIC_NAME = \"containers\" def parseArguments(): if len(sys.argv) <= 1: print(\"Set the", "sys.argv[2] print(\"The arguments are: \" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once", "print('Message delivery failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer():", "\"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid, \"payload\":", "msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol': 'SASL_SSL', 'ssl.ca.location': '/etc/ssl/certs', 'sasl.mechanisms':", "events are published ''' import sys,os import time,json import signal,asyncio from confluent_kafka import", "delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options = { 'bootstrap.servers': KAFKA_BROKERS, 'security.protocol':", "of container ID to send and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE", "and the event type\") NB_EVENTS = int(sys.argv[1]) EVT_TYPE = sys.argv[2] print(\"The arguments are:", "cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\", \"brand\": \"brand-reefer\", \"capacity\":", "Called once for each message produced to indicate delivery result. Triggered by poll()", "'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer( producer_options)", "msg): \"\"\" Called once for each message produced to indicate delivery result. Triggered", "environment variable needs to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError:", "<PASSWORD>, 'api.version.request': True, 'broker.version.fallback': '0.10.2.1', 'log.connection.close' : False, 'client.id': 'kafka-python-container-test-producer', } return Producer(", "eventType, \"version\":\"1\", \"containerID\": cid, \"payload\": {\"containerID\": cid, \"type\": \"Reefer\", \"status\": \"atDock\", \"city\": \"Oakland\",", "failed: {}'.format(err)) else: print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition())) def prepareProducer(): producer_options =", "to be set.\") exit try: KAFKA_APIKEY = os.environ['KAFKA_APIKEY'] except KeyError: print(\"The KAFKA_APIKEY environment", "= \"c_\" + str(i) data = {\"timestamp\": int(time.time()), \"type\": eventType, \"version\":\"1\", \"containerID\": cid,", "\" , str(sys.argv)) def delivery_report(err, msg): \"\"\" Called once for each message produced" ]
[ "Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings", "__tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name = Column('product_name', String,", "model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name =", "primary_key = True) product_name = Column('product_name', String, nullable = True) brand = Column('brand',", "import create_engine, Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import", "CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key", "\"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name = Column('product_name', String, nullable =", "db_connect(): \"\"\" Performs database connection using settings from settings.py. Returns sqlalchemy engine instance.", "Column(Integer, primary_key = True) product_name = Column('product_name', String, nullable = True) brand =", "database connection using settings from settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE))", "= True) product_name = Column('product_name', String, nullable = True) brand = Column('brand', String,", "String, nullable = True) price_high = Column('price_high', Numeric(10, 2), nullable = True) price_low", "from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def", "sqlalchemy import create_engine, Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url", "import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine):", "settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection", "DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using settings from settings.py. Returns sqlalchemy", "settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices", "engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__", "class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer,", "= True) brand = Column('brand', String, nullable = True) price_high = Column('price_high', Numeric(10,", "\"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key =", "String, nullable = True) brand = Column('brand', String, nullable = True) price_high =", "= declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using settings", "Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase =", "<filename>scrapers/competitor_prices/models.py from sqlalchemy import create_engine, Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base", "Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import", "Performs database connection using settings from settings.py. Returns sqlalchemy engine instance. \"\"\" return", "URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs", "DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using", "price_high = Column('price_high', Numeric(10, 2), nullable = True) price_low = Column('price_low', Numeric(10, 2),", "sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def", "Column('product_name', String, nullable = True) brand = Column('brand', String, nullable = True) price_high", "= Column('brand', String, nullable = True) price_high = Column('price_high', Numeric(10, 2), nullable =", "create_engine, Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL", "from sqlalchemy import create_engine, Column, Integer, String, Numeric from sqlalchemy.ext.declarative import declarative_base from", "settings from settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\"", "instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ =", "= Column('product_name', String, nullable = True) brand = Column('brand', String, nullable = True)", "True) product_name = Column('product_name', String, nullable = True) brand = Column('brand', String, nullable", "Column('price_high', Numeric(10, 2), nullable = True) price_low = Column('price_low', Numeric(10, 2), nullable =", "nullable = True) brand = Column('brand', String, nullable = True) price_high = Column('price_high',", "create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id =", "sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect():", "\"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\"", "Column('brand', String, nullable = True) price_high = Column('price_high', Numeric(10, 2), nullable = True)", "\"\"\" Performs database connection using settings from settings.py. Returns sqlalchemy engine instance. \"\"\"", "product_name = Column('product_name', String, nullable = True) brand = Column('brand', String, nullable =", "True) brand = Column('brand', String, nullable = True) price_high = Column('price_high', Numeric(10, 2),", "product_id = Column(Integer, primary_key = True) product_name = Column('product_name', String, nullable = True)", "declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine)", "declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using settings from", "from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base()", "String, Numeric from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase", "return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id", "= \"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name = Column('product_name', String, nullable", "Numeric(10, 2), nullable = True) price_low = Column('price_low', Numeric(10, 2), nullable = True)", "\"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name = Column('product_name',", "def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using settings from settings.py.", "from settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy", "nullable = True) price_high = Column('price_high', Numeric(10, 2), nullable = True) price_low =", "= Column('price_high', Numeric(10, 2), nullable = True) price_low = Column('price_low', Numeric(10, 2), nullable", "connection using settings from settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class", "brand = Column('brand', String, nullable = True) price_high = Column('price_high', Numeric(10, 2), nullable", "Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model", "def db_connect(): \"\"\" Performs database connection using settings from settings.py. Returns sqlalchemy engine", "True) price_high = Column('price_high', Numeric(10, 2), nullable = True) price_low = Column('price_low', Numeric(10,", "= Column(Integer, primary_key = True) product_name = Column('product_name', String, nullable = True) brand", "import URL import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\"", "= True) price_high = Column('price_high', Numeric(10, 2), nullable = True) price_low = Column('price_low',", "sqlalchemy competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key = True)", "competitor_prices model \"\"\" __tablename__ = \"competitor_prices\" product_id = Column(Integer, primary_key = True) product_name", "import settings DeclarativeBase = declarative_base() def create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database", "create_competitor_prices_table(engine): DeclarativeBase.metadata.create_all(engine) def db_connect(): \"\"\" Performs database connection using settings from settings.py. Returns", "using settings from settings.py. Returns sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase):", "sqlalchemy engine instance. \"\"\" return create_engine(URL(**settings.DATABASE)) class CompetitorPrices(DeclarativeBase): \"\"\" sqlalchemy competitor_prices model \"\"\"" ]
[ "goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\",", "= pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 -", "= pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 -", "if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\")", "x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2", "start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs)", "x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1)", "print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df,", "next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs),", "float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 -", "segs): x = inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf))", "return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return", "x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] =", "(x3 - x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x =", "sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return", "x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 - x2) return", "= (x - x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def", "= inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] =", "targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs)", "col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1", "col, segs, posn): x = inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3", "col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return", "& (x<x3)] = (x3 - x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col,", "segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\", segs, 3),", "return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end],", "\"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\", segs, 3), gimme_ending_affect(df, \"x\",", "inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf))", "& (x<x2)] = (x - x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col,", "inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1", "\"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc =", "segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\",", "pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 =", "start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs)", "na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end):", "= float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x", "(x<x3)] = (x3 - x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs):", "segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next =", "util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[0]) x2 =", "return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def", "sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func", "= (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3", "\"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df,", "print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc,", "affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf,", "util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[0]) x2", "x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1)", "na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar))", "gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col]", "def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def", "segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3):", "x1 = float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1)", "affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 - x1) return", "(x<x2)] = (x2 - x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs,", "(x - x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x):", "gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def", "gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x):", "x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[-2])", "pandas as pd import numpy as np import math import util def gimme_pseudo_winsors(inputDf,", "util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x", "print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs,", "col, segs): x = inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness =", "return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[-2]) x2", "in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end)", "= float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2", "gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness", "def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return", "def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1 = float(segs[posn-1]) x2 =", "segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\",", "= float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 -", "- x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return", "1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 - x1) return sum(affectedness) def", "def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar,", "= pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) &", "optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs)", "segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\", segs, 3), gimme_ending_affect(df, \"x\", segs)])", "= 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 - x1) return sum(affectedness)", "& (x<x2)] = (x2 - x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col,", "== \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end)", "(x<x2)] = (x - x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar):", "(x2 - x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x", "def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func", "x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col]", "as np import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3)", "= float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) &", "__name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start,", "posn): x = inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1])", "pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1)", "col, segs): x = inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness =", "affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] =", "gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))}", "{\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs =", "x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] =", "as pd import numpy as np import math import util def gimme_pseudo_winsors(inputDf, col,", "pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)]", "affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2)", "segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf,", "len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end", "optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs)", "float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)]", "= (x2 - x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn):", "x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1 =", "util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\",", "affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2", "= inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness =", "- x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 - x2) return sum(affectedness)", "segs, posn): x = inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 =", "= 1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) return sum(affectedness)", "affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf,", "gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc", "sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x):", "dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen", "numpy as np import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3),", "float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)]", "gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf,", "= inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] =", "= gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end)", "return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1)", "- x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col]", "start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1),", "end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\",", "= float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x", "return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[0])", "pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct", "print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\",", "goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs,", "(x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 -", "if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end)", "x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x])", "[start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt,", "gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i", "\"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in", "import pandas as pd import numpy as np import math import util def", "segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x],", "- x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 - x2)", "def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def", "return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct =", "(x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 -", "import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs):", "def gimme_starting_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[0]) x2 = float(segs[1])", "affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf,", "\"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5", "sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1 = float(segs[posn-1]) x2", "col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if", "return pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end =", "float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1)", "def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\":", "- x)/(x2 - x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x =", "return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return", "gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func", "x = inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness", "df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start]", "affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2", "segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start,", "gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness", "- x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col,", "col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct)", "import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf,", "end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if", "def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1])", "math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col,", "x1)/(x2 - x1) return sum(affectedness) def gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf,", "= [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc,", "gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\", segs, 3), gimme_ending_affect(df,", "end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__ ==", "segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2),", "= util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc =", "print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df,", "pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x2 - x)/(x2 - x1)", "return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1 = float(segs[posn-1])", "= {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs", "segs = [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next =", "float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) & (x<x2)] = (x -", "print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start,", "end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df,", "targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3))", "sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 = float(segs[-2]) x2 =", "\"x\", segs), gimme_normie_affect(df, \"x\", segs, 1), gimme_normie_affect(df, \"x\", segs, 2), gimme_normie_affect(df, \"x\", segs,", "x = inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)]", "import numpy as np import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return", "col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col,", "segs): x = inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf))", "gimme_sa_optimizing_func(inputDf, col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf,", "inputDf[col] x1 = float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1", "float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x -", "gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs)", "np import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def", "next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc", "pd import numpy as np import math import util def gimme_pseudo_winsors(inputDf, col, pw=0.05):", "= float(segs[-2]) x2 = float(segs[-1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) &", "segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col, segsSoFar):", "def gimme_pseudo_winsors(inputDf, col, pw=0.05): return util.round_to_sf(inputDf[col].quantile(pw),3), util.round_to_sf(inputDf[col].quantile(1-pw),3) def gimme_starting_affect(inputDf, col, segs): x =", "col, segsSoFar): def sa_optimizing_func(x): return gimme_starting_affect(inputDf, col, segsSoFar+[x]) return sa_optimizing_func def gimme_na_optimizing_func(inputDf, col,", "affectedness.loc[(x>=x2)] = 1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) return", "pa_optimizing_func if __name__ == \"__main__\": dyct = {\"x\":list(range(100))} df=pd.DataFrame(dyct) start, end = gimme_pseudo_winsors(df,", "= gimme_pseudo_winsors(df, \"x\") print(start, end) targetLen=5 goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2:", "range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3))", "& (x<x2)] = (x - x1)/(x2 - x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3", "segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x]+[end], len(segsSoFar)) return pa_optimizing_func if __name__", "= gimme_sa_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for", "x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1", "segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col,", "= (x3 - x)/(x3 - x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x", "= float(segs[posn-1]) x2 = float(segs[posn]) x3 = float(segs[posn+1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x>=x1) &", "end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next", "util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df,", "- x2) return sum(affectedness) def gimme_ending_affect(inputDf, col, segs): x = inputDf[col] x1 =", "gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1 = float(segs[posn-1]) x2 = float(segs[posn])", "goodAmt=float(len(df))/targetLen segs = [start] print(segs) if targetLen>2: optFunc = gimme_sa_optimizing_func(df, \"x\", segs) next", "- x1) return sum(affectedness) def gimme_normie_affect(inputDf, col, segs, posn): x = inputDf[col] x1", "x1) affectedness.loc[(x>=x2) & (x<x3)] = (x3 - x)/(x3 - x2) return sum(affectedness) def", "col, segsSoFar): def na_optimizing_func(x): return gimme_normie_affect(inputDf, col, segsSoFar+[x], len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf,", "i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt, start,", "x = inputDf[col] x1 = float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)]", "1 affectedness.loc[(x>=x1) & (x<x2)] = (x - x1)/(x2 - x1) return sum(affectedness) def", "for i in range(targetLen-3): optFunc = gimme_na_optimizing_func(df, \"x\", segs) next = util.target_input_with_output(optFunc, goodAmt,", "x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)] =", "len(segsSoFar)-1) return na_optimizing_func def gimme_pa_optimizing_func(inputDf, col, segsSoFar, end): def pa_optimizing_func(x): return gimme_normie_affect(inputDf, col,", "float(segs[0]) x2 = float(segs[1]) affectedness = pd.Series([0]*len(inputDf)) affectedness.loc[(x<x1)] = 1 affectedness.loc[(x>=x1) & (x<x2)]", "= util.target_input_with_output(optFunc, goodAmt, start, end) segs.append(util.round_to_sf(next,3)) print(segs) segs.append(end) print(segs) print([gimme_starting_affect(df, \"x\", segs), gimme_normie_affect(df," ]
[ "results = pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff,", "dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list = [] _ts = time_series.copy() for", "in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter(", "np.arange(3) + 1, window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", )", "IPython.display import display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list,", "pd.DataFrame: _df_list = [] for cutoff in cutoffs: _ts = time_series.copy() for fcaster_name,", "for cutoff in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for", "pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index >", "\"\"\"Evaluation Functions\"\"\" import pandas as pd import numpy as np from sktime.forecasting.model_evaluation import", "deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <= cutoff)", "(_panel_df.index <= cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date = cutoff", "list, forecaster, metric, fh: np.array = np.arange(3) + 1, window_length: int = 5", "int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ] #", "= panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff", "pred_df = _forecaster.predict(fh=fh) # loop over regions to get region level metrics and", "copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict,", "== ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts,", "ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred, }, ignore_index=True,", "= pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] ==", "get region level metrics and y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col]", "1 train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff - window_length)", "results = results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\":", "_forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index", "(_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ] # if forecaster doesn't need", "fh: np.array = np.arange(3) + 1, window_length: int = 5 * 52, freq=\"W-SUN\",", ">= min_test_date) & (_panel_df.index <= max_test_date) ] # if forecaster doesn't need fh", "Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame:", "time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3) +", "for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] ==", "evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict:", "evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3)", "scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df)", "need fh in fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh)", "= 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy()", "cutoff = pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <= cutoff) &", "from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, )", "-> pd.DataFrame: _df_list = [] _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items():", "return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\",", "_df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\",", "dict, metrics_dict: dict, fh: np.array = np.arange(3) + 1, window_length: int = 5", "ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list = []", "np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter,", "\"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred, }, ignore_index=True, )", "import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from IPython.display", "( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from IPython.display import", "as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter,", "from typing import Union from IPython.display import display from copy import deepcopy def", "metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df =", "for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df =", "+ int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ]", "= deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <=", "= fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def", "= _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"],", "window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df", "cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3) + 1, window_length:", "from IPython.display import display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs:", "df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s", "sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from", "SingleWindowSplitter, ) from typing import Union from IPython.display import display from copy import", "cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric,", "pd.DataFrame: _df_list = [] _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for", "int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) &", "def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array = np.arange(3) +", "pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3) + 1,", "cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv,", "time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict,", "fh in fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) #", "panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array = np.arange(3) + 1, window_length:", "+ int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date)", "test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train)", "# if forecaster doesn't need fh in fit fh will be ignored. _forecaster.fit(train_df,", ") -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results", "SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from IPython.display import display from", "= results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test,", "import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh:", "cutoff - window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff +", "in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric", "= [] for cutoff in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in", "_panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ] # if forecaster doesn't", "cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df =", "(_panel_df.index <= max_test_date) ] # if forecaster doesn't need fh in fit fh", "deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array", "to get region level metrics and y_preds for ts in ts_list: _pred =", "cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, )", "target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique())", "pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) +", "cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred, }, ignore_index=True, ) return", "list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff =", "_df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name", "(_panel_df.index > cutoff - window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date =", "return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ],", "time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster =", "= _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date", "metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv,", "props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh:", "ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target]", "evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] =", "> cutoff - window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff", "= evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"]", "y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score,", "= 5 * 52, ) -> pd.DataFrame: _df_list = [] for cutoff in", "= test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred,", "_panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for", "_panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs:", "for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1", "int = 5 * 52, ) -> pd.DataFrame: _df_list = [] for cutoff", "] # if forecaster doesn't need fh in fit fh will be ignored.", "test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ] # if", "= _forecaster.predict(fh=fh) # loop over regions to get region level metrics and y_preds", "forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv =", "window_length: int = 5 * 52, ) -> pd.DataFrame: _df_list = [] for", "train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index()", "_df_list = [] _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name,", "y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df", "will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions to", "== ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score", "and y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test =", "results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster,", "ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list =", "metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length,", "pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\",", "metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster,", "_pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col]", "freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff", "fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions", "metric, fh: np.array = np.arange(3) + 1, window_length: int = 5 * 52,", "_forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate(", "Functions\"\"\" import pandas as pd import numpy as np from sktime.forecasting.model_evaluation import evaluate", "= train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( {", "52, ) -> pd.DataFrame: _df_list = [] for cutoff in cutoffs: _ts =", "_df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list)", "props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df:", "], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list = [] _ts =", ") _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] =", "\"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s ==", "_test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test,", "metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, )", "be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions to get", "= time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster", "_df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results =", "metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name,", "def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\")", "ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred, },", "evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array = np.arange(3) + 1,", "def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min,", "fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv", "- window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh))", "numpy as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter,", "cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) ->", "pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame()", "props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis", "1, window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame:", "in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df", ") display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array =", "<= cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date = cutoff +", "CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True,", "\"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter,", "\"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results", "_df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[", "\"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred, }, ignore_index=True, ) return results", "cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh))", "pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index()", "& (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date", "+ 1, window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) ->", "sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from", "typing import Union from IPython.display import display from copy import deepcopy def evaluate_forecasters_on_cutoffs(", "display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict,", "ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score =", "= metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results", "forecaster doesn't need fh in fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df", "= deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True,", "_train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append(", "== ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results", "ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from IPython.display import display from copy", "\"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame,", "= cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <=", "np.arange(3) + 1, window_length: int = 5 * 52, ) -> pd.DataFrame: _df_list", "5 * 52, ) -> pd.DataFrame: _df_list = [] for cutoff in cutoffs:", ") _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return", "ts][target] _train = train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results =", "= results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\")", "region level metrics and y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] ==", "axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s,", "[] for cutoff in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items():", "metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv:", "dict, fh: np.array = np.arange(3) + 1, window_length: int = 5 * 52,", "int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df =", ") -> pd.DataFrame: _df_list = [] for cutoff in cutoffs: _ts = time_series.copy()", "<reponame>ltsaprounis/dsf-ts-forecasting \"\"\"Evaluation Functions\"\"\" import pandas as pd import numpy as np from sktime.forecasting.model_evaluation", "in fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop", "ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\":", "fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, )", "if forecaster doesn't need fh in fit fh will be ignored. _forecaster.fit(train_df, fh=fh)", "for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster)", "min_test_date) & (_panel_df.index <= max_test_date) ] # if forecaster doesn't need fh in", "= metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series,", "forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]),", "deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts,", "level metrics and y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"]", "& (_panel_df.index <= max_test_date) ] # if forecaster doesn't need fh in fit", "return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"})", "window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"]", "metrics and y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test", ") from typing import Union from IPython.display import display from copy import deepcopy", "import Union from IPython.display import display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series:", "_panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff - window_length) ].sort_index() min_test_date =", "== np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def", "+ 1 train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index > cutoff -", "metrics_dict: dict, ) -> pd.DataFrame: _df_list = [] _ts = time_series.copy() for fcaster_name,", "in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df =", "_forecaster.predict(fh=fh) # loop over regions to get region level metrics and y_preds for", "fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df,", "doesn't need fh in fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df =", "_forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions to get region level", "<= max_test_date) ] # if forecaster doesn't need fh in fit fh will", "pandas as pd import numpy as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection", "= [] _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric", "= np.arange(3) + 1, window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\",", "_df_list = [] for cutoff in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster", "np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs(", "_panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs: _forecaster =", "fit fh will be ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over", "= _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date) ] # if forecaster", "SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list =", "from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict:", "display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def", "y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\":", "np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results)", "forecaster, metric, fh: np.array = np.arange(3) + 1, window_length: int = 5 *", "# loop over regions to get region level metrics and y_preds for ts", "cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in", "strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\":", "import numpy as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter,", "as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values),", "highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric,", "np.array = np.arange(3) + 1, window_length: int = 5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\",", "in forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv)", "forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list = [] _ts = time_series.copy()", "{ ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\": _pred,", "over regions to get region level metrics and y_preds for ts in ts_list:", "* 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df =", "ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train =", "_forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\",", "pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, )", "= pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[ (_panel_df.index <= cutoff) & (_panel_df.index", "= deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"]", "= list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff", "cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df", "results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results", "= _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs: _forecaster", "cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index <= max_test_date)", "freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list", "metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate(", "forecasters_dict.items(): for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df", "_df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter,", "metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results =", "loop over regions to get region level metrics and y_preds for ts in", "cutoffs: list, forecaster, metric, fh: np.array = np.arange(3) + 1, window_length: int =", "fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions to get region level metrics", "forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3) + 1, window_length: int =", "results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs:", "regions to get region level metrics and y_preds for ts in ts_list: _pred", "in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col] == ts][target] _train", "ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster)", "fcaster_name _df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters(", "CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union from IPython.display import display", "-> pd.DataFrame: _df_list = [] for cutoff in cutoffs: _ts = time_series.copy() for", "_df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter,", "ignored. _forecaster.fit(train_df, fh=fh) pred_df = _forecaster.predict(fh=fh) # loop over regions to get region", "min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[", "= np.arange(3) + 1, window_length: int = 5 * 52, ) -> pd.DataFrame:", "def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict,", "_df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series:", "as pd import numpy as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import", "results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"):", "_df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0): results = df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean()", "forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] = fcaster_name _df[\"Metric\"] = metric_name", "= df.groupby([\"Forecaster\", \"Metric\"], as_index=False)[\"Score\"].mean() results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return", "results = results.pivot(index=\"Forecaster\", columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props,", "score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\": cutoff,", "from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import Union", "= pd.DataFrame() for cutoff in cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq)", "panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results = pd.DataFrame() for cutoff in", "train_df[train_df[ts_id_col] == ts][target].sort_index() score = metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col:", "highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\",", "_ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in metrics_dict.items():", "import display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict:", "CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list", "import evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing", "_df[\"Metric\"] = metric_name _df = _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def display_results(df, axis=0):", "dict, ) -> pd.DataFrame: _df_list = [] _ts = time_series.copy() for fcaster_name, forecaster", "].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df =", "5 * 52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df", "in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts,", "np.array = np.arange(3) + 1, window_length: int = 5 * 52, ) ->", "fh: np.array = np.arange(3) + 1, window_length: int = 5 * 52, )", "values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply(", "axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array", "cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >=", "* 52, ) -> pd.DataFrame: _df_list = [] for cutoff in cutoffs: _ts", "= metric(y_true=_test, y_pred=_pred, y_train=_train) results = results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\":", "= cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index", "max_test_date) ] # if forecaster doesn't need fh in fit fh will be", "max_test_date = cutoff + int(np.max(fh)) test_df = _panel_df[ (_panel_df.index >= min_test_date) & (_panel_df.index", "= deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster,", "columns=\"Metric\", values=\"Score\") def highlight_min(s, props=\"\"): return np.where(s == np.nanmin(s.values), props, \"\") results =", ") -> pd.DataFrame: _df_list = [] _ts = time_series.copy() for fcaster_name, forecaster in", "deepcopy(forecaster) cv = deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric,", "-> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index() ts_list = list(panel_df[ts_id_col].unique()) results =", "SingleWindowSplitter, ], forecasters_dict: dict, metrics_dict: dict, ) -> pd.DataFrame: _df_list = [] _ts", "pd import numpy as np from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import (", "pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ], forecasters_dict:", "deepcopy(cv) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\", return_data=True, scoring=metric, ) _df[\"Forecaster\"] =", "def evaluate_forecasters_on_cutoffs( time_series: pd.Series, cutoffs: list, forecasters_dict: dict, metrics_dict: dict, fh: np.array =", "cutoffs: _forecaster = deepcopy(forecaster) cutoff = pd.Period(cutoff, freq=freq) + 1 train_df = _panel_df[", "return np.where(s == np.nanmin(s.values), props, \"\") results = results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis )", "for metric_name, metric in metrics_dict.items(): _forecaster = deepcopy(forecaster) cv = CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh,", "metrics_dict: dict, fh: np.array = np.arange(3) + 1, window_length: int = 5 *", "+ 1, window_length: int = 5 * 52, ) -> pd.DataFrame: _df_list =", "= CutoffSplitter( cutoffs=np.array([cutoff]), fh=fh, window_length=window_length, ) _df = evaluate( forecaster=_forecaster, y=_ts, cv=cv, strategy=\"refit\",", "list, forecasters_dict: dict, metrics_dict: dict, fh: np.array = np.arange(3) + 1, window_length: int", "Union from IPython.display import display from copy import deepcopy def evaluate_forecasters_on_cutoffs( time_series: pd.Series,", "1, window_length: int = 5 * 52, ) -> pd.DataFrame: _df_list = []", "window_length) ].sort_index() min_test_date = cutoff + int(np.min(fh)) max_test_date = cutoff + int(np.max(fh)) test_df", "= results.applymap(\"{:,.2f}\".format).style.apply( highlight_min, props=\"color:white;background-color:purple\", axis=axis ) display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list,", "y_preds for ts in ts_list: _pred = pred_df[pred_df[ts_id_col] == ts][\"y_pred\"] _test = test_df[test_df[ts_id_col]", "cutoff in cutoffs: _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name,", "display(results) def evaluate_panel_forecaster_on_cutoffs( panel_df: pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array = np.arange(3)", "evaluate from sktime.forecasting.model_selection import ( CutoffSplitter, SlidingWindowSplitter, ExpandingWindowSplitter, SingleWindowSplitter, ) from typing import", "results.append( { ts_id_col: ts, \"cutoff\": cutoff, \"Metric\": metric.name, \"Score\": score, \"y_test\": _test, \"y_pred\":", "[] _ts = time_series.copy() for fcaster_name, forecaster in forecasters_dict.items(): for metric_name, metric in", "import pandas as pd import numpy as np from sktime.forecasting.model_evaluation import evaluate from", "pd.DataFrame, cutoffs: list, forecaster, metric, fh: np.array = np.arange(3) + 1, window_length: int", "52, freq=\"W-SUN\", ts_id_col=\"REGION\", target=\"ILITOTAL\", ) -> pd.DataFrame: _panel_df = panel_df.copy() _panel_df = _panel_df.sort_values(by=[ts_id_col]).sort_index()", "= _df.rename(columns={f\"test_{metric.name}\": \"Score\"}) _df_list.append(_df) return pd.concat(_df_list) def evaluate_forecasters( time_series: pd.Series, cv: Union[ CutoffSplitter," ]
[ "def test_new_user_email_normalized(self): \"\"\"test the email for a new user is normilized\"\"\" email =", "\"\"\"test the email for a new user is normilized\"\"\" email = '<EMAIL>' user", "the email for a new user is normilized\"\"\" email = '<EMAIL>' user =", "from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with", "\"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self):", "self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None,", "\"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test", "with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user =", "email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test", "\"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password,", "the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new", "a new user is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, )", "get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\"", "password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password)", "test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser( '<EMAIL>', 'test123', ) self.assertTrue(user.is_superuser)", "= get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is", "test_new_user_email_normalized(self): \"\"\"test the email for a new user is normilized\"\"\" email = '<EMAIL>'", "email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with", "email = \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email,", "email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for", "= '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if", "from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test", "invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user", "email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for a new user is", "= \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email)", "user with an email is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user", "is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def", "with an email is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user =", "user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email", "an email is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user(", "is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\"", "for a new user is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email,", "self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser(", "= get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the", "email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12')", "successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, )", "import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email", ") self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for a new", "TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user", "email for a new user is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user(", "def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser( '<EMAIL>', 'test123', )", "is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password,", "import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new", "user is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower())", "password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for a", "'<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the", "def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def", "test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self):", "new user with an email is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\"", "\"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser( '<EMAIL>', 'test123', ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)", "password) def test_new_user_email_normalized(self): \"\"\"test the email for a new user is normilized\"\"\" email", "django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an", "creating new user with an email is successful\"\"\" email = \"<EMAIL>\" password =", "normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self):", "email is successful\"\"\" email = \"<EMAIL>\" password = \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email,", "user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test", "ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email is successful\"\"\" email", "get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser( '<EMAIL>',", "class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email is successful\"\"\"", "get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email is", "django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): \"\"\"Test creating", "self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for a new user", ") self.assertEqual(user.email, email.lower()) def test_new_user_email_invalid(self): \"\"\"test if the email is invalid\"\"\" with self.assertRaises(ValueError):", "if the email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create", "= \"<PASSWORD>\" user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def", "<reponame>georgecretu26/recipe-app-api from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self):", "'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super user\"\"\" user = get_user_model().objects.create_superuser( '<EMAIL>', 'test123',", "get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email", "\"\"\"Test creating new user with an email is successful\"\"\" email = \"<EMAIL>\" password", "new user is normilized\"\"\" email = '<EMAIL>' user = get_user_model().objects.create_user( email=email, ) self.assertEqual(user.email,", "email is invalid\"\"\" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'asdqw12') def test_create_new_super_user(self): \"\"\"Test create new super", "test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email is successful\"\"\" email = \"<EMAIL>\"", "def test_create_user_with_email_successful(self): \"\"\"Test creating new user with an email is successful\"\"\" email =", "self.assertTrue(user.check_password, password) def test_new_user_email_normalized(self): \"\"\"test the email for a new user is normilized\"\"\"" ]
[ "mnist import tensorflow_datasets as tfds from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D,", "# Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train", "as tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss,", "activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5 loss_fn =", "32 # Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache()", "ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE)", "layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from tensorflow.keras import", "(x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result()", "= ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting", "batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc =", "up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE)", "= ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train", "= ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset", "split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label", "= acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test):", "= keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart", "Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape:", "tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training dataset", "import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow", "print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred =", "tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from tensorflow.keras import Input from tensorflow.keras.layers", "tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import style import os", "the Model model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(),", "from tensorflow import keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist", "Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred", "model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states()", "to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info", "ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) #", "up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)", "with tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients", "utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear')", "5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in", "as tfds from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense,", "for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch,", "{epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred =", "ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to", "= tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training dataset ds_train = ds_train.map(normalize_img,", "import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, regularizers", "tfds from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU", "print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True,", "epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False)", "tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from", "= tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return", "in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over", "regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from tensorflow.keras import Input", "enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over test", "import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear') print(style.YELLOW", "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n')", "dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building", "ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential( [ Input((28, 28,", "AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training dataset ds_train =", "acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred)", "import layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from tensorflow.keras", "ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test", "ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential(", "gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over", "= tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch", "'3' # change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='')", "tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training", "acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for", "acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred", "optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training", "range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with", "= 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch", "end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy()", "epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in", "ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train =", "optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for", "batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch, training=True)", "keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] )", "= keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ]", "num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE)", "keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as", "= keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx,", "Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='')", "from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds from tensorflow.keras import Input from", "in enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch,", "with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE", "# Building the Model model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3,", "version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True,", "ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label):", "Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import style", ") print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric", "= keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training Epoch", "style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear') print(style.YELLOW +", "{train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch,", "= ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential( [ Input((28, 28, 1)),", "Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5", "print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape()", "import keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets", "tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, regularizers from", "import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL']", "for epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch)", "y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss =", "def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32", "ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image,", "= model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights))", "y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy", "y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch)", "import tensorflow_datasets as tfds from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D,", "tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image,", "tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE)", "os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version:", "1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs =", "model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over test set: {train_acc}') acc_metric.reset_states()", "import mnist import tensorflow_datasets as tfds from tensorflow.keras import Input from tensorflow.keras.layers import", "ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32,", "loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result()", "2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info =", "= ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test = ds_train.map(normalize_img,", "= ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model", "y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients,", "f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'],", "ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE)", "] ) print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4)", "enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred)", "'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0,", "of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as", "# Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test", "= ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test =", "Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)", "print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric =", "Model model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10,", "tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils", "shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE =", "tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients =", "<reponame>marknhenry/tf_starter_kit import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers,", "print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist',", "tape: y_pred = model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights)", "loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs):", "train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in", "3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5 loss_fn", "in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch, y_batch) in enumerate(ds_train):", "from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from", "end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, )", "(ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def", "= ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential( [", "'test'], shuffle_files=True, as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE", "{tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True,", "ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model", "training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred)", "keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}')", "change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test),", "keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of", "from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds", "tensorflow import keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import mnist import", "training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train", "Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer", "[ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN,", "import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import", "label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting", ") def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE =", "test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) #", "Flatten, Dense, ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #", "Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test =", "ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE)", "model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx,", "acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch,", "as_supervised=True, with_info=True, ) def normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE", "num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model =", "ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test", "tensorflow_datasets as tfds from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,", "model(x_batch, training=True) loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch,", "for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc", "Building the Model model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'),", "+ f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train',", "= 32 # Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train =", "loss = loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc", "activation='softmax'), ] ) print(style.GREEN, end='') num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer =", "= loss_fn(y_batch, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc =", "# change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train,", "os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN, end='') (ds_train, ds_test), ds_info = tfds.load(", "Dense, ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change", "Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train =", "num_epochs = 5 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.Adam(learning_rate=3e-4) acc_metric = keras.metrics.SparseCategoricalAccuracy() for", "= '3' # change to 2 os.system('clear') print(style.YELLOW + f'Tensorflow version: {tf.__version__}\\n') print(style.GREEN,", "ds_test = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_test = ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the", "BATCH_SIZE = 32 # Setting up training dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train", "tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over epoch {train_acc}')", "from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # change to 2", "label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up training dataset ds_train", "y_batch) in enumerate(ds_test): y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy", "return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 # Setting up", "from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import style import", "ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up", "tf from tensorflow import keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets import", "28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'), ] ) print(style.GREEN, end='') num_epochs", "= model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over test set: {train_acc}')", "ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test =", "(x_batch, y_batch) in enumerate(ds_train): with tf.GradientTape() as tape: y_pred = model(x_batch, training=True) loss", "ds_train.batch(BATCH_SIZE) ds_test = ds_train.prefetch(AUTOTUNE) # Building the Model model = keras.Sequential( [ Input((28,", "model = keras.Sequential( [ Input((28, 28, 1)), Conv2D(32, 3, activation='relu'), Flatten(), Dense(10, activation='softmax'),", "as tf from tensorflow import keras from tensorflow.keras import layers, regularizers from tensorflow.keras.datasets", "normalize_img(image, label): return tf.cast(image, tf.float32)/255.0, label AUTOTUNE = tf.data.experimental.AUTOTUNE BATCH_SIZE = 32 #", "Conv2D, MaxPooling2D, Flatten, Dense, ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] =", "ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(BATCH_SIZE) ds_train = ds_train.prefetch(AUTOTUNE) # Setting up test dataset ds_test", "keras.metrics.SparseCategoricalAccuracy() for epoch in range(num_epochs): print(f'\\nStart of Training Epoch {epoch}') for batch_idx, (x_batch,", "over epoch {train_acc}') acc_metric.reset_states() for batch_idx, (x_batch, y_batch) in enumerate(ds_test): y_pred = model(x_batch,", "dataset ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train =", "y_pred = model(x_batch, training=False) acc_metric.update_state(y_batch, y_pred) train_acc = acc_metric.result() print(f'Accuracy over test set:", "MaxPooling2D, Flatten, Dense, ReLU from utils import style import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'" ]
[ "managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes',", "= __import__('05_remote_processor') import multiprocessing from multiprocessing import managers queue = multiprocessing.Queue() manager =", "= managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes', callable=constants.primes) server = manager.get_server() server.serve_forever()", "constants = __import__('05_remote_processor') import multiprocessing from multiprocessing import managers queue = multiprocessing.Queue() manager", "__import__('05_remote_processor') import multiprocessing from multiprocessing import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('',", "multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes', callable=constants.primes) server =", "multiprocessing from multiprocessing import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password)", "from multiprocessing import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue',", "import multiprocessing from multiprocessing import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port),", "queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes', callable=constants.primes)", "= multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes', callable=constants.primes) server", "import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue)", "<filename>13_multiprocessing/05_remote_server.py constants = __import__('05_remote_processor') import multiprocessing from multiprocessing import managers queue = multiprocessing.Queue()", "manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda: queue) manager.register('primes', callable=constants.primes) server = manager.get_server()", "multiprocessing import managers queue = multiprocessing.Queue() manager = managers.BaseManager(address=('', constants.port), authkey=constants.password) manager.register('queue', callable=lambda:" ]
[ "#!/usr/bin/env python2 import rospy from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\" while", "python2 import rospy from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\" while not", "rospy from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\" while not rospy.is_shutdown(): pub.publish(surname)", "from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\" while not rospy.is_shutdown(): pub.publish(surname) rate.sleep()", "<gh_stars>0 #!/usr/bin/env python2 import rospy from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\"", "import rospy from std_msgs.msg import String rospy.init_node(\"surname\") pub=rospy.Publisher(\"surname\",String) rate=rospy.Rate(3) surname=\"Puranik\" while not rospy.is_shutdown():" ]
[ "center Returns: corners: (N, 8, 3) \"\"\" template = np.array([[1, 1, -1], [1,", "corners3d: of shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8,", "angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] =", "None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d)", "* n3, (n1 * dp[1] - n2 * dc[1]) * n3] outputList =", "logic at the top and use it consistently # Add comments of explanation", "axis=1) wp2 = np.sum(w * boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <=", "return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another polygon. Ref:", "# corners3d: of shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1,", "vp6, vx >= vp7) mask_w = np.logical_and(wx <= wp6, wx >= wp2) mask", ") corners_3d[0, :] += center[0] corners_3d[1, :] += center[1] corners_3d[2, :] += center[2]", "inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s):", "[cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1] -", "y, z, dx, dy, dz, heading], (x, y, z) is the box center", "wx ux = np.matmul(points, u.T) # (n, m) vx = np.matmul(points, v.T) wx", "of (x,y) tuples of hull vertices. return a list of (x,y) for the", ":] - boxes[:, 2, :] # (m, 3) # ux, vx, wx ux", "* dp[0]) return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1", "p1,p2 are a list of (x,y) tuples of hull vertices. return a list", "boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 --------", "numpy as np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args:", ":]) l = distance[0, 2] w = distance[0, 0] h = distance[0, 3]", "0] b = box[0, 1] - box[1, 1] heading_angle = np.arctan2(a, b) return", "np.logical_and(vx <= vp6, vx >= vp7) mask_w = np.logical_and(wx <= wp6, wx >=", "corners: (8,3) no assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2))", "Args: subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon: a list", "up5) # (1024, n) mask_v = np.logical_and(vx <= vp6, vx >= vp7) mask_w", "\"\"\" def inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1]", "for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter,", "polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d", "[l, w, h] def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle: float", "* boxes[:, 6, :], axis=1) vp7 = np.sum(v * boxes[:, 7, :], axis=1)", "direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c", "import numpy as np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\"", "w = p6 - p2 w = boxes[:, 6, :] - boxes[:, 2,", "= boxes[:, 6, :] - boxes[:, 7, :] # (m, 3) # w", "of (x,y) 2d points, any polygon. clipPolygon: a list of (x,y) 2d points,", "mask_w = np.logical_and(wx <= wp6, wx >= wp2) mask = mask_u & mask_v", "[s[0] - e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1] - cp1[1]", "xyz # u = p6 - p5 u = boxes[:, 6, :] -", "inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 if len(outputList) == 0: return", "3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None, :,", "mask_w # (10240, n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return", "assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:]", "= scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners): ''' corners:", "6, :] - boxes[:, 5, :] # (m, 3) # v = p6", "np.sum(u * boxes[:, 5, :], axis=1) vp6 = np.sum(v * boxes[:, 6, :],", "axis=1) wp6 = np.sum(w * boxes[:, 6, :], axis=1) wp2 = np.sum(w *", "= min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin)", "- cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0]", "corners of a single box from rotation matrix Args: size: list of float", "2D bounding box IoU ''' # corner points are in counter clockwise order", "(1, 8, 1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:,", "= inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area", "-1], [-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1, -1, 1],", "- box[1, 0] b = box[0, 1] - box[1, 1] heading_angle = np.arctan2(a,", "(cp2[1] - cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0] -", "m) vx = np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6, up5, vp6,", "\"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another polygon.", "- corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU.", "Y corners2: numpy array (8,3), assume up direction is negative Y Output: iou:", "3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x,", "a single box from rotation matrix Args: size: list of float [dx, dy,", "boxes[:, 7, :], axis=1) wp6 = np.sum(w * boxes[:, 6, :], axis=1) wp2", "Y Output: iou: 3D bounding box IoU iou_2d: bird's eye view 2D bounding", "1]] ) / 2. # corners3d: of shape (N, 3, 8) corners3d =", "= convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(),", "* boxes[:, 6, :], axis=1) up5 = np.sum(u * boxes[:, 5, :], axis=1)", "0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption on axis direction ''' a", "[x, y, z, dx, dy, dz, heading], (x, y, z) is the box", "cp2 = clipVertex inputList = outputList outputList = [] s = inputList[-1] for", "def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip", "7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the", "6 -------- 5 . | | | | . 3 -------- 0 |/", "m) of type bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool)", "center: np.array [x, y, z] rotmat: np.array (3, 3) Returns: corners: (8, 3)", "boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:, None, 0:3] return corners3d", "2d points, has to be *convex* Note: **points have to be counter-clockwise ordered**", "up direction is negative Y corners2: numpy array (8,3), assume up direction is", "- n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1])", "array (8,3), assume up direction is negative Y Output: iou: 3D bounding box", "* cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1]", "the top and use it consistently # Add comments of explanation import numpy", "bird's eye view 2D bounding box IoU ''' # corner points are in", "corner points are in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i", "*convex* Note: **points have to be counter-clockwise ordered** Return: a list of (x,y)", "None, 3:6], (1, 8, 1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8,", "dp[0]) return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 *", "eye view 2D bounding box IoU ''' # corner points are in counter", "z) is the box center Returns: corners: (N, 8, 3) \"\"\" template =", "of hull vertices. return a list of (x,y) for the intersection and its", "b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single box", "heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of", "\"\"\" 7 -------- 4 /| /| 6 -------- 5 . | | |", ":, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 )", "(8,3), assume up direction is negative Y corners2: numpy array (8,3), assume up", "z] rotmat: np.array (3, 3) Returns: corners: (8, 3) \"\"\" l, h, w", "= np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :]", "= get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def", "= [i / 2 for i in size] center = np.reshape(center, (-1, 3))", "(outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex hull's intersection area.", "n2 * dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex", "IoU ''' # corner points are in counter clockwise order rect1 = [(corners1[i,0],", "is negative Y corners2: numpy array (8,3), assume up direction is negative Y", "= s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0]", "n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] *", "bounding box IoU. Input: corners1: numpy array (8,3), assume up direction is negative", "wp6, wp2 up6 = np.sum(u * boxes[:, 6, :], axis=1) up5 = np.sum(u", "(x,y) for the intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p", "y, z) is the box center (dx, dy, dz) as the box size", "# (m, 3) # ux, vx, wx ux = np.matmul(points, u.T) # (n,", "1], dtype=np.bool) points = points[:, :3] # get xyz # u = p6", "return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex", "np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single", "None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners):", "import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx, dy, dz]", "(cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0]", "= [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1]", "up6, ux >= up5) # (1024, n) mask_v = np.logical_and(vx <= vp6, vx", "= np.sum(u * boxes[:, 6, :], axis=1) up5 = np.sum(u * boxes[:, 5,", "3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:, None, 0:3] return", "def convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex hull's intersection area. p1,p2", "the box center Returns: corners: (N, 8, 3) \"\"\" template = np.array([[1, 1,", "7 -------- 4 /| /| 6 -------- 5 . | | | |", "-------- 5 . | | | | . 3 -------- 0 |/ |/", "the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]):", "template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3", "1] - box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size, center,", "(-1, 3)) center = center.reshape(3) x_corners = [l, l, -l, -l, l, l,", "size] center = np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners = [l, l,", "= [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i", "np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :] += center[1]", "- p7 v = boxes[:, 6, :] - boxes[:, 7, :] # (m,", "be counter-clockwise ordered** Return: a list of (x,y) vertex point for the intersection", "of two convex hull's intersection area. p1,p2 are a list of (x,y) tuples", "intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not None:", ":] # (m, 3) # ux, vx, wx ux = np.matmul(points, u.T) #", "have to be counter-clockwise ordered** Return: a list of (x,y) vertex point for", "\"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return", "z, dx, dy, dz, heading] with (x, y, z) is the box center", "comments of explanation import numpy as np import scipy.spatial from .rotation import rotate_points_along_z", "of explanation import numpy as np import scipy.spatial from .rotation import rotate_points_along_z def", "\"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i,", "corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1])", "-------- 1 Args: corners: (N, 8, 3), vertex order shown in figure above", "- boxes[:, 2, :] # (m, 3) # ux, vx, wx ux =", ":], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :,", "cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1]", "* n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2", "corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU. Input:", "3 ) corners3d += boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\"", "if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return", "Note: **points have to be counter-clockwise ordered** Return: a list of (x,y) vertex", "rotmat: np.array (3, 3) Returns: corners: (8, 3) \"\"\" l, h, w =", "- cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp", "explanation import numpy as np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box):", "n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1", "up6, up5, vp6, vp7, wp6, wp2 up6 = np.sum(u * boxes[:, 6, :],", "rotmat): \"\"\"Compute corners of a single box from rotation matrix Args: size: list", "= e cp1 = cp2 if len(outputList) == 0: return None return (outputList)", "[(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] -", "= subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList", "clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0],", "/ 2 for i in size] center = np.reshape(center, (-1, 3)) center =", "a list of (x,y) 2d points, has to be *convex* Note: **points have", "1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1,", "w = boxes[:, 6, :] - boxes[:, 2, :] # (m, 3) #", "no assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b =", "Returns: size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l", "len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] # get", "3) Returns: mask: np.array (n, m) of type bool \"\"\" if len(boxes) ==", "u = boxes[:, 6, :] - boxes[:, 5, :] # (m, 3) #", "-1], [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1]]", "list of (x,y) tuples of hull vertices. return a list of (x,y) for", "Args: pc: np.array (n, 3+d) boxes: np.array (m, 8, 3) Returns: mask: np.array", "dtype=np.bool) points = points[:, :3] # get xyz # u = p6 -", "rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol", "np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] # get xyz # u =", ":] - boxes[:, 7, :] # (m, 3) # w = p6 -", "cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0])", "polygon_clip(p1,p2) if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else:", "wx = np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6, wp2 up6 =", "assume up direction is negative Y Output: iou: 3D bounding box IoU iou_2d:", "np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6, wp2 up6 = np.sum(u *", "(8,3) no assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b", "np.sum(w * boxes[:, 6, :], axis=1) wp2 = np.sum(w * boxes[:, 2, :],", "2. # corners3d: of shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6],", "center.reshape(3) x_corners = [l, l, -l, -l, l, l, -l, -l] y_corners =", "(x,y) 2d points, has to be *convex* Note: **points have to be counter-clockwise", "corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute", "and use it consistently # Add comments of explanation import numpy as np", "[dx, dy, dz] center: np.array [x, y, z] rotmat: np.array (3, 3) Returns:", "boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n,", "box[1:5, :]) l = distance[0, 2] w = distance[0, 0] h = distance[0,", "corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d +=", "wp6 = np.sum(w * boxes[:, 6, :], axis=1) wp2 = np.sum(w * boxes[:,", "cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp =", "axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :])", "i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 =", "= p6 - p7 v = boxes[:, 6, :] - boxes[:, 7, :]", "= inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou =", "center, rotmat): \"\"\"Compute corners of a single box from rotation matrix Args: size:", "subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon: a list of", "cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc =", "h = distance[0, 3] return [l, w, h] def get_heading_angle(box): \"\"\" Args: box:", "- boxes[:, 7, :] # (m, 3) # w = p6 - p2", "Args: box: (8, 3) Returns: heading_angle: float \"\"\" a = box[0, 0] -", "= 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1 *", "in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2", "[i / 2 for i in size] center = np.reshape(center, (-1, 3)) center", "corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2)", "= get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /|", "wp2 = np.sum(w * boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <= up6,", ") corners3d += boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args:", "get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle: float \"\"\" a = box[0,", "corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 . | |", "ux >= up5) # (1024, n) mask_v = np.logical_and(vx <= vp6, vx >=", "* dp[1] - n2 * dc[1]) * n3] outputList = subjectPolygon cp1 =", "0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes:", "p2 w = boxes[:, 6, :] - boxes[:, 2, :] # (m, 3)", "vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol / (vol1 + vol2", "8 corners logic at the top and use it consistently # Add comments", "| . 3 -------- 0 |/ |/ 2 -------- 1 Args: corners: (N,", "in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i,", "= np.sum(v * boxes[:, 6, :], axis=1) vp7 = np.sum(v * boxes[:, 7,", "0] h = distance[0, 3] return [l, w, h] def get_heading_angle(box): \"\"\" Args:", "* dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2", "is the box center Returns: corners: (N, 8, 3) \"\"\" template = np.array([[1,", "vol2 = box3d_vol(corners2) iou = inter_vol / (vol1 + vol2 - inter_vol) return", "| | . 3 -------- 0 |/ |/ 2 -------- 1 Args: corners:", "# v = p6 - p7 v = boxes[:, 6, :] - boxes[:,", "scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners): ''' corners: (8,3)", "boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z)", "z, dx, dy, dz, heading], (x, y, z) is the box center Returns:", "= p6 - p5 u = boxes[:, 6, :] - boxes[:, 5, :]", "dy, dz) as the box size and heading as the clockwise rotation angle", "corners logic at the top and use it consistently # Add comments of", "6, :], axis=1) up5 = np.sum(u * boxes[:, 5, :], axis=1) vp6 =", ">= wp2) mask = mask_u & mask_v & mask_w # (10240, n) return", "heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single box from rotation", "cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1] - e[1]] n1", "np.array [x, y, z] rotmat: np.array (3, 3) Returns: corners: (8, 3) \"\"\"", "- cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0],", "y, z, dx, dy, dz, heading] with (x, y, z) is the box", "[x, y, z] rotmat: np.array (3, 3) Returns: corners: (8, 3) \"\"\" l,", ". | | | | . 3 -------- 0 |/ |/ 2 --------", "counter-clockwise ordered** Return: a list of (x,y) vertex point for the intersection polygon.", "return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) *", "s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] *", "distance[0, 3] return [l, w, h] def get_heading_angle(box): \"\"\" Args: box: (8, 3)", "\"\"\"Compute corners of a single box from rotation matrix Args: size: list of", "h, h, -h, -h, h] z_corners = [w, w, w, w, -w, -w,", "h] z_corners = [w, w, w, w, -w, -w, -w, -w] corners_3d =", "corners_3d[0, :] += center[0] corners_3d[1, :] += center[1] corners_3d[2, :] += center[2] return", "wx >= wp2) mask = mask_u & mask_v & mask_w # (10240, n)", "1 Args: corners: (N, 8, 3), vertex order shown in figure above Returns:", "as the box size and heading as the clockwise rotation angle \"\"\" boxes3d", "array (8,3), assume up direction is negative Y corners2: numpy array (8,3), assume", "= np.array([[1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1],", "corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)]", "# (m, 3) # v = p6 - p7 v = boxes[:, 6,", "w, w, -w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners])", "= poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax =", "inter_vol = inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou", "s[1] - e[1]] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2", "size and heading as the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7))", "else: return None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption on axis", "1] heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners", "- corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): '''", "assume up direction is negative Y corners2: numpy array (8,3), assume up direction", "polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) >", "as np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box:", "area of two convex hull's intersection area. p1,p2 are a list of (x,y)", "dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon:", "of shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1))", "mask_u = np.logical_and(ux <= up6, ux >= up5) # (1024, n) mask_v =", "y, z] rotmat: np.array (3, 3) Returns: corners: (8, 3) \"\"\" l, h,", "boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :])", "order shown in figure above Returns: boxes3d: (N, 7) [x, y, z, dx,", "| | . 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d:", "point for the intersection polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0]) *", "z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :] += center[1] corners_3d[2, :] +=", "* boxes[:, 5, :], axis=1) vp6 = np.sum(v * boxes[:, 6, :], axis=1)", "boxes[:, 5, :], axis=1) vp6 = np.sum(v * boxes[:, 6, :], axis=1) vp7", ":], axis=1) wp2 = np.sum(w * boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux", "= np.sum(u * boxes[:, 5, :], axis=1) vp6 = np.sum(v * boxes[:, 6,", "axis=1) vp6 = np.sum(v * boxes[:, 6, :], axis=1) vp7 = np.sum(v *", "corners2: numpy array (8,3), assume up direction is negative Y Output: iou: 3D", "np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] =", "for subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection())", "/ (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1 * dp[0] -", "u = p6 - p5 u = boxes[:, 6, :] - boxes[:, 5,", "outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 if len(outputList) ==", "8x3 Returns: size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :])", "5, :], axis=1) vp6 = np.sum(v * boxes[:, 6, :], axis=1) vp7 =", "corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes: np.array (m,", "distance[0, 0] h = distance[0, 3] return [l, w, h] def get_heading_angle(box): \"\"\"", "dy, dz] center: np.array [x, y, z] rotmat: np.array (3, 3) Returns: corners:", "= np.matmul(points, u.T) # (n, m) vx = np.matmul(points, v.T) wx = np.matmul(points,", "np.sum(w * boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <= up6, ux >=", "[1, -1, 1], [-1, -1, 1], [-1, 1, 1]] ) / 2. #", "for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList = []", "inputList = outputList outputList = [] s = inputList[-1] for subjectVertex in inputList:", "(x,y) tuples of hull vertices. return a list of (x,y) for the intersection", "corners2): ''' Compute 3D bounding box IoU. Input: corners1: numpy array (8,3), assume", "iou_2d: bird's eye view 2D bounding box IoU ''' # corner points are", "scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2] w = distance[0, 0] h", "in size] center = np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners = [l,", "# get xyz # u = p6 - p5 u = boxes[:, 6,", "-w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] +=", "1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1,", "matrix Args: size: list of float [dx, dy, dz] center: np.array [x, y,", "box IoU. Input: corners1: numpy array (8,3), assume up direction is negative Y", "compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single box from rotation matrix Args:", "hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners): '''", "1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1 * dp[0]", ":] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /|", "corners_3d[1, :] += center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\"", "def inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] -", "box from rotation matrix Args: size: list of float [dx, dy, dz] center:", "2d points, any polygon. clipPolygon: a list of (x,y) 2d points, has to", "for i in size] center = np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners", "points, has to be *convex* Note: **points have to be counter-clockwise ordered** Return:", "hull_inter.volume else: return None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption on", "rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2", "-1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1],", "1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1]] ) / 2.", "v.T) wx = np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6, wp2 up6", "bounding box IoU ''' # corner points are in counter clockwise order rect1", "mask_u & mask_v & mask_w # (10240, n) return mask def poly_area(x,y): \"\"\"", "= subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s", "outputList.append(computeIntersection()) s = e cp1 = cp2 if len(outputList) == 0: return None", "= cp2 if len(outputList) == 0: return None return (outputList) def convex_hull_intersection(p1, p2):", "''' Compute 3D bounding box IoU. Input: corners1: numpy array (8,3), assume up", "(3, 3) Returns: corners: (8, 3) \"\"\" l, h, w = [i /", "y, z) is the box center Returns: corners: (N, 8, 3) \"\"\" template", "1], [-1, -1, 1], [-1, 1, 1]] ) / 2. # corners3d: of", "single box from rotation matrix Args: size: list of float [dx, dy, dz]", "n) mask_v = np.logical_and(vx <= vp6, vx >= vp7) mask_w = np.logical_and(wx <=", "box: (8, 3) Returns: heading_angle: float \"\"\" a = box[0, 0] - box[1,", "Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y,", "3) Returns: heading_angle: float \"\"\" a = box[0, 0] - box[1, 0] b", "min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1", "8, 3) Returns: mask: np.array (n, m) of type bool \"\"\" if len(boxes)", "size: list of float [dx, dy, dz] center: np.array [x, y, z] rotmat:", "vp6, vp7, wp6, wp2 up6 = np.sum(u * boxes[:, 6, :], axis=1) up5", "-------- 4 /| /| 6 -------- 5 . | | | | .", "up5, vp6, vp7, wp6, wp2 up6 = np.sum(u * boxes[:, 6, :], axis=1)", "https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon: a", "|/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y, z, dx,", "= rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:,", "8, 3) \"\"\" template = np.array([[1, 1, -1], [1, -1, -1], [-1, -1,", "p6 - p7 v = boxes[:, 6, :] - boxes[:, 7, :] #", "# (10240, n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))", "is negative Y Output: iou: 3D bounding box IoU iou_2d: bird's eye view", "mask = mask_u & mask_v & mask_w # (10240, n) return mask def", "for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6]", "cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList", "\"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2] w =", "| | | . 3 -------- 0 |/ |/ 2 -------- 1 Args:", "def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args:", "cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0", "(N, 8, 3), vertex order shown in figure above Returns: boxes3d: (N, 7)", "boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 . | |", "def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0]", "return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes: np.array", "* dp[1] - dc[1] * dp[0]) return [(n1 * dp[0] - n2 *", "\"\"\" l, h, w = [i / 2 for i in size] center", "dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2]", "box[0, 1] - box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size,", "0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] # get xyz #", "3)) center = center.reshape(3) x_corners = [l, l, -l, -l, l, l, -l,", "= np.sum(w * boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <= up6, ux", "= polygon_clip(p1,p2) if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume", "are a list of (x,y) tuples of hull vertices. return a list of", "list of float [dx, dy, dz] center: np.array [x, y, z] rotmat: np.array", "-w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0,", "+= boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array", "Compute area of two convex hull's intersection area. p1,p2 are a list of", "boxes: np.array (m, 8, 3) Returns: mask: np.array (n, m) of type bool", "np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding box", "scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns: size:", "negative Y corners2: numpy array (8,3), assume up direction is negative Y Output:", "h] def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle: float \"\"\" a", "[-1, 1, 1]] ) / 2. # corners3d: of shape (N, 3, 8)", "a = box[0, 0] - box[1, 0] b = box[0, 1] - box[1,", ":], axis=1) mask_u = np.logical_and(ux <= up6, ux >= up5) # (1024, n)", "np.array (n, 3+d) boxes: np.array (m, 8, 3) Returns: mask: np.array (n, m)", "3) \"\"\" template = np.array([[1, 1, -1], [1, -1, -1], [-1, -1, -1],", "6, :] - boxes[:, 2, :] # (m, 3) # ux, vx, wx", "from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx,", "return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex hull's intersection", "outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 if len(outputList)", "y_corners = [h, -h, -h, h, h, -h, -h, h] z_corners = [w,", "8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None, :, :]", "3 -------- 0 |/ |/ 2 -------- 1 Args: corners: (N, 8, 3),", "= np.logical_and(wx <= wp6, wx >= wp2) mask = mask_u & mask_v &", "max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 =", "distance[0, 2] w = distance[0, 0] h = distance[0, 3] return [l, w,", "[-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1,", "\"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon", "inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin =", "(m, 3) # ux, vx, wx ux = np.matmul(points, u.T) # (n, m)", "boxes[:, 2, :] # (m, 3) # ux, vx, wx ux = np.matmul(points,", "return a list of (x,y) for the intersection and its volume \"\"\" inter_p", "= np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners = [l, l, -l, -l,", "outputList outputList = [] s = inputList[-1] for subjectVertex in inputList: e =", "- cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc", "def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle: float \"\"\" a =", "center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4", "rotation matrix Args: size: list of float [dx, dy, dz] center: np.array [x,", "wp6, wx >= wp2) mask = mask_u & mask_v & mask_w # (10240,", ":, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\"", "<= vp6, vx >= vp7) mask_w = np.logical_and(wx <= wp6, wx >= wp2)", "polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d points, any polygon.", "- n2 * dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for", ":3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i,", "[(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in", "w, -w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) )", "3D bounding box IoU iou_2d: bird's eye view 2D bounding box IoU '''", "corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None, :, :] corners3d", "boxes[:, 5, :] # (m, 3) # v = p6 - p7 v", "- cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] -", "x_corners = [l, l, -l, -l, l, l, -l, -l] y_corners = [h,", "np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners = [l, l, -l, -l, l,", "up direction is negative Y Output: iou: 3D bounding box IoU iou_2d: bird's", "boxes[:, 7, :] # (m, 3) # w = p6 - p2 w", "| . 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N,", "of (x,y) 2d points, has to be *convex* Note: **points have to be", "to be counter-clockwise ordered** Return: a list of (x,y) vertex point for the", "mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\"", "v = p6 - p7 v = boxes[:, 6, :] - boxes[:, 7,", "computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0] -", ">= up5) # (1024, n) mask_v = np.logical_and(vx <= vp6, vx >= vp7)", "n3, (n1 * dp[1] - n2 * dc[1]) * n3] outputList = subjectPolygon", "= np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1,", "up6 = np.sum(u * boxes[:, 6, :], axis=1) up5 = np.sum(u * boxes[:,", "-h, -h, h] z_corners = [w, w, w, w, -w, -w, -w, -w]", "mask_v & mask_w # (10240, n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates", "| | | | . 3 -------- 0 |/ |/ 2 -------- 1", "not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0 def", "- p5 u = boxes[:, 6, :] - boxes[:, 5, :] # (m,", "np.sum(v * boxes[:, 6, :], axis=1) vp7 = np.sum(v * boxes[:, 7, :],", "-l, -l] y_corners = [h, -h, -h, h, h, -h, -h, h] z_corners", "<= up6, ux >= up5) # (1024, n) mask_v = np.logical_and(vx <= vp6,", "(m, 8, 3) Returns: mask: np.array (n, m) of type bool \"\"\" if", "3:6], (1, 8, 1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3),", "l, l, -l, -l] y_corners = [h, -h, -h, h, h, -h, -h,", "with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d points,", "inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1])", "e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return", "box IoU iou_2d: bird's eye view 2D bounding box IoU ''' # corner", "heading as the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i", "n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0 /", "= [l, l, -l, -l, l, l, -l, -l] y_corners = [h, -h,", "# (m, 3) # w = p6 - p2 w = boxes[:, 6,", "3) # v = p6 - p7 v = boxes[:, 6, :] -", "clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList =", "convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min())", "* (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def", "-1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1, -1,", "and heading as the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for", "0: return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of two", "(8, 3) Returns: heading_angle: float \"\"\" a = box[0, 0] - box[1, 0]", "3), vertex order shown in figure above Returns: boxes3d: (N, 7) [x, y,", "= np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6]", "a list of (x,y) 2d points, any polygon. clipPolygon: a list of (x,y)", "u.T) # (n, m) vx = np.matmul(points, v.T) wx = np.matmul(points, w.T) #", "(m, 3) # v = p6 - p7 v = boxes[:, 6, :]", "0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python", "Returns: corners: (8, 3) \"\"\" l, h, w = [i / 2 for", "# TODO: Explain 8 corners logic at the top and use it consistently", ":] - boxes[:, 5, :] # (m, 3) # v = p6 -", "wp2) mask = mask_u & mask_v & mask_w # (10240, n) return mask", "1], [-1, 1, 1]] ) / 2. # corners3d: of shape (N, 3,", "n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 =", "w.T) # up6, up5, vp6, vp7, wp6, wp2 up6 = np.sum(u * boxes[:,", "e cp1 = cp2 if len(outputList) == 0: return None return (outputList) def", ") / 2. # corners3d: of shape (N, 3, 8) corners3d = np.tile(boxes3d[:,", "-h, -h, h, h, -h, -h, h] z_corners = [w, w, w, w,", "[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1,", "inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1", "p7 v = boxes[:, 6, :] - boxes[:, 7, :] # (m, 3)", "http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another", "= [s[0] - e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1] -", "hull's intersection area. p1,p2 are a list of (x,y) tuples of hull vertices.", "-w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :]", "= box[0, 1] - box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle def", "6, :] - boxes[:, 7, :] # (m, 3) # w = p6", "[] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e):", "area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax", "max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol / (vol1", "polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon:", "inter_p = polygon_clip(p1,p2) if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p,", "corners1: numpy array (8,3), assume up direction is negative Y corners2: numpy array", "float [dx, dy, dz] center: np.array [x, y, z] rotmat: np.array (3, 3)", "- cp2[1]] dp = [s[0] - e[0], s[1] - e[1]] n1 = cp1[0]", "5 . | | | | . 3 -------- 0 |/ |/ 2", "= mask_u & mask_v & mask_w # (10240, n) return mask def poly_area(x,y):", "Explain 8 corners logic at the top and use it consistently # Add", "cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1] - e[1]] n1 =", "box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol / (vol1 + vol2 - inter_vol)", "if len(outputList) == 0: return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute", "for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1", ". 3 -------- 0 |/ |/ 2 -------- 1 Args: corners: (N, 8,", "w = distance[0, 0] h = distance[0, 3] return [l, w, h] def", "= distance[0, 2] w = distance[0, 0] h = distance[0, 3] return [l,", "TODO: Explain 8 corners logic at the top and use it consistently #", "np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0)", "get xyz # u = p6 - p5 u = boxes[:, 6, :]", "7, :], axis=1) wp6 = np.sum(w * boxes[:, 6, :], axis=1) wp2 =", "of a single box from rotation matrix Args: size: list of float [dx,", "np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6, wp2", "cp2[1]] dp = [s[0] - e[0], s[1] - e[1]] n1 = cp1[0] *", "tuples of hull vertices. return a list of (x,y) for the intersection and", "h, -h, -h, h] z_corners = [w, w, w, w, -w, -w, -w,", "get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d):", "inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None,", ":]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6 --------", "p2): \"\"\" Compute area of two convex hull's intersection area. p1,p2 are a", "shown in figure above Returns: boxes3d: (N, 7) [x, y, z, dx, dy,", "boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 .", "8, 1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape(", "points, any polygon. clipPolygon: a list of (x,y) 2d points, has to be", "(x,y) vertex point for the intersection polygon. \"\"\" def inside(p): return (cp2[0] -", "* dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in", "intersection polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1])", "Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a polygon with", "-1, 1], [-1, -1, 1], [-1, 1, 1]] ) / 2. # corners3d:", "dz, heading] with (x, y, z) is the box center (dx, dy, dz)", "len(outputList) == 0: return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area", "-1, 1], [-1, 1, 1]] ) / 2. # corners3d: of shape (N,", "dy, dz, heading] with (x, y, z) is the box center (dx, dy,", "return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] # get xyz # u", "y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :] += center[1] corners_3d[2, :]", "corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /|", "(N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None,", "on axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] -", "Return: a list of (x,y) vertex point for the intersection polygon. \"\"\" def", "dx, dy, dz, heading] with (x, y, z) is the box center (dx,", "clipPolygon: a list of (x,y) 2d points, has to be *convex* Note: **points", "i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] =", "convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex hull's intersection area. p1,p2 are", "/| 6 -------- 5 . | | | | . 3 -------- 0", "get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /|", "intersection area. p1,p2 are a list of (x,y) tuples of hull vertices. return", "np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2))", "/| /| 6 -------- 5 . | | | | . 3 --------", "vertex point for the intersection polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0])", "e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] -", "dz] center: np.array [x, y, z] rotmat: np.array (3, 3) Returns: corners: (8,", "boxes[:, 6, :] - boxes[:, 5, :] # (m, 3) # v =", "dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2] w", "if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 =", "- boxes[:, 5, :] # (m, 3) # v = p6 - p7", "ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1)", "* max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol /", "dc[1] * dp[0]) return [(n1 * dp[0] - n2 * dc[0]) * n3,", "box[0, 0] - box[1, 0] b = box[0, 1] - box[1, 1] heading_angle", "inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 if", "- dc[1] * dp[0]) return [(n1 * dp[0] - n2 * dc[0]) *", "= inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if not", "n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) *", "np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3", "\"\"\" Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list", "2] w = distance[0, 0] h = distance[0, 3] return [l, w, h]", "& mask_v & mask_w # (10240, n) return mask def poly_area(x,y): \"\"\" Ref:", "= cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1]", "-w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0]", "(N, 8, 3) \"\"\" template = np.array([[1, 1, -1], [1, -1, -1], [-1,", "vp6 = np.sum(v * boxes[:, 6, :], axis=1) vp7 = np.sum(v * boxes[:,", ":3] # get xyz # u = p6 - p5 u = boxes[:,", "- e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1] - cp1[1] *", "b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def", "8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:, None, 0:3]", "get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx, dy, dz] \"\"\" distance =", "[-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1,", "dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 *", ". 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7)", "polygon. clipPolygon: a list of (x,y) 2d points, has to be *convex* Note:", "dx, dy, dz, heading], (x, y, z) is the box center Returns: corners:", "np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max())", "8, 3 ) corners3d += boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes):", "vertex order shown in figure above Returns: boxes3d: (N, 7) [x, y, z,", "& mask_w # (10240, n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\"", "= distance[0, 3] return [l, w, h] def get_heading_angle(box): \"\"\" Args: box: (8,", "-------- 0 |/ |/ 2 -------- 1 Args: corners: (N, 8, 3), vertex", ":] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d", "of type bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points", "p6 - p5 u = boxes[:, 6, :] - boxes[:, 5, :] #", "ux = np.matmul(points, u.T) # (n, m) vx = np.matmul(points, v.T) wx =", "-l, l, l, -l, -l] y_corners = [h, -h, -h, h, h, -h,", "= outputList outputList = [] s = inputList[-1] for subjectVertex in inputList: e", "\"\"\" Compute area of two convex hull's intersection area. p1,p2 are a list", "use it consistently # Add comments of explanation import numpy as np import", "-1, 8, 3 ) corners3d += boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points,", "Returns: mask: np.array (n, m) of type bool \"\"\" if len(boxes) == 0:", "np.sum(v * boxes[:, 7, :], axis=1) wp6 = np.sum(w * boxes[:, 6, :],", "inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s):", "= np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] -", "corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1 =", "\"\"\" Args: pc: np.array (n, 3+d) boxes: np.array (m, 8, 3) Returns: mask:", "l, -l, -l] y_corners = [h, -h, -h, h, h, -h, -h, h]", "[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1]] )", "* boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <= up6, ux >= up5)", "* boxes[:, 7, :], axis=1) wp6 = np.sum(w * boxes[:, 6, :], axis=1)", "np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2):", "rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:, None,", "(n1 * dp[1] - n2 * dc[1]) * n3] outputList = subjectPolygon cp1", "subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s =", "# w = p6 - p2 w = boxes[:, 6, :] - boxes[:,", "box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute", "corners: (8, 3) \"\"\" l, h, w = [i / 2 for i", "- cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1] - e[1]]", "clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s", "3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d", "|/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y, z, dx, dy,", "def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU. Input: corners1: numpy array", "a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y)", "type bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points =", "return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single box from", "direction is negative Y corners2: numpy array (8,3), assume up direction is negative", "figure above Returns: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading]", "boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading] with (x, y,", "(N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is", "= [] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if", "axis=1) mask_u = np.logical_and(ux <= up6, ux >= up5) # (1024, n) mask_v", "and its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not None: hull_inter", "of float [dx, dy, dz] center: np.array [x, y, z] rotmat: np.array (3,", "wp2 up6 = np.sum(u * boxes[:, 6, :], axis=1) up5 = np.sum(u *", "= np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6,", "range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :,", "box center (dx, dy, dz) as the box size and heading as the", "list of (x,y) 2d points, has to be *convex* Note: **points have to", "dy, dz, heading], (x, y, z) is the box center Returns: corners: (N,", "above Returns: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading] with", "boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return", "area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2)", "mask_v = np.logical_and(vx <= vp6, vx >= vp7) mask_w = np.logical_and(wx <= wp6,", "(dx, dy, dz) as the box size and heading as the clockwise rotation", "inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area *", "its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not None: hull_inter =", "[x, y, z, dx, dy, dz, heading] with (x, y, z) is the", "3) \"\"\" l, h, w = [i / 2 for i in size]", "2 -------- 1 Args: corners: (N, 8, 3), vertex order shown in figure", "of (x,y) vertex point for the intersection polygon. \"\"\" def inside(p): return (cp2[0]", "(10240, n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def", "s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] *", "at the top and use it consistently # Add comments of explanation import", "\"\"\" Args: box: 8x3 Returns: size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1,", "= np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None, :, :] corners3d =", "np.array (m, 8, 3) Returns: mask: np.array (n, m) of type bool \"\"\"", "vx = np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6, up5, vp6, vp7,", "# (1024, n) mask_v = np.logical_and(vx <= vp6, vx >= vp7) mask_w =", "vx >= vp7) mask_w = np.logical_and(wx <= wp6, wx >= wp2) mask =", "* dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3]", "numpy array (8,3), assume up direction is negative Y Output: iou: 3D bounding", "w, h] def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle: float \"\"\"", "= box3d_vol(corners2) iou = inter_vol / (vol1 + vol2 - inter_vol) return iou", "# (n, m) vx = np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6,", "distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2] w = distance[0,", "8, 3), vertex order shown in figure above Returns: boxes3d: (N, 7) [x,", "7, :] # (m, 3) # w = p6 - p2 w =", "in figure above Returns: boxes3d: (N, 7) [x, y, z, dx, dy, dz,", "return [l, w, h] def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns: heading_angle:", "0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y, z,", "* template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1, 8, 3), boxes3d[:, 6]).reshape( -1, 8,", "is the box center (dx, dy, dz) as the box size and heading", "* boxes[:, 6, :], axis=1) wp2 = np.sum(w * boxes[:, 2, :], axis=1)", "(1024, n) mask_v = np.logical_and(vx <= vp6, vx >= vp7) mask_w = np.logical_and(wx", "# ux, vx, wx ux = np.matmul(points, u.T) # (n, m) vx =", "np.array (3, 3) Returns: corners: (8, 3) \"\"\" l, h, w = [i", "boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :,", "dp[1] - dc[1] * dp[0]) return [(n1 * dp[0] - n2 * dc[0])", "corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c", "list of (x,y) 2d points, any polygon. clipPolygon: a list of (x,y) 2d", "= np.sum(v * boxes[:, 7, :], axis=1) wp6 = np.sum(w * boxes[:, 6,", "outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex", "def get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx, dy, dz] \"\"\" distance", "-h, h] z_corners = [w, w, w, w, -w, -w, -w, -w] corners_3d", "(x,y) 2d points, any polygon. clipPolygon: a list of (x,y) 2d points, has", "Args: size: list of float [dx, dy, dz] center: np.array [x, y, z]", "h, w = [i / 2 for i in size] center = np.reshape(center,", "view 2D bounding box IoU ''' # corner points are in counter clockwise", "in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0],", "if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] #", "v = boxes[:, 6, :] - boxes[:, 7, :] # (m, 3) #", "s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if", "of (x,y) for the intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2) if", "(N, 7) [x, y, z, dx, dy, dz, heading] with (x, y, z)", "heading] with (x, y, z) is the box center (dx, dy, dz) as", "from rotation matrix Args: size: list of float [dx, dy, dz] center: np.array", "= [h, -h, -h, h, h, -h, -h, h] z_corners = [w, w,", "3) # ux, vx, wx ux = np.matmul(points, u.T) # (n, m) vx", "the intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not", "-l] y_corners = [h, -h, -h, h, h, -h, -h, h] z_corners =", "points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes: np.array (m, 8, 3)", "clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s = inputList[-1]", "in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif", "* (p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] -", "axis direction ''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2))", "with (x, y, z) is the box center (dx, dy, dz) as the", "3] return [l, w, h] def get_heading_angle(box): \"\"\" Args: box: (8, 3) Returns:", "= np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding", "= box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol / (vol1 + vol2 -", "0] - box[1, 0] b = box[0, 1] - box[1, 1] heading_angle =", "are in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)]", "negative Y Output: iou: 3D bounding box IoU iou_2d: bird's eye view 2D", "np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :] += center[1] corners_3d[2,", "l, h, w = [i / 2 for i in size] center =", "+= center[0] corners_3d[1, :] += center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def", "box: 8x3 Returns: size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5,", "2 -------- 1 Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz,", "6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4", "1, 1]] ) / 2. # corners3d: of shape (N, 3, 8) corners3d", "Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of", "mask: np.array (n, m) of type bool \"\"\" if len(boxes) == 0: return", "a list of (x,y) vertex point for the intersection polygon. \"\"\" def inside(p):", "iou: 3D bounding box IoU iou_2d: bird's eye view 2D bounding box IoU", "-1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1, -1, 1],", "elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 if len(outputList) == 0:", "Input: corners1: numpy array (8,3), assume up direction is negative Y corners2: numpy", "heading_angle: float \"\"\" a = box[0, 0] - box[1, 0] b = box[0,", "it consistently # Add comments of explanation import numpy as np import scipy.spatial", "2 for i in size] center = np.reshape(center, (-1, 3)) center = center.reshape(3)", "any polygon. clipPolygon: a list of (x,y) 2d points, has to be *convex*", "vp7) mask_w = np.logical_and(wx <= wp6, wx >= wp2) mask = mask_u &", "s = e cp1 = cp2 if len(outputList) == 0: return None return", "poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(),", "template = np.array([[1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1,", "boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes: np.array (m, 8, 3) Returns:", "* e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1]", "return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5", "(8,3), assume up direction is negative Y Output: iou: 3D bounding box IoU", "box center Returns: corners: (N, 8, 3) \"\"\" template = np.array([[1, 1, -1],", "Returns: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading] with (x,", "6]).reshape( -1, 8, 3 ) corners3d += boxes3d[:, None, 0:3] return corners3d def", "IoU iou_2d: bird's eye view 2D bounding box IoU ''' # corner points", "for the intersection polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0]) * (p[1]", "center (dx, dy, dz) as the box size and heading as the clockwise", "np.logical_and(wx <= wp6, wx >= wp2) mask = mask_u & mask_v & mask_w", "= np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a", "ordered** Return: a list of (x,y) vertex point for the intersection polygon. \"\"\"", "heading], (x, y, z) is the box center Returns: corners: (N, 8, 3)", "0 |/ |/ 2 -------- 1 Args: corners: (N, 8, 3), vertex order", "6, :], axis=1) vp7 = np.sum(v * boxes[:, 7, :], axis=1) wp6 =", ":]) boxes3d[i, 6] = get_heading_angle(corners3d[i, :, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7", ":] += center[0] corners_3d[1, :] += center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d)", "= np.logical_and(vx <= vp6, vx >= vp7) mask_w = np.logical_and(wx <= wp6, wx", "# corner points are in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for", "box size and heading as the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0],", "box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU. Input: corners1: numpy array (8,3),", "= [w, w, w, w, -w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat),", "boxes[:, 6, :], axis=1) vp7 = np.sum(v * boxes[:, 7, :], axis=1) wp6", "= np.logical_and(ux <= up6, ux >= up5) # (1024, n) mask_v = np.logical_and(vx", "the box center (dx, dy, dz) as the box size and heading as", "another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d points, any", "two convex hull's intersection area. p1,p2 are a list of (x,y) tuples of", "consistently # Add comments of explanation import numpy as np import scipy.spatial from", "ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol / (vol1 +", "== 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3] # get xyz", "e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection())", ":], axis=1) vp6 = np.sum(v * boxes[:, 6, :], axis=1) vp7 = np.sum(v", "boxes[:, 6, :] - boxes[:, 7, :] # (m, 3) # w =", "vx, wx ux = np.matmul(points, u.T) # (n, m) vx = np.matmul(points, v.T)", "''' a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c =", "- corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return", "return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU. Input: corners1:", "a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2)) b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2)) c = np.sqrt(np.sum((corners[0,:]", "np.array (n, m) of type bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0],", "= np.sum(w * boxes[:, 6, :], axis=1) wp2 = np.sum(w * boxes[:, 2,", "the intersection polygon. \"\"\" def inside(p): return (cp2[0] - cp1[0]) * (p[1] -", ":] # (m, 3) # v = p6 - p7 v = boxes[:,", "volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is not None: hull_inter = scipy.spatial.ConvexHull(inter_p)", ":], axis=1) up5 = np.sum(u * boxes[:, 5, :], axis=1) vp6 = np.sum(v", "z_corners = [w, w, w, w, -w, -w, -w, -w] corners_3d = np.dot(", "3) Returns: corners: (8, 3) \"\"\" l, h, w = [i / 2", "cp1 = cp2 if len(outputList) == 0: return None return (outputList) def convex_hull_intersection(p1,", "order rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1])", "not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2", "def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 . |", ":], axis=1) wp6 = np.sum(w * boxes[:, 6, :], axis=1) wp2 = np.sum(w", "inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2 = box3d_vol(corners2) iou = inter_vol", "bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:,", "the box size and heading as the clockwise rotation angle \"\"\" boxes3d =", "= np.matmul(points, w.T) # up6, up5, vp6, vp7, wp6, wp2 up6 = np.sum(u", "\"\"\" a = box[0, 0] - box[1, 0] b = box[0, 1] -", "box3d_vol(corners): ''' corners: (8,3) no assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:]", "7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :], axis=0) boxes3d[i,", "i in size] center = np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners =", "center[0] corners_3d[1, :] += center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d):", "l = distance[0, 2] w = distance[0, 0] h = distance[0, 3] return", "/ 2. # corners3d: of shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None,", "(n, m) vx = np.matmul(points, v.T) wx = np.matmul(points, w.T) # up6, up5,", "cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] *", "1, -1], [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1,", "box[1, 0] b = box[0, 1] - box[1, 1] heading_angle = np.arctan2(a, b)", "c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2)) return a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D", "= boxes[:, 6, :] - boxes[:, 2, :] # (m, 3) # ux,", "\"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1], dtype=np.bool) points = points[:, :3]", "return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1]", ".rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx, dy,", "''' corners: (8,3) no assumption on axis direction ''' a = np.sqrt(np.sum((corners[0,:] -", ":, :]) return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6", "1 Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x,", "points = points[:, :3] # get xyz # u = p6 - p5", "poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon): \"\"\" Clip a", "be *convex* Note: **points have to be counter-clockwise ordered** Return: a list of", "> (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0]", "* e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])", "counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 =", "3+d) boxes: np.array (m, 8, 3) Returns: mask: np.array (n, m) of type", "in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area =", "- box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle def compute_box_3d(size, center, rotmat):", "np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 .", "Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon:", "corners: (N, 8, 3), vertex order shown in figure above Returns: boxes3d: (N,", "is not None: hull_inter = scipy.spatial.ConvexHull(inter_p) return inter_p, hull_inter.volume else: return None, 0.0", "e[1]] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0]", ":, :], axis=0) boxes3d[i, 3:6] = get_size(corners3d[i, :, :]) boxes3d[i, 6] = get_heading_angle(corners3d[i,", "up5 = np.sum(u * boxes[:, 5, :], axis=1) vp6 = np.sum(v * boxes[:,", "inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption", "6, :], axis=1) wp2 = np.sum(w * boxes[:, 2, :], axis=1) mask_u =", "e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]", "Args: box: 8x3 Returns: size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :],", "def points_in_boxes(points, boxes): \"\"\" Args: pc: np.array (n, 3+d) boxes: np.array (m, 8,", "Output: iou: 3D bounding box IoU iou_2d: bird's eye view 2D bounding box", "n) return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon,", "3D bounding box IoU. Input: corners1: numpy array (8,3), assume up direction is", "(8, 3) \"\"\" l, h, w = [i / 2 for i in", "points[:, :3] # get xyz # u = p6 - p5 u =", "return inter_p, hull_inter.volume else: return None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no", "(p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def computeIntersection():", "return mask def poly_area(x,y): \"\"\" Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates \"\"\" return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def polygon_clip(subjectPolygon, clipPolygon):", "None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption on axis direction '''", "|/ |/ 2 -------- 1 Args: corners: (N, 8, 3), vertex order shown", "[l, l, -l, -l, l, l, -l, -l] y_corners = [h, -h, -h,", "ux, vx, wx ux = np.matmul(points, u.T) # (n, m) vx = np.matmul(points,", "- s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1]", "rect1 = [(corners1[i,0], corners1[i,1]) for i in range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for", "corners: (N, 8, 3) \"\"\" template = np.array([[1, 1, -1], [1, -1, -1],", "p6 - p2 w = boxes[:, 6, :] - boxes[:, 2, :] #", "(p[0] - cp1[0]) def computeIntersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]]", "Add comments of explanation import numpy as np import scipy.spatial from .rotation import", "iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol =", "Compute 3D bounding box IoU. Input: corners1: numpy array (8,3), assume up direction", "outputList = [] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex", "cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] -", "3) # w = p6 - p2 w = boxes[:, 6, :] -", "dp[1] - n2 * dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1]", "boxes[:, 6, :], axis=1) wp2 = np.sum(w * boxes[:, 2, :], axis=1) mask_u", "[h, -h, -h, h, h, -h, -h, h] z_corners = [w, w, w,", "# Add comments of explanation import numpy as np import scipy.spatial from .rotation", "direction is negative Y Output: iou: 3D bounding box IoU iou_2d: bird's eye", "# u = p6 - p5 u = boxes[:, 6, :] - boxes[:,", "vp7 = np.sum(v * boxes[:, 7, :], axis=1) wp6 = np.sum(w * boxes[:,", "Args: corners: (N, 8, 3), vertex order shown in figure above Returns: boxes3d:", "-------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y,", "== 0: return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of", "cp2 if len(outputList) == 0: return None return (outputList) def convex_hull_intersection(p1, p2): \"\"\"", "points are in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1]) for i in", "shape (N, 3, 8) corners3d = np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) *", "|/ 2 -------- 1 Args: corners: (N, 8, 3), vertex order shown in", "# up6, up5, vp6, vp7, wp6, wp2 up6 = np.sum(u * boxes[:, 6,", "**points have to be counter-clockwise ordered** Return: a list of (x,y) vertex point", "center = center.reshape(3) x_corners = [l, l, -l, -l, l, l, -l, -l]", "bounding box IoU iou_2d: bird's eye view 2D bounding box IoU ''' #", "- p2 w = boxes[:, 6, :] - boxes[:, 2, :] # (m,", "return boxes3d def boxes_to_corners_3d(boxes3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5", "boxes[:, 2, :], axis=1) mask_u = np.logical_and(ux <= up6, ux >= up5) #", "+= center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6", "dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0],", "w = [i / 2 for i in size] center = np.reshape(center, (-1,", "boxes[:, 6, :] - boxes[:, 2, :] # (m, 3) # ux, vx,", "list of (x,y) vertex point for the intersection polygon. \"\"\" def inside(p): return", "IoU. Input: corners1: numpy array (8,3), assume up direction is negative Y corners2:", "-h, h, h, -h, -h, h] z_corners = [w, w, w, w, -w,", "def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6 -------- 5 . |", "corners3d += boxes3d[:, None, 0:3] return corners3d def points_in_boxes(points, boxes): \"\"\" Args: pc:", "= p6 - p2 w = boxes[:, 6, :] - boxes[:, 2, :]", "= box[0, 0] - box[1, 0] b = box[0, 1] - box[1, 1]", "vp7, wp6, wp2 up6 = np.sum(u * boxes[:, 6, :], axis=1) up5 =", "dp = [s[0] - e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1]", "dz, heading], (x, y, z) is the box center Returns: corners: (N, 8,", "def box3d_vol(corners): ''' corners: (8,3) no assumption on axis direction ''' a =", "2, :] # (m, 3) # ux, vx, wx ux = np.matmul(points, u.T)", "hull vertices. return a list of (x,y) for the intersection and its volume", "None return (outputList) def convex_hull_intersection(p1, p2): \"\"\" Compute area of two convex hull's", "l, -l, -l, l, l, -l, -l] y_corners = [h, -h, -h, h,", "axis=1) vp7 = np.sum(v * boxes[:, 7, :], axis=1) wp6 = np.sum(w *", "w, w, w, -w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners,", "= clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList", "top and use it consistently # Add comments of explanation import numpy as", "(x, y, z) is the box center Returns: corners: (N, 8, 3) \"\"\"", "range(3,-1,-1)] rect2 = [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1])", "\"\"\" template = np.array([[1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1,", "a*b*c def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU. Input: corners1: numpy", "2, :], axis=1) mask_u = np.logical_and(ux <= up6, ux >= up5) # (1024,", "inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area) ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin", "np.sum(u * boxes[:, 6, :], axis=1) up5 = np.sum(u * boxes[:, 5, :],", "subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList =", "subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e)", "np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d = inter_area/(area1+area2-inter_area)", "<= wp6, wx >= wp2) mask = mask_u & mask_v & mask_w #", "p5 u = boxes[:, 6, :] - boxes[:, 5, :] # (m, 3)", ":], box[1:5, :]) l = distance[0, 2] w = distance[0, 0] h =", "rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3]", "= boxes[:, 6, :] - boxes[:, 5, :] # (m, 3) # v", "(n, m) of type bool \"\"\" if len(boxes) == 0: return np.zeros([points.shape[0], 1],", "center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 -------- 4 /| /| 6 --------", "= max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0, ymax-ymin) vol1 = box3d_vol(corners1) vol2", "convex hull's intersection area. p1,p2 are a list of (x,y) tuples of hull", "[-1, -1, 1], [-1, 1, 1]] ) / 2. # corners3d: of shape", "1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1]] ) /", "Returns: heading_angle: float \"\"\" a = box[0, 0] - box[1, 0] b =", "to be *convex* Note: **points have to be counter-clockwise ordered** Return: a list", "clipPolygon): \"\"\" Clip a polygon with another polygon. Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python Args: subjectPolygon: a", "np.logical_and(ux <= up6, ux >= up5) # (1024, n) mask_v = np.logical_and(vx <=", ">= vp7) mask_w = np.logical_and(wx <= wp6, wx >= wp2) mask = mask_u", "[dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0,", "center = np.reshape(center, (-1, 3)) center = center.reshape(3) x_corners = [l, l, -l,", "range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1,", "= poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d", "area. p1,p2 are a list of (x,y) tuples of hull vertices. return a", ":], axis=1) vp7 = np.sum(v * boxes[:, 7, :], axis=1) wp6 = np.sum(w", "return None, 0.0 def box3d_vol(corners): ''' corners: (8,3) no assumption on axis direction", "(n, 3+d) boxes: np.array (m, 8, 3) Returns: mask: np.array (n, m) of", "vertices. return a list of (x,y) for the intersection and its volume \"\"\"", "[(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0],", "corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1,", "Returns: corners: (N, 8, 3) \"\"\" template = np.array([[1, 1, -1], [1, -1,", "- e[1]] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 =", "z) is the box center (dx, dy, dz) as the box size and", "* cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 =", "= distance[0, 0] h = distance[0, 3] return [l, w, h] def get_heading_angle(box):", "[w, w, w, w, -w, -w, -w, -w] corners_3d = np.dot( np.transpose(rotmat), np.vstack([x_corners,", "= center.reshape(3) x_corners = [l, l, -l, -l, l, l, -l, -l] y_corners", "np.matmul(points, u.T) # (n, m) vx = np.matmul(points, v.T) wx = np.matmul(points, w.T)", "poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area = convex_hull_intersection(rect1, rect2) iou_2d =", "np.array([[1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1,", "clipVertex inputList = outputList outputList = [] s = inputList[-1] for subjectVertex in", "dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3] outputList", "def compute_box_3d(size, center, rotmat): \"\"\"Compute corners of a single box from rotation matrix", "import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns:", "if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e", "a list of (x,y) tuples of hull vertices. return a list of (x,y)", "box IoU ''' # corner points are in counter clockwise order rect1 =", "= [(corners2[i,0], corners2[i,1]) for i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 =", "= clipVertex inputList = outputList outputList = [] s = inputList[-1] for subjectVertex", "np.dot( np.transpose(rotmat), np.vstack([x_corners, y_corners, z_corners]) ) corners_3d[0, :] += center[0] corners_3d[1, :] +=", "np.tile(boxes3d[:, None, 3:6], (1, 8, 1)) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.reshape(-1,", "(x, y, z) is the box center (dx, dy, dz) as the box", "= np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i, :3] = np.mean(corners3d[i, :, :],", "boxes[:, 6, :], axis=1) up5 = np.sum(u * boxes[:, 5, :], axis=1) vp6", "has to be *convex* Note: **points have to be counter-clockwise ordered** Return: a", "4 /| /| 6 -------- 5 . | | | | . 3", "size: [dx, dy, dz] \"\"\" distance = scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l =", "clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in range(corners3d.shape[0]): boxes3d[i,", "numpy array (8,3), assume up direction is negative Y corners2: numpy array (8,3),", "dz) as the box size and heading as the clockwise rotation angle \"\"\"", ":] += center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7", ":] # (m, 3) # w = p6 - p2 w = boxes[:,", "-1, -1], [-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1, -1,", "i in range(3,-1,-1)] area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1]) area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1]) inter, inter_area", "pc: np.array (n, 3+d) boxes: np.array (m, 8, 3) Returns: mask: np.array (n,", "rotate_points_along_z def get_size(box): \"\"\" Args: box: 8x3 Returns: size: [dx, dy, dz] \"\"\"", "+= center[1] corners_3d[2, :] += center[2] return np.transpose(corners_3d) def corners_to_boxes(corners3d): \"\"\" 7 --------", "(m, 3) # w = p6 - p2 w = boxes[:, 6, :]", "float \"\"\" a = box[0, 0] - box[1, 0] b = box[0, 1]", "5, :] # (m, 3) # v = p6 - p7 v =", "= points[:, :3] # get xyz # u = p6 - p5 u", "= scipy.spatial.distance.cdist(box[0:1, :], box[1:5, :]) l = distance[0, 2] w = distance[0, 0]", "cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3", "(dc[0] * dp[1] - dc[1] * dp[0]) return [(n1 * dp[0] - n2", "b = box[0, 1] - box[1, 1] heading_angle = np.arctan2(a, b) return heading_angle", "axis=1) up5 = np.sum(u * boxes[:, 5, :], axis=1) vp6 = np.sum(v *", "-l, -l, l, l, -l, -l] y_corners = [h, -h, -h, h, h,", "\"\"\" Args: box: (8, 3) Returns: heading_angle: float \"\"\" a = box[0, 0]", "list of (x,y) for the intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2)", "ymax = min(corners1[:,2].max(), corners2[:,2].max()) ymin = max(corners1[:,2].min(), corners2[:,2].min()) inter_vol = inter_area * max(0.0,", "7) [x, y, z, dx, dy, dz, heading] with (x, y, z) is", "''' # corner points are in counter clockwise order rect1 = [(corners1[i,0], corners1[i,1])", "a list of (x,y) for the intersection and its volume \"\"\" inter_p =", "for the intersection and its volume \"\"\" inter_p = polygon_clip(p1,p2) if inter_p is", "as the clockwise rotation angle \"\"\" boxes3d = np.zeros((corners3d.shape[0], 7)) for i in", "-------- 1 Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading],", "in clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s =" ]
[ "True MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD command\", *args): self.reason =", "= True MIN_ARITY = 1 def __init__(self, reason, *args): self.reason = reason def", "\"376\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD command\",", "self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\"", "Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user, prefix):", "reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY =", "message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker", "as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY =", "user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for", "merc import feature from merc import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION", "{} Message of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line))", "motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for line in", "*args): self.reason = reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\"", "the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def", "__init__(self, reason=\"End of /MOTD command\", *args): self.reason = reason def as_reply_params(self): return [self.reason]", "merc import config from merc import feature from merc import message class MotdFeature(feature.Feature):", "str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY = 1 def", "True MIN_ARITY = 1 def __init__(self, line, *args): self.line = line def as_reply_params(self):", "reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True", "True MIN_ARITY = 1 def __init__(self, reason, *args): self.reason = reason def as_reply_params(self):", "def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY", "config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY = 1", "reason, *args): self.reason = reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME =", "MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart(", "MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING", "def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True", "= 1 def __init__(self, line, *args): self.line = line def as_reply_params(self): return [self.line]", "app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name)))", "__name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str)", "return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY = 1", "from merc import config from merc import feature from merc import message class", "\"- {} Message of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" +", "'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME", "MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, line,", "motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def send_motd_on_welcome(app, user): user.on_message(app, user.hostmask, Motd())", "= \"375\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason, *args): self.reason", "return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY = 1", "= True MIN_ARITY = 1 def __init__(self, line, *args): self.line = line def", "line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def send_motd_on_welcome(app, user): user.on_message(app,", "line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True", "[self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self,", "0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {}", "Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def send_motd_on_welcome(app,", "NAME = __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return", "FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, line, *args): self.line = line", "class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user,", "command\", *args): self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME", "\"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__)", "\"372\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, line, *args): self.line =", "1 def __init__(self, reason, *args): self.reason = reason def as_reply_params(self): return [self.reason] class", "install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME =", "= 0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"-", "prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for line", "class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self,", "*args): self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME =", "@message.Command.requires_registration def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message", "import config from merc import feature from merc import message class MotdFeature(feature.Feature): NAME", "*args): self.line = line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\"", "MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section):", "of /MOTD command\", *args): self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class", "[self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY = 1 def", "user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \"", "self.line = line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING", "class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self,", "from merc import feature from merc import message class MotdFeature(feature.Feature): NAME = __name__", "import feature from merc import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION =", "Message of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd())", "1 def __init__(self, reason=\"End of /MOTD command\", *args): self.reason = reason def as_reply_params(self):", "class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self,", "app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"-", "= \"376\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD", "return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def", "def handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of", "of the Day\".format(app.server.name))) for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\")", "def __init__(self, line, *args): self.line = line def as_reply_params(self): return [self.line] class MotdStart(message.Reply):", "merc import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install =", "@MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING =", "def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY", "line, *args): self.line = line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME =", "check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY", "from merc import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install", "MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD command\", *args): self.reason = reason", "= line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING =", "def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0", "handle_for(self, app, user, prefix): motd = app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the", "as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY =", "MIN_ARITY = 1 def __init__(self, reason, *args): self.reason = reason def as_reply_params(self): return", "MIN_ARITY = 1 def __init__(self, line, *args): self.line = line def as_reply_params(self): return", "FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason, *args): self.reason = reason", "NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd", "reason=\"End of /MOTD command\", *args): self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command", "import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install", "EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason=\"End", "CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class", "NAME = \"376\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason=\"End of", "def __init__(self, reason=\"End of /MOTD command\", *args): self.reason = reason def as_reply_params(self): return", "= 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply):", "NAME = \"372\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, line, *args):", "= reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY", "MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason,", "/MOTD command\", *args): self.reason = reason def as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command):", "FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD command\", *args):", "\"375\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason, *args): self.reason =", "= \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app, user, prefix): motd =", "__init__(self, line, *args): self.line = line def as_reply_params(self): return [self.line] class MotdStart(message.Reply): NAME", "= __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section,", "self.reason = reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING", "NAME = \"375\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, reason, *args):", "= MotdFeature.install @MotdFeature.register_config_checker def check_config(section): return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\"", "__init__(self, reason, *args): self.reason = reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME", "feature from merc import message class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd'", "= 1 def __init__(self, reason=\"End of /MOTD command\", *args): self.reason = reason def", "return config.validate(section, str) class MotdReply(message.Reply): NAME = \"372\" FORCE_TRAILING = True MIN_ARITY =", "class MotdFeature(feature.Feature): NAME = __name__ CONFIG_SECTION = 'motd' install = MotdFeature.install @MotdFeature.register_config_checker def", "= app.features.get_config_section(__name__) user.send_reply(MotdStart( \"- {} Message of the Day\".format(app.server.name))) for line in motd.splitlines():", "= True MIN_ARITY = 1 def __init__(self, reason=\"End of /MOTD command\", *args): self.reason", "= \"372\" FORCE_TRAILING = True MIN_ARITY = 1 def __init__(self, line, *args): self.line", "[self.line] class MotdStart(message.Reply): NAME = \"375\" FORCE_TRAILING = True MIN_ARITY = 1 def", "1 def __init__(self, line, *args): self.line = line def as_reply_params(self): return [self.line] class", "@MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration def handle_for(self, app,", "def __init__(self, reason, *args): self.reason = reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply):", "as_reply_params(self): return [self.reason] @MotdFeature.register_user_command class Motd(message.Command): NAME = \"MOTD\" MIN_ARITY = 0 @message.Command.requires_registration", "config from merc import feature from merc import message class MotdFeature(feature.Feature): NAME =", "= reason def as_reply_params(self): return [self.reason] class EndOfMotd(message.Reply): NAME = \"376\" FORCE_TRAILING =", "= 1 def __init__(self, reason, *args): self.reason = reason def as_reply_params(self): return [self.reason]", "for line in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def send_motd_on_welcome(app, user):", "in motd.splitlines(): user.send_reply(MotdReply(\"- \" + line)) user.send_reply(EndOfMotd()) @MotdFeature.hook(\"user.welcome\") def send_motd_on_welcome(app, user): user.on_message(app, user.hostmask," ]
[ "= {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def", "78) pop = [] for population in results: pop_dict = {} pop_dict[\"ID\"] =", "def pop(ID): results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop", "new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save", "= demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] =", "= total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID)", "= total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] =", "population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980", "Race = Base.classes.race Crime = Base.classes.crime # Create our session (link) from Python", "template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters", "import numpy as np import pandas as pd from flask import ( Flask,", "= Base.classes.crime # Create our session (link) from Python to the DB session", "all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = []", "Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race", "in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] =", "twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle", "pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940", "{} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID):", "race.append(demo_dict) race_data = jsonify(race) # query the neighborhood data for chart based off", "for hood in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods", "= crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def", "= session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in neighborhoods: hood_dict = {}", "neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data =", "from sqlalchemy.orm import Session from sqlalchemy import create_engine, func ################################################# # Flask Setup", "return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\") if __name__ == '__main__':", "into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True)", "jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities =", "as np import pandas as pd from flask import ( Flask, render_template, jsonify,", "for comm in results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community", "crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes():", "(link) from Python to the DB session = Session(engine) ################################################# # Flask Routes", "crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data)", "crime_data = [] for crime in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id", "Base.classes.crime # Create our session (link) from Python to the DB session =", "session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"]", "results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities)", "comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id ==", "all_names.append(comm_dict) name = jsonify(all_names) # query for community twitter handle based off of", "= crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] =", "demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the neighborhood data for", "population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015", "Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime", "crime in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"]", "crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago", "demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the neighborhood data for chart based", "results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940", "pd from flask import ( Flask, render_template, jsonify, request, redirect) import sqlalchemy from", "pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"]", "names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) # query", "= crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template", "return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id", "pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"]", "demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"]", "session.query(Communities).filter(Communities.id == ID) all_names = [] for name in names: comm_dict = {}", "reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table Communities =", "demographics = session.query(Race).filter(Race.id == ID) race = [] for demo in demographics: demo_dict", "= jsonify(handles) # query the population data for chart based off of ID", "################################################# app = Flask(__name__) ################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") #", "for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930", "= hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data for chart based", "= total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return", "Base.classes.population Race = Base.classes.race Crime = Base.classes.crime # Create our session (link) from", "jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict)", "= total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data", "#render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the", "population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970", "@app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID) race = [] for demo", "pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"]", "= demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID)", "demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\")", "pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"]", "@app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm", "twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in twitters:", "query for community twitter handle based off of ID twitters = session.query(Twitter).filter(Twitter.id ==", "based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood", "# Save reference to the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter", "twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query", "in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return", "= population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"]", "Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime = Base.classes.crime # Create our", "total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015", "race = [] for demo in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id", "demo in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"]", "twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in twitters: handle_dict", "# query the race data for chart based off of ID demographics =", "for name in names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name =", "= jsonify(all_names) # query for community twitter handle based off of ID twitters", "def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm in", "= population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] =", "Setup ################################################# app = Flask(__name__) ################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\")", "Base.classes.race Crime = Base.classes.crime # Create our session (link) from Python to the", "= population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total", "jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \"", "crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict)", "to the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population", "ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in twitters:", "return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data = []", "= Base.classes.race Crime = Base.classes.crime # Create our session (link) from Python to", "comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) # query for community twitter handle", "table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population", "demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data", "pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"]", "hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\")", "<reponame>jessicagtz/Project-2-Chicago-Communities import datetime as dt import numpy as np import pandas as pd", "Routes ################################################# @app.route(\"/\") def index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def", "handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population data for", "in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] =", "= total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] =", "def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\") if __name__", "the crime data for chart based off of ID crimes = session.query(Crime).filter(Crime.id ==", "hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id ==", "pandas as pd from flask import ( Flask, render_template, jsonify, request, redirect) import", "the neighborhood data for chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID)", "comm in results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict)", "demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015", "# reflect an existing database into a new model Base = automap_base() #", "name in names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names)", "= population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] =", "= name.community all_names.append(comm_dict) name = jsonify(all_names) # query for community twitter handle based", "= [] for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"]", "off of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime", "{} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population data", "ID) all_communities = [] for comm in results: comm_dict = {} comm_dict[\"ID\"] =", "all_communities = [] for comm in results: comm_dict = {} comm_dict[\"ID\"] = comm.id", "population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960", "off of ID selected names = session.query(Communities).filter(Communities.id == ID) all_names = [] for", "comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID)", "= crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return", "@app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>,", "= population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] =", "of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in neighborhoods:", "of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in", "query for the community name based off of ID selected names = session.query(Communities).filter(Communities.id", "{} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID):", "based off of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for", "jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID) race = [] for", "names = session.query(Communities).filter(Communities.id == ID) all_names = [] for name in names: comm_dict", "name based off of ID selected names = session.query(Communities).filter(Communities.id == ID) all_names =", "results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods)", "= Flask(__name__) ################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an", "# Flask Routes ################################################# @app.route(\"/\") def index(): #render the index template return render_template(\"index.html\")", "= demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes =", "[] for demo in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] =", "totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960", "pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict)", "= population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total", "for community twitter handle based off of ID twitters = session.query(Twitter).filter(Twitter.id == ID)", "for chart based off of ID results = session.query(Population).filter(Population.id == ID) totals =", "#query the crime data for chart based off of ID crimes = session.query(Crime).filter(Crime.id", "population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000", "existing database into a new model Base = automap_base() # reflect the tables", "race(ID): demographics = session.query(Race).filter(Race.id == ID) race = [] for demo in demographics:", "flask import ( Flask, render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import", "import create_engine, func ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# #", "= jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict,", "population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010", "population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015", "twitter handle based off of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles =", "population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"]", "query the race data for chart based off of ID demographics = session.query(Race).filter(Race.id", "off of ID results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78)", "comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\")", "demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race)", "handle based off of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles = []", "= crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) #", "chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for", "our session (link) from Python to the DB session = Session(engine) ################################################# #", "crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"]", "population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total in", "in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] =", "crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community", "== ID) all_names = [] for name in names: comm_dict = {} comm_dict[\"name\"]", "pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics", "of ID selected names = session.query(Communities).filter(Communities.id == ID) all_names = [] for name", "= crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict,", "= population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] =", "sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func #################################################", "@app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78)", "pop = [] for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id", "crime data for chart based off of ID crimes = session.query(Crime).filter(Crime.id == ID)", "hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID) totals", "ID demographics = session.query(Race).filter(Race.id == ID) race = [] for demo in demographics:", "as dt import numpy as np import pandas as pd from flask import", "neighborhood data for chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods", "reflect an existing database into a new model Base = automap_base() # reflect", "= comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results =", "= session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop = [] for", "= [] for handle in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict)", "database into a new model Base = automap_base() # reflect the tables Base.prepare(engine,", "= session.query(Population).filter(Population.id == 78) pop = [] for population in results: pop_dict =", "hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results", "pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"]", "from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func", "= jsonify(race) # query the neighborhood data for chart based off of ID", "[] for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] =", "in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return", "from Python to the DB session = Session(engine) ################################################# # Flask Routes #################################################", "= population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] =", "== ID) totals = session.query(Population).filter(Population.id == 78) pop = [] for population in", "total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"]", "an existing database into a new model Base = automap_base() # reflect the", "= total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) #", "total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop)", "for the community name based off of ID selected names = session.query(Communities).filter(Communities.id ==", "off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in", "name.community all_names.append(comm_dict) name = jsonify(all_names) # query for community twitter handle based off", "chart based off of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data = []", "Flask, render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm", "== ID) handles = [] for handle in twitters: handle_dict = {} handle_dict[\"handle\"]", "pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id ==", "@app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\") if", "( Flask, render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from", "Save reference to the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter =", "= automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the", "return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the community name based off", "index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for", "in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] =", "import ( Flask, render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base", "Population = Base.classes.population Race = Base.classes.race Crime = Base.classes.crime # Create our session", "pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930", "handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results", "ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in neighborhoods: hood_dict", "chart based off of ID demographics = session.query(Race).filter(Race.id == ID) race = []", "demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015", "ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in crimes:", "= session.query(Race).filter(Race.id == ID) race = [] for demo in demographics: demo_dict =", "dt import numpy as np import pandas as pd from flask import (", "hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data for chart", "crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft", "return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities = []", "handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID)", "redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy", "= {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def", "hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id", "################################################# # Flask Routes ################################################# @app.route(\"/\") def index(): #render the index template return", "= demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) #", "the community name based off of ID selected names = session.query(Communities).filter(Communities.id == ID)", "def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in", "crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\")", "chart based off of ID results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id", "total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010", "population._2010 pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] =", "Crime = Base.classes.crime # Create our session (link) from Python to the DB", "Create our session (link) from Python to the DB session = Session(engine) #################################################", "handles = [] for handle in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle", "crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"]", "pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"]", "session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop = [] for population", "== ID) crime_data = [] for crime in crimes: crime_dict = {} crime_dict[\"ID\"]", "template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the community name based", "@app.route(\"/dash/<ID>\") def dash(ID): # query for the community name based off of ID", "import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func ################################################# #", "population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990", "[] for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] =", "all_names = [] for name in names: comm_dict = {} comm_dict[\"name\"] = name.community", "[] for hood in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] =", "= {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] =", "= hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID)", "= comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods", "comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods =", "import datetime as dt import numpy as np import pandas as pd from", "numpy as np import pandas as pd from flask import ( Flask, render_template,", "pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"]", "pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"]", "population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000", "engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a new model Base", "based off of ID selected names = session.query(Communities).filter(Communities.id == ID) all_names = []", "= crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] =", "off of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle", "ID) all_names = [] for name in names: comm_dict = {} comm_dict[\"name\"] =", "= population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] =", "pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"]", "= {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] =", "for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930", "crimes2017 = jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict,", "= demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def", "# Create our session (link) from Python to the DB session = Session(engine)", "jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session", "= crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] =", "crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data)", "all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data for chart based off of", "data for chart based off of ID results = session.query(Population).filter(Population.id == ID) totals", "{} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950", "= [] for hood in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"]", "= session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in crimes: crime_dict =", "session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in crimes: crime_dict = {}", "= session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm in results: comm_dict =", "= hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results =", "= demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return", "crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in crimes: crime_dict", "= {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) # query for community", "crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>,", "= total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] =", "ID selected names = session.query(Communities).filter(Communities.id == ID) all_names = [] for name in", "@app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle", "pop.append(pop_dict) population_data = jsonify(pop) # query the race data for chart based off", "comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) # query for", "crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"]", "to the DB session = Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def", "pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles", "population_data = jsonify(pop) # query the race data for chart based off of", "return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for", "crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"]", "session (link) from Python to the DB session = Session(engine) ################################################# # Flask", "= population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"]", "session.query(Population).filter(Population.id == 78) pop = [] for population in results: pop_dict = {}", "pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940", "= population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] =", "return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters =", "= [] for demo in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"]", "= population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] =", "crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the", "for chart based off of ID demographics = session.query(Race).filter(Race.id == ID) race =", "handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the", "total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980", "from flask import ( Flask, render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap", "handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id", "population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980", "crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return", "Python to the DB session = Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\")", "== ID) race = [] for demo in demographics: demo_dict = {} demo_dict[\"ID\"]", "sqlalchemy import create_engine, func ################################################# # Flask Setup ################################################# app = Flask(__name__) #################################################", "[] for name in names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name", "twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities = [] for", "as pd from flask import ( Flask, render_template, jsonify, request, redirect) import sqlalchemy", "hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict)", "= demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data", "query the neighborhood data for chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID", "a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) #", "[] for handle in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle", "= population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] =", "pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the", "based off of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for", "demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles =", "for chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = []", "= population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] =", "== 78) pop = [] for population in results: pop_dict = {} pop_dict[\"ID\"]", "hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime", "reflect=True) # Save reference to the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods", "render_template, jsonify, request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import", "= total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the race", "hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles = []", "ID) totals = session.query(Population).filter(Population.id == 78) pop = [] for population in results:", "query the population data for chart based off of ID results = session.query(Population).filter(Population.id", "model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference", "################################################# @app.route(\"/\") def index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID):", "{} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) # query for community twitter", "total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the race data", "hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in results: hood_dict", "Flask(__name__) ################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing", "selected names = session.query(Communities).filter(Communities.id == ID) all_names = [] for name in names:", "== ID) all_communities = [] for comm in results: comm_dict = {} comm_dict[\"ID\"]", "[] for crime in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] =", "= crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] =", "total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID):", "= [] for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"]", "results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in results: hood_dict =", "off of ID demographics = session.query(Race).filter(Race.id == ID) race = [] for demo", "pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for", "crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics", "= {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] =", "pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"]", "Flask Routes ################################################# @app.route(\"/\") def index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\")", "jsonify(pop) # query the race data for chart based off of ID demographics", "total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id", "= session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in results: hood_dict = {}", "pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"]", "= crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about():", "= [] for comm in results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"]", "= crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017", "pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"]", "demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"]", "from sqlalchemy import create_engine, func ################################################# # Flask Setup ################################################# app = Flask(__name__)", "of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in", "demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID):", "neighborhood_data = jsonify(all_neighborhoods) #query the crime data for chart based off of ID", "app = Flask(__name__) ################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect", "in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] =", "= total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def", "community twitter handle based off of ID twitters = session.query(Twitter).filter(Twitter.id == ID) handles", "= total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics =", "jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for", "crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\")", "comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID", "Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to", "= jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities", "[] for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] =", "handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id ==", "= {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query", "demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id ==", "population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990", "population._1970 pop_dict[\"1980\"] = population._1980 pop_dict[\"1990\"] = population._1990 pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010", "session.query(Race).filter(Race.id == ID) race = [] for demo in demographics: demo_dict = {}", "create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a new model Base = automap_base()", "def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in results:", "race_data = jsonify(race) # query the neighborhood data for chart based off of", "results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940", "Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def index(): #render the index template", "name = jsonify(all_names) # query for community twitter handle based off of ID", "pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"]", "totals = session.query(Population).filter(Population.id == 78) pop = [] for population in results: pop_dict", "crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in crimes:", "render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\")", "index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the community name", "pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"]", "comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results", "# reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table Communities", "jsonify(race) # query the neighborhood data for chart based off of ID neighborhoods", "dash(ID): # query for the community name based off of ID selected names", "import pandas as pd from flask import ( Flask, render_template, jsonify, request, redirect)", "render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def", "for demo in demographics: demo_dict = {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015", "jsonify(handles) # query the population data for chart based off of ID results", "tables Base.prepare(engine, reflect=True) # Save reference to the table Communities = Base.classes.comm_names Neighborhoods", "jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id ==", "pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID) race =", "population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] =", "[] for comm in results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] =", "= [] for crime in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"]", "pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"]", "crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"]", "data for chart based off of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data", "def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>,", "demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"]", "the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the community", "pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"]", "pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals:", "results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop = []", "handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\")", "= crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\")", "jsonify(all_names) # query for community twitter handle based off of ID twitters =", "= population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960 pop_dict[\"1970\"] = population._1970 pop_dict[\"1980\"] =", "demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes", "results = session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm in results: comm_dict", "in results: comm_dict = {} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return", "pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\")", "data for chart based off of ID neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods =", "@app.route(\"/\") def index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): #", "= demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the neighborhood", "import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import", "################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Database Setup #################################################", "return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID) race = []", "= handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results =", "request, redirect) import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from", "{} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950", "hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data for chart based off", "render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id", "# Flask Setup ################################################# app = Flask(__name__) ################################################# # Database Setup ################################################# engine", "in names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict) name = jsonify(all_names) #", "= Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def index(): #render the index", "based off of ID results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id ==", "total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query", "np import pandas as pd from flask import ( Flask, render_template, jsonify, request,", "Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a", "render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query for the community name based off of", "def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime in", "ID) handles = [] for handle in twitters: handle_dict = {} handle_dict[\"handle\"] =", "# Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into", "all_neighborhoods = [] for hood in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID", "data for chart based off of ID demographics = session.query(Race).filter(Race.id == ID) race", "= jsonify(pop) # query the race data for chart based off of ID", "sqlalchemy.orm import Session from sqlalchemy import create_engine, func ################################################# # Flask Setup #################################################", "for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950", "jsonify(all_neighborhoods) #query the crime data for chart based off of ID crimes =", "session = Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def index(): #render the", "community name based off of ID selected names = session.query(Communities).filter(Communities.id == ID) all_names", "total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970", "= session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in twitters: handle_dict =", "{} comm_dict[\"ID\"] = comm.id comm_dict[\"Name\"] = comm.community all_communities.append(comm_dict) return jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID):", "def dash(ID): # query for the community name based off of ID selected", "handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population data for chart based", "race data for chart based off of ID demographics = session.query(Race).filter(Race.id == ID)", "race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data =", "all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def pop(ID): results = session.query(Population).filter(Population.id == ID) totals =", "= population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] =", "twitter_handle = jsonify(handles) # query the population data for chart based off of", "Base.prepare(engine, reflect=True) # Save reference to the table Communities = Base.classes.comm_names Neighborhoods =", "ID) race = [] for demo in demographics: demo_dict = {} demo_dict[\"ID\"] =", "crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 =", "total._2015 pop.append(pop_dict) return jsonify(pop) @app.route(\"/race/<ID>\") def race(ID): demographics = session.query(Race).filter(Race.id == ID) race", "based off of ID demographics = session.query(Race).filter(Race.id == ID) race = [] for", "hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods)", "in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) #", "pop_dict[\"2000\"] = population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total in totals:", "Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a new", "handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population data for chart based off", "for crime in crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery", "DB session = Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def index(): #render", "crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template return render_template(\"dashboard.html\",", "crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal", "# render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\")", "Session from sqlalchemy import create_engine, func ################################################# # Flask Setup ################################################# app =", "reference to the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter", "return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project:", "= jsonify(all_neighborhoods) #query the crime data for chart based off of ID crimes", "# query the population data for chart based off of ID results =", "@app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id == ID) crime_data = [] for crime", "the table Communities = Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population =", "population data for chart based off of ID results = session.query(Population).filter(Population.id == ID)", "population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] =", "neighborhoods = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in neighborhoods: hood_dict =", "crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict,", "demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data =", "demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race) @app.route(\"/crime/<ID>\") def crime(ID): crimes = session.query(Crime).filter(Crime.id", "the DB session = Session(engine) ################################################# # Flask Routes ################################################# @app.route(\"/\") def index():", "Flask Setup ################################################# app = Flask(__name__) ################################################# # Database Setup ################################################# engine =", "automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func ################################################# # Flask", "population._2000 pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] =", "pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for", "= total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] =", "demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query", "{} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide", "population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"_1930\"] = population._1930 pop_dict[\"_1940\"]", "session.query(Twitter).filter(Twitter.id == ID) handles = [] for handle in twitters: handle_dict = {}", "return render_template(\"crime.html\") @app.route(\"/about\") def about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>,", "jsonify(all_communities) @app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood", "of ID demographics = session.query(Race).filter(Race.id == ID) race = [] for demo in", "@app.route(\"/hoods/<ID>\") def hoods(ID): results = session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in", "about(): return(\"Chicago Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\") if __name__ ==", "pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"]", "names(ID): results = session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm in results:", "= session.query(Communities).filter(Communities.id == ID) all_names = [] for name in names: comm_dict =", "session.query(Neighborhoods).filter(Neighborhoods.ID ==ID) all_neighborhoods = [] for hood in results: hood_dict = {} hood_dict[\"ID\"]", "ID results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop =", "population._1930 pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970", "crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template return", "==ID) all_neighborhoods = [] for hood in results: hood_dict = {} hood_dict[\"ID\"] =", "crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) return jsonify(crime_data) @app.route(\"/crime\") def crimes(): return render_template(\"crime.html\") @app.route(\"/about\") def", "total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the race data for chart based", "total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data =", "= population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"]", "Twitter = Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime = Base.classes.crime #", "for handle in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle =", "= total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] =", "total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000", "population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"] = population._1960", "for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods", "# query for the community name based off of ID selected names =", "the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict, pop_dict=pop_dict, demo_dict=demo_dict, hood_dict=hood_dict, crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID):", "==ID) all_neighborhoods = [] for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] =", "handle in twitters: handle_dict = {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles)", "= hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data", "pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the race data for", "= [] for population in results: pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"]", "pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"] = population._1950 pop_dict[\"1960\"]", "= population._1970 pop_dict[\"_1980\"] = population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] =", "demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the neighborhood data", "################################################# # Database Setup ################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database", "ID) crime_data = [] for crime in crimes: crime_dict = {} crime_dict[\"ID\"] =", "hood in results: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict)", "{} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015", "in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data", "sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine,", "= Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race =", "pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] = total._2015 pop.append(pop_dict) population_data = jsonify(pop)", "= create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a new model Base =", "all_neighborhoods = [] for hood in neighborhoods: hood_dict = {} hood_dict[\"ID\"] = hood.ID", "demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the", "{} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the", "hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) neighborhood_data = jsonify(all_neighborhoods) #query the crime data for", "= demo.white2015 race.append(demo_dict) race_data = jsonify(race) # query the neighborhood data for chart", "the population data for chart based off of ID results = session.query(Population).filter(Population.id ==", "= demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] =", "pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"] = total._1940 pop_dict[\"all_1950\"] = total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"]", "import Session from sqlalchemy import create_engine, func ################################################# # Flask Setup ################################################# app", "for chart based off of ID crimes = session.query(Crime).filter(Crime.id == ID) crime_data =", "func ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Database Setup", "def index(): #render the index template return render_template(\"index.html\") @app.route(\"/dash/<ID>\") def dash(ID): # query", "= {} demo_dict[\"ID\"] = demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] =", "demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict) return jsonify(race)", "crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render the template return render_template(\"dashboard.html\", comm_dict=comm_dict, handle_dict=handle_dict,", "Base.classes.comm_names Neighborhoods = Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race = Base.classes.race", "= {} hood_dict[\"ID\"] = hood.ID hood_dict[\"Neighborhoods\"] = hood.neighborhoods all_neighborhoods.append(hood_dict) return jsonify(all_neighborhoods) @app.route(\"/pop/<ID>\") def", "= total._2015 pop.append(pop_dict) population_data = jsonify(pop) # query the race data for chart", "twitter_handle = jsonify(handles) return twitter_handle @app.route(\"/names/<ID>\") def names(ID): results = session.query(Communities).filter(Communities.id == ID)", "= population._1980 pop_dict[\"_1990\"] = population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] =", "crime.non_criminal crime_dict[\"sexual\"] = crime.sexual crime_dict[\"theft\"] = crime.theft crime_data.append(crime_dict) crimes2017 = jsonify(crime_data) # render", "= Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime =", "# query the neighborhood data for chart based off of ID neighborhoods =", "Base.classes.neighborhoods Twitter = Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime = Base.classes.crime", "pop_dict = {} pop_dict[\"ID\"] = population.id pop_dict[\"1930\"] = population._1930 pop_dict[\"1940\"] = population._1940 pop_dict[\"1950\"]", "= {} handle_dict[\"handle\"] = handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population", "crime.deceptive_practice crime_dict[\"homicide\"] = crime.homicide crime_dict[\"narcotics\"] = crime.narcotics crime_dict[\"non_criminal\"] = crime.non_criminal crime_dict[\"sexual\"] = crime.sexual", "the race data for chart based off of ID demographics = session.query(Race).filter(Race.id ==", "population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] =", "create_engine, func ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Database", "################################################# engine = create_engine(\"sqlite:///chi_db.sqlite\") # reflect an existing database into a new model", "the tables Base.prepare(engine, reflect=True) # Save reference to the table Communities = Base.classes.comm_names", "pop(ID): results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop =", "of ID results = session.query(Population).filter(Population.id == ID) totals = session.query(Population).filter(Population.id == 78) pop", "pop_dict[\"_1940\"] = population._1940 pop_dict[\"_1950\"] = population._1950 pop_dict[\"_1960\"] = population._1960 pop_dict[\"_1970\"] = population._1970 pop_dict[\"_1980\"]", "crime_dict=crime_dict) @app.route(\"/twitter/<ID>\") def twitter(ID): twitters = session.query(Twitter).filter(Twitter.id == ID) handles = [] for", "pop_dict[\"2010\"] = population._2010 pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930", "= [] for name in names: comm_dict = {} comm_dict[\"name\"] = name.community all_names.append(comm_dict)", "demo.id demo_dict[\"asian2015\"] = demo.asian2015 demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015", "# query for community twitter handle based off of ID twitters = session.query(Twitter).filter(Twitter.id", "demo_dict[\"black2015\"] = demo.black2015 demo_dict[\"hispanic2015\"] = demo.hispanic2015 demo_dict[\"other2015\"] = demo.other2015 demo_dict[\"white2015\"] = demo.white2015 race.append(demo_dict)", "= handle.twitter_handle handles.append(handle_dict) twitter_handle = jsonify(handles) # query the population data for chart", "automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table", "Community Project: \" \"<NAME>, <NAME>, <NAME>, <NAME>, <NAME>\") if __name__ == '__main__': app.run(debug=True)", "= population._2010 pop_dict[\"2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"]", "= population._2010 pop_dict[\"_2015\"] = population._2015 for total in totals: pop_dict[\"all_1930\"] = total._1930 pop_dict[\"all_1940\"]", "= total._1980 pop_dict[\"all_1990\"] = total._1990 pop_dict[\"all_2000\"] = total._2000 pop_dict[\"all_2010\"] = total._2010 pop_dict[\"all_2015\"] =", "session.query(Communities).filter(Communities.id == ID) all_communities = [] for comm in results: comm_dict = {}", "total._1950 pop_dict[\"all_1960\"] = total._1960 pop_dict[\"all_1970\"] = total._1970 pop_dict[\"all_1980\"] = total._1980 pop_dict[\"all_1990\"] = total._1990", "datetime as dt import numpy as np import pandas as pd from flask", "population._1990 pop_dict[\"_2000\"] = population._2000 pop_dict[\"_2010\"] = population._2010 pop_dict[\"_2015\"] = population._2015 for total in", "crimes: crime_dict = {} crime_dict[\"ID\"] = crime.id crime_dict[\"battery\"] = crime.battery crime_dict[\"deceptive_practice\"] = crime.deceptive_practice", "def race(ID): demographics = session.query(Race).filter(Race.id == ID) race = [] for demo in", "= Base.classes.population Race = Base.classes.race Crime = Base.classes.crime # Create our session (link)", "= Base.classes.twitter Population = Base.classes.population Race = Base.classes.race Crime = Base.classes.crime # Create" ]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "KIND, either express or implied. # See the License for the specific language", "permissions and # limitations under the License. from ament_index_python import get_package_share_directory from launch", "Unless required by applicable law or agreed to in writing, software # distributed", "detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean", "= Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param,", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# See the License for the specific language governing permissions and # limitations", "# limitations under the License. from ament_index_python import get_package_share_directory from launch import LaunchDescription", "import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import", "License. # You may obtain a copy of the License at # #", ") ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground", "get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file", "# Copyright 2021 the Autoware Foundation # # Licensed under the Apache License,", "generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix", "from ament_index_python import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from", "Autoware Foundation # # Licensed under the Apache License, Version 2.0 (the \"License\");", "off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "compliance with the License. # You may obtain a copy of the License", "package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service',", "launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions", "description='Path to config file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file,", "= Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out',", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter", "this file except in compliance with the License. # You may obtain a", "file for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to", "= os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle", "executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param, off_map_obstacles_filter_param,", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory(", ") ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return", "you may not use this file except in compliance with the License. #", "from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import", "def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\"", "ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "Copyright 2021 the Autoware Foundation # # Licensed under the Apache License, Version", "launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import os", "with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file',", "'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')],", "Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param,", "DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node", "description='Path to parameter file for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file',", "ANY KIND, either express or implied. # See the License for the specific", "Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[", "from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration from", "# Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\")", "under the License. from ament_index_python import get_package_share_directory from launch import LaunchDescription from launch.actions", "os def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier", "in compliance with the License. # You may obtain a copy of the", "import Node import os def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster *", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "to config file for Ray Ground Classifier' ) # Nodes euclidean_clustering = Node(", "config file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "launch_ros.actions import Node import os def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster", "use this file except in compliance with the License. # You may obtain", "ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file =", "condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions", "euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join(", "not use this file except in compliance with the License. # You may", "description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file", "'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument(", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'),", "autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles',", "('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')),", "autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' )", "= os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix,", "specific language governing permissions and # limitations under the License. from ament_index_python import", "See the License for the specific language governing permissions and # limitations under", "the specific language governing permissions and # limitations under the License. from ament_index_python", "file for Ray Ground Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe',", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration", "License, Version 2.0 (the \"License\"); # you may not use this file except", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path", "config file for Ray Ground Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes',", "namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node',", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "2021 the Autoware Foundation # # Licensed under the Apache License, Version 2.0", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", ") off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle", "# Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param =", "'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception',", "import os def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter *", ") # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\",", "'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param", "= DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering' ) off_map_obstacles_filter_param", "OF ANY KIND, either express or implied. # See the License for the", "euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join(", "'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments", "= DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle filter' )", "Ground Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')],", "2.0 (the \"License\"); # you may not use this file except in compliance", "governing permissions and # limitations under the License. from ament_index_python import get_package_share_directory from", "os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml')", "= DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file,", "# you may not use this file except in compliance with the License.", "DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering' ) off_map_obstacles_filter_param =", "euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] )", "executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] )", "the Autoware Foundation # # Licensed under the Apache License, Version 2.0 (the", "filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray", "Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for", "agreed to in writing, software # distributed under the License is distributed on", "off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param", "Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map", "obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe',", "\"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix =", "from launch_ros.actions import Node import os def generate_launch_description(): \"\"\" Launch perception nodes. *", "(the \"License\"); # you may not use this file except in compliance with", "import LaunchConfiguration from launch_ros.actions import Node import os def generate_launch_description(): \"\"\" Launch perception", "= os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param =", "'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True',", "# # Unless required by applicable law or agreed to in writing, software", "parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param, off_map_obstacles_filter_param, euclidean_clustering, ray_ground_classifier, off_map_obstacles_filter,", "express or implied. # See the License for the specific language governing permissions", "Version 2.0 (the \"License\"); # you may not use this file except in", "# Unless required by applicable law or agreed to in writing, software #", "for the specific language governing permissions and # limitations under the License. from", "except in compliance with the License. # You may obtain a copy of", "\"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join(", "autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix,", "euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering' )", "by applicable law or agreed to in writing, software # distributed under the", "for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file", "IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import os def generate_launch_description():", "DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle filter' ) ray_ground_classifier_param", "remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes',", "remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')),", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "import IfCondition from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import os def", "either express or implied. # See the License for the specific language governing", "off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml')", "default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument(", "] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground Classifier' ) # Nodes euclidean_clustering", "Node import os def generate_launch_description(): \"\"\" Launch perception nodes. * euclidean_cluster * off_map_obstacles_filter", "launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import os def generate_launch_description(): \"\"\" Launch", "(\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')],", "] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] )", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition", "import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from launch.substitutions import", "off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'),", "parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier =", "('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe',", "for Ray Ground Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception',", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "* ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file", "description='Path to config file for Ray Ground Classifier' ) # Nodes euclidean_clustering =", "from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node import os def generate_launch_description(): \"\"\"", "Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ]", "parameter file for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path", "and # limitations under the License. from ament_index_python import get_package_share_directory from launch import", "namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ]", "file except in compliance with the License. # You may obtain a copy", "off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle filter'", "remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param, off_map_obstacles_filter_param, euclidean_clustering, ray_ground_classifier, off_map_obstacles_filter, ])", "perception nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch')", "ament_index_python import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions", "obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param, off_map_obstacles_filter_param, euclidean_clustering,", "License for the specific language governing permissions and # limitations under the License.", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter file for off-map obstacle filter' ) ray_ground_classifier_param =", "\"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen',", "the License. # You may obtain a copy of the License at #", "Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument(", "Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter =", ") euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering'", "* euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file =", "to in writing, software # distributed under the License is distributed on an", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config", "ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground Classifier'", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground Classifier' ) #", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param, off_map_obstacles_filter_param, euclidean_clustering, ray_ground_classifier,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground Classifier' )", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "required by applicable law or agreed to in writing, software # distributed under", "file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path to parameter", "Ray Ground Classifier' ) # Nodes euclidean_clustering = Node( package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')),", "applicable law or agreed to in writing, software # distributed under the License", "executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes',", "default_value=euclidean_cluster_param_file, description='Path to config file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file',", "ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable", "autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') #", "limitations under the License. from ament_index_python import get_package_share_directory from launch import LaunchDescription from", "License. from ament_index_python import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument", "or agreed to in writing, software # distributed under the License is distributed", "import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import", "Foundation # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "to config file for Euclidean Clustering' ) off_map_obstacles_filter_param = DeclareLaunchArgument( 'off_map_obstacles_filter_param_file', default_value=off_map_obstacles_filter_param_file, description='Path", "condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception',", "output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node(", "package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")] ) return LaunchDescription([ euclidean_cluster_param, ray_ground_classifier_param, with_obstacles_param,", "or implied. # See the License for the specific language governing permissions and", "= get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml')", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file, description='Path to config file for Ray Ground Classifier' ) # Nodes", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument( 'with_obstacles', default_value='True', description='Enable obstacle detection'", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "* off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix,", "from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.conditions import IfCondition from", "'autoware_auto_launch') euclidean_cluster_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/euclidean_cluster.param.yaml') off_map_obstacles_filter_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file =", "name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in', 'lidar_bounding_boxes'), ('bounding_boxes_out', 'lidar_bounding_boxes_filtered'), ('HAD_Map_Service', '/had_maps/HAD_Map_Service'),", "with the License. # You may obtain a copy of the License at", "nodes. * euclidean_cluster * off_map_obstacles_filter * ray_ground_classifier \"\"\" autoware_auto_launch_pkg_prefix = get_package_share_directory( 'autoware_auto_launch') euclidean_cluster_param_file", "'with_obstacles', default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to", "language governing permissions and # limitations under the License. from ament_index_python import get_package_share_directory", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "to parameter file for off-map obstacle filter' ) ray_ground_classifier_param = DeclareLaunchArgument( 'ray_ground_classifier_param_file', default_value=ray_ground_classifier_param_file,", "'/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\", \"/lidars/points_fused\")]", "in writing, software # distributed under the License is distributed on an \"AS", "default_value='True', description='Enable obstacle detection' ) euclidean_cluster_param = DeclareLaunchArgument( 'euclidean_cluster_param_file', default_value=euclidean_cluster_param_file, description='Path to config", "package='euclidean_cluster_nodes', executable='euclidean_cluster_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('euclidean_cluster_param_file')], remappings=[ (\"points_in\", \"points_nonground\") ] ) off_map_obstacles_filter = Node(", "os.path.join( autoware_auto_launch_pkg_prefix, 'param/off_map_obstacles_filter.param.yaml') ray_ground_classifier_param_file = os.path.join( autoware_auto_launch_pkg_prefix, 'param/ray_ground_classifier.param.yaml') # Arguments with_obstacles_param = DeclareLaunchArgument(", "the License. from ament_index_python import get_package_share_directory from launch import LaunchDescription from launch.actions import", "LaunchConfiguration from launch_ros.actions import Node import os def generate_launch_description(): \"\"\" Launch perception nodes.", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "('HAD_Map_Service', '/had_maps/HAD_Map_Service'), ] ) ray_ground_classifier = Node( package='ray_ground_classifier_nodes', executable='ray_ground_classifier_cloud_node_exe', namespace='perception', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('ray_ground_classifier_param_file')], remappings=[(\"points_in\",", ") off_map_obstacles_filter = Node( package='off_map_obstacles_filter_nodes', name='off_map_obstacles_filter_node', namespace='perception', executable='off_map_obstacles_filter_nodes_exe', condition=IfCondition(LaunchConfiguration('with_obstacles')), parameters=[LaunchConfiguration('off_map_obstacles_filter_param_file')], output='screen', remappings=[ ('bounding_boxes_in'," ]
[]
[ "pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4", "lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile) except:", "try: FullList = [] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" +", "0 couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7,", "= {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12,", "os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList = [] if str(dir).endswith('.json'): continue", "json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename) ) print(\"made \" +str(count) )", "for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList", "1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py", "str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {}", "x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't", "for item in items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5])", "+ item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir +", "'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for", "+= 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3", "x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass", "<reponame>Nadern96/Realtime-Action-Recognition import os import json path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count", "import os import json path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count =", "'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for subdir, dirs,", "FullList = [] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" + str(count))", "itemList.append(dir + '/' + item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList =", "itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList =", "os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f) for item in items: itemList", "'walk':13, 'wave':14, } imagecount = 1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort()", "file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {}", "'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for subdir, dirs, files in", "+ '.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename)", "couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8,", "/home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f:", "\"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as", "items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name)", "in items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1)", "items = json.load(f) for item in items: itemList = [] class_name = dir.split('_')[0]", "= \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json')", "subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList =", "'wave':14, } imagecount = 1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for", "with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename", "dirs: try: FullList = [] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\"", "+ str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir", "+ '/' + item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList,", "open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \"", "\".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f) for item in items:", "'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for subdir,", "= [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir +", "= 1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in dirs:", "itemList = itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2])", "[] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/'", "'.txt', 'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename) )", "{} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items =", "sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList,", "--detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f) for item", "class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' +", "'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, }", "f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0 Classes = {'clap':1, 'hit':2,", "# f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0 Classes = {'clap':1,", "itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList = itemList +", "r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0 Classes =", "'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14,", "os import json path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0", "itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList", "os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command)", "4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f) for item in", "FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+')", "'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount", "= 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9,", "json path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename =", "dirs.sort() for dir in dirs: try: FullList = [] if str(dir).endswith('.json'): continue count", "'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for subdir, dirs, files in os.walk(path,topdown=True):", "= json.load(f) for item in items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name])", "'w+') count = 0 couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4,", "0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10,", "{'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13,", "if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile =", "print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch", "key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile: json.dump(FullList, outfile)", "with open('data_proc/alphapose-results.json') as f: items = json.load(f) for item in items: itemList =", "{} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f) for", "outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename) ) print(\"made \" +str(count)", "[] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile", "'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1 for subdir, dirs, files", "json.load(f) for item in items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count)", "'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount =", "str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir)", "as f: items = json.load(f) for item in items: itemList = [] class_name", "1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList)", "itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList = itemList", "dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList", "imagecount = 1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in", "item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x:", "path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0", "= [] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing file#\" + str(count)) print(dir)", "dir in dirs: try: FullList = [] if str(dir).endswith('.json'): continue count += 1", "in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList = [] if str(dir).endswith('.json'):", "= dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id'])", "as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename) ) print(\"made \"", "print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir", "= 0 couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6,", "command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with", "= r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0 Classes", "files in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList = [] if", "count = 0 couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5,", "f: items = json.load(f) for item in items: itemList = [] class_name =", "--indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items", "} imagecount = 1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir", "itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir", "'w+') as outfile: json.dump(FullList, outfile) except: pass print(\"couldn't rename \" +str(couldRename) ) print(\"made", "= sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as outfile:", "Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11,", "'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } imagecount = 1", "in dirs: try: FullList = [] if str(dir).endswith('.json'): continue count += 1 print(\"proccessing", "FullList = sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt', 'w+') as", "--outdir {} --detbatch 4 \".format(pathtofile,subdir) os.system(command) with open('data_proc/alphapose-results.json') as f: items = json.load(f)", "item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2]) with open('../data_proc/raw_skeletons/skeletons_info/'+dir + '.txt',", "import json path = r\"../data/source_images3\" # f= open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename", "+ 1) itemList.append(class_name) itemList.append(dir + '/' + item['image_id']) itemList = itemList + item['keypoints']", "continue count += 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command", "count += 1 print(\"proccessing file#\" + str(count)) print(dir) pathtofile = os.path.join(subdir,dir) command =", "dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try: FullList = []", "+ item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda", "1 for subdir, dirs, files in os.walk(path,topdown=True): dirs.sort() for dir in dirs: try:", "open('data_proc/alphapose-results.json') as f: items = json.load(f) for item in items: itemList = []", "'/' + item['image_id']) itemList = itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key=", "open(\"../data_proc/raw_skeletons/skeletons_info.txt\", 'w+') count = 0 couldRename = 0 Classes = {'clap':1, 'hit':2, 'jump':3,", "for dir in dirs: try: FullList = [] if str(dir).endswith('.json'): continue count +=", "= os.path.join(subdir,dir) command = \"python3 /home/mina_atef0/Desktop/AlphaPose/demo.py --indir {} --outdir {} --detbatch 4 \".format(pathtofile,subdir)", "itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) + 1) itemList.append(class_name) itemList.append(dir", "= itemList + item['keypoints'] FullList.append(itemList) FullList = sorted(FullList, key= lambda x: x[2]) with", "item in items: itemList = [] class_name = dir.split('_')[0] itemList.append(Classes[class_name]) itemList.append(count) itemList.append(int(item['image_id'][:5]) +" ]
[ "bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts", "argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt", "import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None", "args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal", "(--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before)", "--exclude, --selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts", "scripts = _select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args): # run globals", "typing import Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts", "bool): global_scripts = list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before", "path)) elif path in args.scripts: # if --script selector is there only run", "and not before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError raise", "DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir", "no --script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else:", "model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map(", "filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models):", "--selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts =", "_get_models_with_keyword(faldbt) for node in models: if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif", "FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results = run_scripts(global_scripts,", "return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all,", "filtered_models: List[DbtModel] = [] if ( not all and not selected and not", "FalParseError raise FalParseError( \"Cannot define models to run without selection flags or dbt", "dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from", "= os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not", "in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not scripts_flag:", "all and not selected and not before and faldbt._run_results.nativeRunResult is None ): from", "real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace):", "import FalParseError raise FalParseError( \"Cannot define models to run without selection flags or", "args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts,", "args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else:", "List[DbtModel] = [] if ( not all and not selected and not before", "scripts_flag = _scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path", ") ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]:", "import Path from typing import Any, Dict, List import os from dbt.config.profile import", "else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals", "model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not scripts_flag: # run", "import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException", "there only run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt,", "real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal run command in a", "subprocess\" selector_flags = args.select or args.exclude or args.selector if args.all and selector_flags: raise", "real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not", "real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if", "List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for model in models: model_scripts =", "-> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt:", "flag\" ) models = _get_models_with_keyword(faldbt) for node in models: if selected: if node.unique_id", "None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, )", "else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not None: real_state", "for path in model_scripts: if not scripts_flag: # run all scripts when no", "elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status", "raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals when no --script is passed", "None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results = run_scripts(global_scripts, faldbt)", "if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\":", "results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list(", "command in a subprocess\" selector_flags = args.select or args.exclude or args.selector if args.all", "args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal run command in", "is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts(", "= _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if args.before: if", "FalDbt, all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = []", "path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results =", "artifact or --before flag\" ) models = _get_models_with_keyword(faldbt) for node in models: if", "run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not", "model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before) ->", "in a subprocess\" selector_flags = args.select or args.exclude or args.selector if args.all and", "is None ): from faldbt.parse import FalParseError raise FalParseError( \"Cannot define models to", "raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in", "is passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: # if --script selector", "from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript", "models: if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before)", "args.scripts: # if --script selector is there only run selected scripts scripts.append(FalScript(faldbt, model,", "= [] if ( not all and not selected and not before and", "results) if not _scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt,", "run globals when no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) ->", "FalDbt, is_before: bool): global_scripts = list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\"", "if ( not all and not selected and not before and faldbt._run_results.nativeRunResult is", "not _scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt, args.before) results", "run all scripts when no --script is passed scripts.append(FalScript(faldbt, model, path)) elif path", "all scripts when no --script is passed scripts.append(FalScript(faldbt, model, path)) elif path in", "results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta,", "_get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) )", "not _scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt, args.before) def", "!= []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models", "def fal_run(args: argparse.Namespace): \"Runs the fal run command in a subprocess\" selector_flags =", "--before flag\" ) models = _get_models_with_keyword(faldbt) for node in models: if selected: if", "def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models())", "from typing import Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from", "for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if", "real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude,", "raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): #", "_models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not all and not selected and", "else \"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt)", "run command in a subprocess\" selector_flags = args.select or args.exclude or args.selector if", "_get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] =", "None ): from faldbt.parse import FalParseError raise FalParseError( \"Cannot define models to run", "raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def", "selection flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all,", ") def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models:", ") models = _get_models_with_keyword(faldbt) for node in models: if selected: if node.unique_id in", "FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\")", "bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) ->", "flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags,", "if node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node)", "only run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before:", "DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import", "real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not None: real_state =", "import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir =", "faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args):", "os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\")", "args.exclude or args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all flag", "def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel],", "raise FalParseError( \"Cannot define models to run without selection flags or dbt run_results", "FalParseError( \"Cannot define models to run without selection flags or dbt run_results artifact", "List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt,", "to run without selection flags or dbt run_results artifact or --before flag\" )", "if args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside selection flags", "create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir", "os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir", "FalGeneralException( \"Cannot pass --all flag alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt", "list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected,", "import Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import", "is there only run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt:", "scripts when no --script is passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts:", "a subprocess\" selector_flags = args.select or args.exclude or args.selector if args.all and selector_flags:", "or dbt run_results artifact or --before flag\" ) models = _get_models_with_keyword(faldbt) for node", "all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if", "import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script", "filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before)", "faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals when no --script is", "define models to run without selection flags or dbt run_results artifact or --before", "= _get_models_with_keyword(faldbt) for node in models: if selected: if node.unique_id in selected_ids: filtered_models.append(node)", "\"state\") and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None", "selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts", "map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) )", "else: real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads,", "the fal run command in a subprocess\" selector_flags = args.select or args.exclude or", "args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the", "real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is", "_select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args): # run globals when no", "flag alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models =", "if --script selector is there only run selected scripts scripts.append(FalScript(faldbt, model, path)) return", "return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def", "env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir:", "hasattr(args, \"state\") and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state =", "<gh_stars>100-1000 import argparse from pathlib import Path from typing import Any, Dict, List", "global_scripts = list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else", "before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status !=", "args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt(", "fal_run(args: argparse.Namespace): \"Runs the fal run command in a subprocess\" selector_flags = args.select", "# run globals when no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace)", "= os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None:", "not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir =", "is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir,", "selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []:", "--all flag alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models", "FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir =", "alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt,", "is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results =", "None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif", "real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs", "no --script is passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: # if", "model, path)) elif path in args.scripts: # if --script selector is there only", "elif path in args.scripts: # if --script selector is there only run selected", "model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not scripts_flag: # run all scripts", "not before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError raise FalParseError(", "not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir, real_profiles_dir,", "List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for", "list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], )", "args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside selection flags (--select/--models,", "# run all scripts when no --script is passed scripts.append(FalScript(faldbt, model, path)) elif", "os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not None:", "def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts =", "when no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return", "scripts_flag: # run all scripts when no --script is passed scripts.append(FalScript(faldbt, model, path))", "_run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map( lambda path: FalScript(faldbt, None, path),", "--script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def", "all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models): return list(map(lambda", "is_before else \"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt:", "globals when no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool:", "in models: if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword,", "if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) !=", "= os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir", "FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword in model.meta, faldbt.list_models()) ) def", "= Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector,", "( not all and not selected and not before and faldbt._run_results.nativeRunResult is None", "args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts = [] scripts_flag", "faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError raise FalParseError( \"Cannot define models", "_scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts:", "argparse.Namespace): \"Runs the fal run command in a subprocess\" selector_flags = args.select or", "in model_scripts: if not scripts_flag: # run all scripts when no --script is", "fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir", "--script selector is there only run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts", "bool(args.before)) for path in model_scripts: if not scripts_flag: # run all scripts when", "selected and not before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError", "before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError raise FalParseError( \"Cannot", "models to run without selection flags or dbt run_results artifact or --before flag\"", "faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model: faldbt.keyword", "-> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt )", "when no --script is passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: #", "= None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target,", "faldbt) if args.before: if not _scripts_flag(args): # run globals when no --script is", "if not _scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt, args.before)", "= model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not scripts_flag: # run all", "run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals when no --script", "def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel]", "fal run command in a subprocess\" selector_flags = args.select or args.exclude or args.selector", "scripts = [] scripts_flag = _scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword,", "= _scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in", "): from faldbt.parse import FalParseError raise FalParseError( \"Cannot define models to run without", "or --before flag\" ) models = _get_models_with_keyword(faldbt) for node in models: if selected:", "if is_before else \"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def", "run globals when no --script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt)", "faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models,", "FalDbt ) -> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for model in", "= _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not all and not selected", "= [] scripts_flag = _scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before))", "not scripts_flag: # run all scripts when no --script is passed scripts.append(FalScript(faldbt, model,", "from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel,", "model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not", "from faldbt.parse import FalParseError raise FalParseError( \"Cannot define models to run without selection", "from pathlib import Path from typing import Any, Dict, List import os from", ") def fal_run(args: argparse.Namespace): \"Runs the fal run command in a subprocess\" selector_flags", "passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: # if --script selector is", "passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts,", "List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not all and", "and not selected and not before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse", "results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals when", "Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword,", "path in model_scripts: if not scripts_flag: # run all scripts when no --script", "\"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) ->", "Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts", "selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside selection flags (--select/--models, --exclude, --selector)\"", "scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list(", "selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if (", ") faldbt = create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args,", "def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map( lambda path: FalScript(faldbt, None,", "run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool):", "_run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt)", "in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids", "os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir =", "before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return", "model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids =", "node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node)", "\"Runs the fal run command in a subprocess\" selector_flags = args.select or args.exclude", "if hasattr(args, \"state\") and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state", "args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal run command in a subprocess\"", "--script is passed scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: # if --script", "passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args:", "models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args)", "for node in models: if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before:", "args.select or args.exclude or args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot pass", "and selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside selection flags (--select/--models, --exclude,", "= list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"],", "\"Cannot define models to run without selection flags or dbt run_results artifact or", "argparse from pathlib import Path from typing import Any, Dict, List import os", "selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args): #", "not all and not selected and not before and faldbt._run_results.nativeRunResult is None ):", "if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir))", "models = _get_models_with_keyword(faldbt) for node in models: if selected: if node.unique_id in selected_ids:", "env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state", "fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt,", "if not scripts_flag: # run all scripts when no --script is passed scripts.append(FalScript(faldbt,", "before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not", "when no --script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results)", "in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all:", "in args.scripts: # if --script selector is there only run selected scripts scripts.append(FalScript(faldbt,", ") -> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for model in models:", "Path from typing import Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR", "scripts scripts.append(FalScript(faldbt, model, path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts =", "create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if", "scripts.append(FalScript(faldbt, model, path)) elif path in args.scripts: # if --script selector is there", "args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside selection", "import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project", "models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for path in model_scripts: if not scripts_flag: #", "no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts)", "args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args):", "return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map( lambda path:", "_scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt:", "faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir =", "or args.exclude or args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all", "FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir))", "raise FalGeneralException( \"Cannot pass --all flag alongside selection flags (--select/--models, --exclude, --selector)\" )", ") results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return", "[] scripts_flag = _scripts_flag(args) for model in models: model_scripts = model.get_scripts(args.keyword, bool(args.before)) for", "def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if", "run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args:", "args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models:", "selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node)", "run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda model:", "path in args.scripts: # if --script selector is there only run selected scripts", "= run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results) def _get_models_with_keyword(faldbt: FalDbt) -> List[DbtModel]: return list( filter(lambda", "real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state,", "_scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt, args.before) results =", "= run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run globals when no", "faldbt.parse import FalParseError raise FalParseError( \"Cannot define models to run without selection flags", "results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results)", "# run globals when no --script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts,", "not selected and not before and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import", "elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models): return", "node.unique_id in selected_ids: filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif", "--script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results", "node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models): return list(map(lambda r: r.unique_id, models))", "args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal run", "args.before: if not _scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt,", "path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts,", "argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is", "= args.select or args.exclude or args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot", "selector is there only run selected scripts scripts.append(FalScript(faldbt, model, path)) return scripts def", "node in models: if selected: if node.unique_id in selected_ids: filtered_models.append(node) elif before: if", "elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models): return list(map(lambda r: r.unique_id,", "= _select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args): # run globals when", "selection flags or dbt run_results artifact or --before flag\" ) models = _get_models_with_keyword(faldbt)", "models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if args.before:", "faldbt.keyword in model.meta, faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]:", "filtered_models.append(node) elif before: if node.get_scripts(faldbt.keyword, before) != []: filtered_models.append(node) elif all: filtered_models.append(node) elif", "_run_global_scripts(faldbt, args.before) def _scripts_flag(args: argparse.Namespace) -> bool: return bool(args.scripts) def _select_scripts( args: argparse.Namespace,", "if args.before: if not _scripts_flag(args): # run globals when no --script is passed", "argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts = [] scripts_flag =", "faldbt.list_models()) ) def _get_filtered_models(faldbt: FalDbt, all, selected, before) -> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes)", "[]: filtered_models.append(node) elif all: filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def", "is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir", "os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import", "-> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for model in models: model_scripts", "-> List[DbtModel]: selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not all", "\"Cannot pass --all flag alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt =", "FalDbt( real_project_dir, real_profiles_dir, args.select, args.exclude, args.selector, args.keyword, args.threads, real_state, args.target, ) def fal_run(args:", "_scripts_flag(args): # run globals when no --script is passed _run_global_scripts(faldbt, args.before) def _scripts_flag(args:", "List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from", "and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return", "selected_ids = _models_ids(faldbt._compile_task._flattened_nodes) filtered_models: List[DbtModel] = [] if ( not all and not", "flags or dbt run_results artifact or --before flag\" ) models = _get_models_with_keyword(faldbt) for", "DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else:", "or args.selector if args.all and selector_flags: raise FalGeneralException( \"Cannot pass --all flag alongside", "run without selection flags or dbt run_results artifact or --before flag\" ) models", "_get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt) if args.before: if not", "real_profiles_dir = None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir =", "model_scripts: if not scripts_flag: # run all scripts when no --script is passed", "selector_flags = args.select or args.exclude or args.selector if args.all and selector_flags: raise FalGeneralException(", "[] if ( not all and not selected and not before and faldbt._run_results.nativeRunResult", "= create_fal_dbt(args) models = _get_filtered_models(faldbt, args.all, selector_flags, args.before) scripts = _select_scripts(args, models, faldbt)", "faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results = run_scripts(global_scripts, faldbt) raise_for_run_results_failures(global_scripts, results)", "lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if is_before else \"after\"], ) ) results", "dbt run_results artifact or --before flag\" ) models = _get_models_with_keyword(faldbt) for node in", "path)) return scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map( lambda", "= run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if", "pathlib import Path from typing import Any, Dict, List import os from dbt.config.profile", "filtered_models.append(node) elif node.status != \"skipped\": filtered_models.append(node) return filtered_models def _models_ids(models): return list(map(lambda r:", "import argparse from pathlib import Path from typing import Any, Dict, List import", "scripts def _run_global_scripts(faldbt: FalDbt, is_before: bool): global_scripts = list( map( lambda path: FalScript(faldbt,", "= None env_profiles_dir = os.getenv(\"DBT_PROFILES_DIR\") if args.profiles_dir is not None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir))", "results) else: results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts, results) if not _scripts_flag(args): # run", "models, faldbt) if args.before: if not _scripts_flag(args): # run globals when no --script", "pass --all flag alongside selection flags (--select/--models, --exclude, --selector)\" ) faldbt = create_fal_dbt(args)", "Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures,", "faldbt: FalDbt ) -> List[FalScript]: scripts = [] scripts_flag = _scripts_flag(args) for model", "and faldbt._run_results.nativeRunResult is None ): from faldbt.parse import FalParseError raise FalParseError( \"Cannot define", "args.before) scripts = _select_scripts(args, models, faldbt) if args.before: if not _scripts_flag(args): # run", "from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace): real_project_dir = os.path.realpath(os.path.normpath(args.project_dir)) real_profiles_dir", "args.keyword, args.threads, real_state, args.target, ) def fal_run(args: argparse.Namespace): \"Runs the fal run command", "elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and", "globals when no --script is passed _run_global_scripts(faldbt, args.before) results = run_scripts(scripts, faldbt) raise_for_run_results_failures(scripts,", "# if --script selector is there only run selected scripts scripts.append(FalScript(faldbt, model, path))", "from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGeneralException def create_fal_dbt(args: argparse.Namespace):", "return bool(args.scripts) def _select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]:", "None: real_profiles_dir = os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR", "= os.path.realpath(os.path.normpath(args.profiles_dir)) elif env_profiles_dir: real_profiles_dir = os.path.realpath(os.path.normpath(env_profiles_dir)) else: real_profiles_dir = DEFAULT_PROFILES_DIR if hasattr(args,", "is_before: bool): global_scripts = list( map( lambda path: FalScript(faldbt, None, path), faldbt._global_script_paths[\"before\" if", "= DEFAULT_PROFILES_DIR if hasattr(args, \"state\") and args.state is not None: real_state = Path(os.path.realpath(os.path.normpath(args.state)))", "without selection flags or dbt run_results artifact or --before flag\" ) models =", "None: real_state = Path(os.path.realpath(os.path.normpath(args.state))) else: real_state = None return FalDbt( real_project_dir, real_profiles_dir, args.select,", "_select_scripts( args: argparse.Namespace, models: List[DbtModel], faldbt: FalDbt ) -> List[FalScript]: scripts = []", "run_results artifact or --before flag\" ) models = _get_models_with_keyword(faldbt) for node in models:" ]
[ "= max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2)) * m - 1.0)", "= np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2", "def calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi", "as np from cxroots import AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv,", "m, roots) else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt()", "z = C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int, m,", "if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m,", "argv import matplotlib.pyplot as plt import numpy as np from cxroots import AnnulusSector,", "def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind =", "= min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0 Out.close()", "3: zMod = np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75)", "rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C", "= min(angle, -1e-3) z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z)", "k) * h1vp(m, k) + iv(m, η * k) * h1vp(m, k, 2)", "print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z)", "aMin = -np.pi / 4 for m in range(1, 65): z = rootsAnnSec(m,", "\"w\") angle = -np.pi / 4.0 for m in range(1, 65): r =", "t = np.linspace(0.2, 65.0, num=1024) k = 1j * t rf = np.real(f0(k))", "= rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close()", "of California, Merced Last modified: 20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot", "def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda k: ivp(m, η *", "max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin,", "r = max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2)) * m -", "k = 1j * t rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1]", "scipy.special import h1vp, hankel1, iv, ivp ## Entries ## ε = float(argv[1]) #", "roots) else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def", "calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0", "= 0.0 for m in range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m,", "enumerate(ind): C = Circle(center=1j * (t[i] + t[i + 1]) / 2.0, radius=(t[i", "65.0, num=1024) k = 1j * t rf = np.real(f0(k)) ind = np.where(rf[1:]", "For example -1.1 + 1e-2 * 1j η = np.sqrt(-ε) print(f\"η = {η}\")", "/ 4.0 for m in range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0", "cxroots import AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv, ivp ## Entries", "{η}\") c = η + 1 / η ## Internal functions ## def", "aMax)) z = A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z): if np.size(z,", "= η + 1 / η ## Internal functions ## def rootsAnnSec(m, rMin,", "η ** (-2)) * m - 1.0) R = max(2.0, 1.1 * np.sqrt(1.0", "1.1 * np.sqrt(1.0 - η ** (-2)) * m + 1.0) a =", "- η ** (-2)) * m + 1.0) a = min(angle, -1e-3) z", "η * k) * h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0, num=1024)", "phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z): if", "inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla = np.loadtxt(f\"eps_{ε}_pla\") np.savez(f\"eps_{ε}.npz\", plasmon=Pla) # rewriteSave_pla()", "np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla", "California, Merced Last modified: 20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot as", "(-2)) * m - 1.0) R = max(2.0, 1.1 * np.sqrt(1.0 - η", "open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for m in range(1, 65): r", "/ 4 for m in range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin,", "rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla():", "+ t[i + 1]) / 2.0, radius=(t[i + 1] - t[i])) z =", "Pla.close() else: Int.close() calcInt() def calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\",", "+ iv(m, η * k) * h1vp(m, k, 2) ) t = np.linspace(0.2,", "Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1,", "aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0", "lambda k: ivp(m, η * k, 2) * hankel1(m, k) + c *", "* k) * h1vp(m, k) f1 = ( lambda k: ivp(m, η *", "* np.sqrt(1.0 - η ** (-2)) * m + 1.0) a = min(angle,", "= np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax =", "i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε >", "-1.1 + 1e-2 * 1j η = np.sqrt(-ε) print(f\"η = {η}\") c =", "aMax) writeFile(Out, m, z) if m > 3: zMod = np.abs(z) zArg =", "= abs(z) * (m + 1) / m + 1 aMin = min(2.5", "* 1j η = np.sqrt(-ε) print(f\"η = {η}\") c = η + 1", "if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int =", "in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0", "np.linspace(0.2, 65.0, num=1024) k = 1j * t rf = np.real(f0(k)) ind =", "* hankel1(m, k) + c * ivp(m, η * k) * h1vp(m, k)", "h1vp(m, k) + iv(m, η * k) * h1vp(m, k, 2) ) A", "= np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i", "* k) * h1vp(m, k) + iv(m, η * k) * h1vp(m, k,", "h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z =", "techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany University of California, Merced", "calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind", "= abs(z) rMax = abs(z) * (m + 1) / m + 1", "= {m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z) if", "1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out =", "aMax = 0.0 for m in range(33, 65): print(f\"m = {m}\") z =", "* m - 1.0) R = max(2.0, 1.1 * np.sqrt(1.0 - η **", "hankel1(m, k) / η + iv(m, η * k) * h1vp(m, k) f1", "z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin", "* hankel1(m, k) / η + iv(m, η * k) * h1vp(m, k)", "from scipy.special import h1vp, hankel1, iv, ivp ## Entries ## ε = float(argv[1])", "zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod)", "writeFile(myFile, m, z): if np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real}", "4.0 for m in range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0 -", "as plt import numpy as np from cxroots import AnnulusSector, Circle from scipy.special", "m > 3: zMod = np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod)", "rMax = 0.1, 0.5 aMin = -np.pi / 4 for m in range(1,", "iv(m, η * k) * h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin,", "/ η + iv(m, η * k) * h1vp(m, k) f1 = (", "z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0])", "myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0 if plaTrue: Int", "R = max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2)) * m +", "= Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave()", "0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C = Circle(center=1j", "= AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots def", "# For example -1.1 + 1e-2 * 1j η = np.sqrt(-ε) print(f\"η =", "AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots def writeFile(myFile,", "+ 1]) / 2.0, radius=(t[i + 1] - t[i])) z = C.roots(f0, df=f1)", "+ 1.0) a = min(angle, -1e-3) z = rootsAnnSec(m, r, R, a, 1e-3)", "= Circle(center=1j * (t[i] + t[i + 1]) / 2.0, radius=(t[i + 1]", "hankel1(m, k) + c * ivp(m, η * k) * h1vp(m, k) +", "for m in range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m}", "np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C = Circle(center=1j * (t[i] +", "Technology, Germany University of California, Merced Last modified: 20/04/2021 \"\"\" from sys import", "def calcInt(): plaTrue = ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\")", "2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax =", "angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin =", "> 3: zMod = np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) *", "rMin = 0.2 rMax = 5.0 aMin = -np.pi + 0.01 aMax =", "<NAME> Karlsruhe Institute of Technology, Germany University of California, Merced Last modified: 20/04/2021", "0.9 * np.sqrt(1.0 - η ** (-2)) * m - 1.0) R =", "for m in range(65): print(f\"m = {m}\") f0 = lambda k: ivp(m, η", "2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\")", "in enumerate(ind): C = Circle(center=1j * (t[i] + t[i + 1]) / 2.0,", "= np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\",", "η * k) * h1vp(m, k) f1 = ( lambda k: ivp(m, η", "η ** (-2)) * m + 1.0) a = min(angle, -1e-3) z =", "/ 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax", "University of California, Merced Last modified: 20/04/2021 \"\"\" from sys import argv import", "+ c * ivp(m, η * k) * h1vp(m, k) + iv(m, η", "max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2)) * m - 1.0) R", "-1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int", "np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax =", "* k) * hankel1(m, k) / η + iv(m, η * k) *", "rMin, rMax, aMin, aMax) writeFile(Out, m, z) if m > 3: zMod =", "* ivp(m, η * k) * h1vp(m, k) + iv(m, η * k)", "= {η}\") c = η + 1 / η ## Internal functions ##", "np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) + 3.0)", "z.roots def writeFile(myFile, m, z): if np.size(z, 0): for i in range(np.size(z, 0)):", "= 5.0 aMin = -np.pi + 0.01 aMax = 0.0 for m in", "= -np.pi + 0.01 aMax = 0.0 for m in range(33, 65): print(f\"m", "1 / η ## Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax):", "\"w\") for m in range(65): print(f\"m = {m}\") f0 = lambda k: ivp(m,", "a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out", "Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0 aMin = -np.pi", "rMax = 5.0 aMin = -np.pi + 0.01 aMax = 0.0 for m", "k, 2) * hankel1(m, k) + c * ivp(m, η * k) *", "\"w\") rMin = 0.2 rMax = 5.0 aMin = -np.pi + 0.01 aMax", "range(65): print(f\"m = {m}\") f0 = lambda k: ivp(m, η * k) *", "of Technology, Germany University of California, Merced Last modified: 20/04/2021 \"\"\" from sys", "h1vp(m, k) f1 = ( lambda k: ivp(m, η * k, 2) *", "np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax", "abs(z) * (m + 1) / m + 1 aMin = min(2.5 *", "= 1j * t rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] <", "{z.imag}\\n\") rMin = abs(z) rMax = abs(z) * (m + 1) / m", "η * k) * h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax),", "= np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) +", "= float(argv[1]) # For example -1.1 + 1e-2 * 1j η = np.sqrt(-ε)", "-np.pi / 4.0 for m in range(1, 65): r = max(0.1, 0.9 *", "t rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots =", "1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla = np.loadtxt(f\"eps_{ε}_pla\")", "** (-2)) * m + 1.0) a = min(angle, -1e-3) z = rootsAnnSec(m,", "Germany University of California, Merced Last modified: 20/04/2021 \"\"\" from sys import argv", "= 0.2 rMax = 5.0 aMin = -np.pi + 0.01 aMax = 0.0", "roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close()", "num=1024) k = 1j * t rf = np.real(f0(k)) ind = np.where(rf[1:] *", "= open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m = {m}\") f0 = lambda", "aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave():", "= C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:])", "Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def", "k) * h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0, num=1024) k =", "radius=(t[i + 1] - t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0] if", "{m}\") f0 = lambda k: ivp(m, η * k) * hankel1(m, k) /", "open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0 aMin = -np.pi + 0.01", "+ np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla():", "= ( lambda k: ivp(m, η * k, 2) * hankel1(m, k) +", "iv, ivp ## Entries ## ε = float(argv[1]) # For example -1.1 +", "= {m}\") f0 = lambda k: ivp(m, η * k) * hankel1(m, k)", "plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots)", "iv(m, η * k) * h1vp(m, k) f1 = ( lambda k: ivp(m,", "aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\")", "20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot as plt import numpy as", "(-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def", "def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0 aMin", "rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out", "in range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax)", "m in range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real}", "Entries ## ε = float(argv[1]) # For example -1.1 + 1e-2 * 1j", "Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:,", "k) + iv(m, η * k) * h1vp(m, k, 2) ) A =", "k) / η + iv(m, η * k) * h1vp(m, k) f1 =", "< -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for m", "plaTrue = ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla =", "ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:, 1] > -1e-3", "rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla()", "np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin,", "as file: rMin, rMax = 0.1, 0.5 aMin = -np.pi / 4 for", "radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots def writeFile(myFile, m,", "/ 2.0, radius=(t[i + 1] - t[i])) z = C.roots(f0, df=f1) roots[a] =", "rMax, aMin, aMax): f0 = lambda k: ivp(m, η * k) * hankel1(m,", "** (-2)) * m - 1.0) R = max(2.0, 1.1 * np.sqrt(1.0 -", "\"\"\" Compute resonances using the cxroots library (contour integration techniques) Authors: <NAME>, <NAME>", "\"w\") as file: rMin, rMax = 0.1, 0.5 aMin = -np.pi / 4", "np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla = np.loadtxt(f\"eps_{ε}_pla\") np.savez(f\"eps_{ε}.npz\", plasmon=Pla) #", "1j * t rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0]", "np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi", "= np.sqrt(-ε) print(f\"η = {η}\") c = η + 1 / η ##", "* h1vp(m, k) f1 = ( lambda k: ivp(m, η * k, 2)", "in range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\")", "open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m", "= open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m", "ε = float(argv[1]) # For example -1.1 + 1e-2 * 1j η =", "z) if m > 3: zMod = np.abs(z) zArg = np.angle(z) rMin =", "65): r = max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2)) * m", "0.1, 0.5 aMin = -np.pi / 4 for m in range(1, 65): z", "m + 1.0) a = min(angle, -1e-3) z = rootsAnnSec(m, r, R, a,", "Circle from scipy.special import h1vp, hankel1, iv, ivp ## Entries ## ε =", "/ m + 1 aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax,", "rMin, rMax, aMin, aMax): f0 = lambda k: ivp(m, η * k) *", "numpy as np from cxroots import AnnulusSector, Circle from scipy.special import h1vp, hankel1,", "> -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else:", "if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else:", "Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\")", "print(f\"m = {m}\") f0 = lambda k: ivp(m, η * k) * hankel1(m,", "/ 2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\",", "rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z) *", "roots = np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C = Circle(center=1j *", "m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int,", "= out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla", "+ iv(m, η * k) * h1vp(m, k) f1 = ( lambda k:", "1] - t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if", "def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1, 0.5 aMin", "using the cxroots library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of", "rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:,", "calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1, 0.5", "C = Circle(center=1j * (t[i] + t[i + 1]) / 2.0, radius=(t[i +", "hankel1, iv, ivp ## Entries ## ε = float(argv[1]) # For example -1.1", ") A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return", "= 0.1, 0.5 aMin = -np.pi / 4 for m in range(1, 65):", "calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi /", "1j η = np.sqrt(-ε) print(f\"η = {η}\") c = η + 1 /", "< 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C =", "η * k, 2) * hankel1(m, k) + c * ivp(m, η *", "* np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\")", "* h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0, num=1024) k = 1j", "2.0, radius=(t[i + 1] - t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0]", "{z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z) * (m + 1) /", "Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda k:", "plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\",", "ivp ## Entries ## ε = float(argv[1]) # For example -1.1 + 1e-2", "= open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for", "t[i + 1]) / 2.0, radius=(t[i + 1] - t[i])) z = C.roots(f0,", "rMax = max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) /", "-1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla =", "out2 = Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep])", "ivp(m, η * k) * hankel1(m, k) / η + iv(m, η *", "range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin", "+ 1) / m + 1 aMin = min(2.5 * np.angle(z), -1e-3) print(m,", "m + 1 aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin)", "functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda k: ivp(m,", "a = min(angle, -1e-3) z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m,", "* rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind):", "Int.close() calcInt() def calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle", "roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if ε <", "Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if ε < -1.0: Pla =", "m in range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0 - η **", "max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2)) * m + 1.0) a", "h1vp, hankel1, iv, ivp ## Entries ## ε = float(argv[1]) # For example", "+ 0.01 aMax = 0.0 for m in range(33, 65): print(f\"m = {m}\")", "+ 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg)", "np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep =", "= np.linspace(0.2, 65.0, num=1024) k = 1j * t rf = np.real(f0(k)) ind", "Merced Last modified: 20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot as plt", "65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m,", "in range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2))", "for m in range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0 - η", "file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z) * (m + 1)", "aMin = -np.pi + 0.01 aMax = 0.0 for m in range(33, 65):", "(m + 1) / m + 1 aMin = min(2.5 * np.angle(z), -1e-3)", "* k) * h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin,", "calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0 aMin =", "= lambda k: ivp(m, η * k) * hankel1(m, k) / η +", "np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:, 1] >", "np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax,", "m in range(65): print(f\"m = {m}\") f0 = lambda k: ivp(m, η *", "= -np.pi / 4 for m in range(1, 65): z = rootsAnnSec(m, rMin,", "- η ** (-2)) * m - 1.0) R = max(2.0, 1.1 *", "* h1vp(m, k) + iv(m, η * k) * h1vp(m, k, 2) )", "η ## Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 =", "from sys import argv import matplotlib.pyplot as plt import numpy as np from", "lambda k: ivp(m, η * k) * hankel1(m, k) / η + iv(m,", "z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z) if m >", "np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue", "η + 1 / η ## Internal functions ## def rootsAnnSec(m, rMin, rMax,", "m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m, roots) if plaTrue: Int.close()", "* 0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi +", "roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]])", "m, z): if np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\")", "max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax", "+ 1 / η ## Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin,", "ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for", "1) / m + 1 aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin,", "import matplotlib.pyplot as plt import numpy as np from cxroots import AnnulusSector, Circle", "import numpy as np from cxroots import AnnulusSector, Circle from scipy.special import h1vp,", "df=f1) roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m,", "rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z) if m > 3: zMod", "if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if ε < -1.0:", "rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out =", "1])[::-1] out2 = Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla,", "- t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if m:", "0.01 aMax = 0.0 for m in range(33, 65): print(f\"m = {m}\") z", "print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\")", "= np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep", "np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a, i in", "abs(z) rMax = abs(z) * (m + 1) / m + 1 aMin", "A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots", "Compute resonances using the cxroots library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe", "( lambda k: ivp(m, η * k, 2) * hankel1(m, k) + c", "iv(m, η * k) * h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0,", "= open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax = 5.0 aMin = -np.pi +", "## Entries ## ε = float(argv[1]) # For example -1.1 + 1e-2 *", "+ 1 aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla()", "\"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m = {m}\")", "open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m = {m}\") f0 = lambda k:", "rMin, rMax = 0.1, 0.5 aMin = -np.pi / 4 for m in", "calcInt(): plaTrue = ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla", "rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z)", "out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla =", "* np.sqrt(1.0 - η ** (-2)) * m - 1.0) R = max(2.0,", "rMin = abs(z) rMax = abs(z) * (m + 1) / m +", "else: Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m = {m}\") f0", "np from cxroots import AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv, ivp", "ivp(m, η * k, 2) * hankel1(m, k) + c * ivp(m, η", "import argv import matplotlib.pyplot as plt import numpy as np from cxroots import", "-1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for m in", "1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z) * (m +", "np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 =", "else: writeFile(Int, m, roots) else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else:", "R, a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut():", "cxroots library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany", "2) ) t = np.linspace(0.2, 65.0, num=1024) k = 1j * t rf", "sys import argv import matplotlib.pyplot as plt import numpy as np from cxroots", "zMod = np.abs(z) zArg = np.angle(z) rMin = max(0.2, np.amin(zMod) * 0.75) rMax", "k) f1 = ( lambda k: ivp(m, η * k, 2) * hankel1(m,", "else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla():", "modified: 20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot as plt import numpy", "return z.roots def writeFile(myFile, m, z): if np.size(z, 0): for i in range(np.size(z,", "{z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\",", "+ iv(m, η * k) * h1vp(m, k, 2) ) A = AnnulusSector(center=0.0,", "ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\", \"w\")", "range(1, 65): r = max(0.1, 0.9 * np.sqrt(1.0 - η ** (-2)) *", "m, roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if ε", "k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0,", "AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv, ivp ## Entries ## ε", "0.0 for m in range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin,", "0.5 aMin = -np.pi / 4 for m in range(1, 65): z =", "* (t[i] + t[i + 1]) / 2.0, radius=(t[i + 1] - t[i]))", "{m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z) if m", "= np.zeros(np.shape(ind), dtype=complex) for a, i in enumerate(ind): C = Circle(center=1j * (t[i]", "f0 = lambda k: ivp(m, η * k) * hankel1(m, k) / η", "\"w\") Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m in", "Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for m in range(1,", "* h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z", "m, z) if m > 3: zMod = np.abs(z) zArg = np.angle(z) rMin", "rMin = max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin", "np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for", "= z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else:", "rMax = abs(z) * (m + 1) / m + 1 aMin =", "5.0 aMin = -np.pi + 0.01 aMax = 0.0 for m in range(33,", "## ε = float(argv[1]) # For example -1.1 + 1e-2 * 1j η", "* (m + 1) / m + 1 aMin = min(2.5 * np.angle(z),", "calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1, 0.5 aMin =", "print(f\"η = {η}\") c = η + 1 / η ## Internal functions", "np.sqrt(1.0 - η ** (-2)) * m + 1.0) a = min(angle, -1e-3)", "+ 1e-2 * 1j η = np.sqrt(-ε) print(f\"η = {η}\") c = η", "1]) / 2.0, radius=(t[i + 1] - t[i])) z = C.roots(f0, df=f1) roots[a]", "(-2)) * m + 1.0) a = min(angle, -1e-3) z = rootsAnnSec(m, r,", "m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\")", "integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany University of California,", "for a, i in enumerate(ind): C = Circle(center=1j * (t[i] + t[i +", "from cxroots import AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv, ivp ##", "range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0 if", "np.sqrt(1.0 - η ** (-2)) * m - 1.0) R = max(2.0, 1.1", "writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\",", "= max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0)", "## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda k: ivp(m, η", "aMin, aMax): f0 = lambda k: ivp(m, η * k) * hankel1(m, k)", "Pla.close() calcResPla() def calcResOut(): Out = open(f\"eps_{ε}_out\", \"w\") rMin = 0.2 rMax =", "open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m =", "* t rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots", "* k, 2) * hankel1(m, k) + c * ivp(m, η * k)", "m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m, roots)", "4 for m in range(1, 65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0]", "min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut()", "aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as", "+ 1] - t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue:", "Karlsruhe Institute of Technology, Germany University of California, Merced Last modified: 20/04/2021 \"\"\"", "η + iv(m, η * k) * h1vp(m, k) f1 = ( lambda", "\"\"\" from sys import argv import matplotlib.pyplot as plt import numpy as np", "t[i])) z = C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int,", "> -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla = np.loadtxt(f\"eps_{ε}_pla\") np.savez(f\"eps_{ε}.npz\",", "A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z): if np.size(z, 0): for i", "dtype=complex) for a, i in enumerate(ind): C = Circle(center=1j * (t[i] + t[i", "= np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2", "0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue =", "writeFile(Int, m, roots) else: writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else: Int.close()", "k) + c * ivp(m, η * k) * h1vp(m, k) + iv(m,", "roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m, roots) if", "matplotlib.pyplot as plt import numpy as np from cxroots import AnnulusSector, Circle from", "aMax): f0 = lambda k: ivp(m, η * k) * hankel1(m, k) /", "Circle(center=1j * (t[i] + t[i + 1]) / 2.0, radius=(t[i + 1] -", "k) * h1vp(m, k) f1 = ( lambda k: ivp(m, η * k,", "else: Int.close() calcInt() def calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\")", "1.0) a = min(angle, -1e-3) z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla,", "z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int,", "Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65): print(f\"m = {m}\") f0 =", "aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax = abs(z) * (m", "example -1.1 + 1e-2 * 1j η = np.sqrt(-ε) print(f\"η = {η}\") c", "writeFile(Int, m, roots) if plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if", "m - 1.0) R = max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2))", "df=f1) return z.roots def writeFile(myFile, m, z): if np.size(z, 0): for i in", "writeFile(Int, m, roots[1:]) writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m,", "65): z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin =", "1e-2 * 1j η = np.sqrt(-ε) print(f\"η = {η}\") c = η +", "f1 = ( lambda k: ivp(m, η * k, 2) * hankel1(m, k)", "in range(65): print(f\"m = {m}\") f0 = lambda k: ivp(m, η * k)", "writeFile(Pla, m, roots[[0]]) else: writeFile(Int, m, roots) else: writeFile(Int, m, roots) if plaTrue:", "= rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out, m, z) if m > 3:", "k: ivp(m, η * k) * hankel1(m, k) / η + iv(m, η", "plt import numpy as np from cxroots import AnnulusSector, Circle from scipy.special import", "def writeFile(myFile, m, z): if np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m}", "-1e-3) z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z) angle =", "c = η + 1 / η ## Internal functions ## def rootsAnnSec(m,", "(t[i] + t[i + 1]) / 2.0, radius=(t[i + 1] - t[i])) z", "2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1)", "if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0", "-1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int, plasmon=Pla, outer=out2[rep]) rewriteSave() def rewriteSave_pla(): Pla = np.loadtxt(f\"eps_{ε}_pla\") np.savez(f\"eps_{ε}.npz\", plasmon=Pla)", "1 aMin = min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def", "= A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z): if np.size(z, 0): for", "range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax, aMin, aMax) writeFile(Out,", "c * ivp(m, η * k) * h1vp(m, k) + iv(m, η *", "η * k) * h1vp(m, k) + iv(m, η * k) * h1vp(m,", "z): if np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def", "Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind]", "0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0 if plaTrue:", "k: ivp(m, η * k, 2) * hankel1(m, k) + c * ivp(m,", "min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int =", "rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda k: ivp(m, η * k)", "2) * hankel1(m, k) + c * ivp(m, η * k) * h1vp(m,", "= rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax", "resonances using the cxroots library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute", "0.2 rMax = 5.0 aMin = -np.pi + 0.01 aMax = 0.0 for", "{z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε > -1.0 if plaTrue: Int =", "Pla = open(f\"eps_{ε}_pla\", \"w\") else: Int = open(f\"eps_{ε}_int\", \"w\") for m in range(65):", "m in range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax, aMin,", "rMax), phiRange=(aMin, aMax)) z = A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z):", "= np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex)", "calcInt() def calcResPla(): if ε < -1.0: Pla = open(f\"eps_{ε}_pla\", \"w\") angle =", "z = rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z)", "file: rMin, rMax = 0.1, 0.5 aMin = -np.pi / 4 for m", "k) * h1vp(m, k, 2) ) A = AnnulusSector(center=0.0, radii=(rMin, rMax), phiRange=(aMin, aMax))", "1.0) R = max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2)) * m", "Last modified: 20/04/2021 \"\"\" from sys import argv import matplotlib.pyplot as plt import", "k) + iv(m, η * k) * h1vp(m, k, 2) ) t =", "0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin = min(aMin, (-np.pi + np.amin(zArg))", "rootsAnnSec(m, rMin, rMax, aMin, 1e-3)[0] file.write(f\"{m} {z.real} {z.imag}\\n\") rMin = abs(z) rMax =", "= -np.pi / 4.0 for m in range(1, 65): r = max(0.1, 0.9", "float(argv[1]) # For example -1.1 + 1e-2 * 1j η = np.sqrt(-ε) print(f\"η", "rMax, aMin, aMax) writeFile(Out, m, z) if m > 3: zMod = np.abs(z)", "= max(0.2, np.amin(zMod) * 0.75) rMax = max(rMax, np.amax(zMod) + 3.0) aMin =", "r, R, a, 1e-3) writeFile(Pla, m, z) angle = np.angle(z[0]) Pla.close() calcResPla() def", "min(angle, -1e-3) z = rootsAnnSec(m, r, R, a, 1e-3) writeFile(Pla, m, z) angle", "z = A.roots(f0, df=f1) return z.roots def writeFile(myFile, m, z): if np.size(z, 0):", "np.amin(zArg)) / 2.0) aMax = np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with", "k) * hankel1(m, k) / η + iv(m, η * k) * h1vp(m,", "a, i in enumerate(ind): C = Circle(center=1j * (t[i] + t[i + 1])", "= max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2)) * m + 1.0)", "k, 2) ) t = np.linspace(0.2, 65.0, num=1024) k = 1j * t", "h1vp(m, k) + iv(m, η * k) * h1vp(m, k, 2) ) t", "= np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:, 1]", "if m > 3: zMod = np.abs(z) zArg = np.angle(z) rMin = max(0.2,", "h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0, num=1024) k = 1j *", "<NAME>, <NAME> Karlsruhe Institute of Technology, Germany University of California, Merced Last modified:", "open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1, 0.5 aMin = -np.pi /", "/ η ## Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0", "3.0) aMin = min(aMin, (-np.pi + np.amin(zArg)) / 2.0) aMax = np.amax(zArg) /", "for m in range(33, 65): print(f\"m = {m}\") z = rootsAnnSec(m, rMin, rMax,", "Institute of Technology, Germany University of California, Merced Last modified: 20/04/2021 \"\"\" from", "η * k) * hankel1(m, k) / η + iv(m, η * k)", "Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany University of California, Merced Last", "if np.size(z, 0): for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt():", "writeFile(Out, m, z) if m > 3: zMod = np.abs(z) zArg = np.angle(z)", "np.sqrt(-ε) print(f\"η = {η}\") c = η + 1 / η ## Internal", "= ε > -1.0 if plaTrue: Int = open(f\"eps_{ε}_int\", \"w\") Pla = open(f\"eps_{ε}_pla\",", "Int = np.loadtxt(f\"eps_{ε}_int\") Pla = np.loadtxt(f\"eps_{ε}_pla\") Out = np.loadtxt(f\"eps_{ε}_out\") ind = np.argsort(Out[:, 1])[::-1]", "-np.pi + 0.01 aMax = 0.0 for m in range(33, 65): print(f\"m =", "## Internal functions ## def rootsAnnSec(m, rMin, rMax, aMin, aMax): f0 = lambda", "the cxroots library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology,", "ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind), dtype=complex) for a,", "aMin, aMax) writeFile(Out, m, z) if m > 3: zMod = np.abs(z) zArg", "angle = -np.pi / 4.0 for m in range(1, 65): r = max(0.1,", "np.argsort(Out[:, 1])[::-1] out2 = Out[ind] rep = out2[:, 1] > -1e-3 np.savez(f\"eps_{ε}.npz\", inner=Int,", "for i in range(np.size(z, 0)): myFile.write(f\"{m} {z[i].real} {z[i].imag}\\n\") def calcInt(): plaTrue = ε", "import h1vp, hankel1, iv, ivp ## Entries ## ε = float(argv[1]) # For", "import AnnulusSector, Circle from scipy.special import h1vp, hankel1, iv, ivp ## Entries ##", "-np.pi / 4 for m in range(1, 65): z = rootsAnnSec(m, rMin, rMax,", "= np.amax(zArg) / 2.0 Out.close() calcResOut() def calc_cx_pla(): with open(f\"eps_{ε}_pla\", \"w\") as file:", "i in enumerate(ind): C = Circle(center=1j * (t[i] + t[i + 1]) /", "- 1.0) R = max(2.0, 1.1 * np.sqrt(1.0 - η ** (-2)) *", "plaTrue: Int.close() Pla.close() else: Int.close() calcInt() def calcResPla(): if ε < -1.0: Pla", "η = np.sqrt(-ε) print(f\"η = {η}\") c = η + 1 / η", ") t = np.linspace(0.2, 65.0, num=1024) k = 1j * t rf =", "library (contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany University", "= min(2.5 * np.angle(z), -1e-3) print(m, rMin, rMax, aMin) calc_cx_pla() def rewriteSave(): Int", "= open(f\"eps_{ε}_pla\", \"w\") angle = -np.pi / 4.0 for m in range(1, 65):", "* m + 1.0) a = min(angle, -1e-3) z = rootsAnnSec(m, r, R,", "rf = np.real(f0(k)) ind = np.where(rf[1:] * rf[:-1] < 0.0)[0] roots = np.zeros(np.shape(ind),", "with open(f\"eps_{ε}_pla\", \"w\") as file: rMin, rMax = 0.1, 0.5 aMin = -np.pi", "ivp(m, η * k) * h1vp(m, k) + iv(m, η * k) *", "(contour integration techniques) Authors: <NAME>, <NAME> Karlsruhe Institute of Technology, Germany University of", "* k) * h1vp(m, k, 2) ) t = np.linspace(0.2, 65.0, num=1024) k", "C.roots(f0, df=f1) roots[a] = z.roots[0] if plaTrue: if m: writeFile(Int, m, roots[1:]) writeFile(Pla," ]
[ "def make_from_firmware_version(self, version): \"\"\" Report the current firmware version to WolkAbout IoT Platform.", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "an alarm event to be sent to WolkAbout IoT Platform. :param alarm: Alarm", "make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk of the firmware file from", "def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk of the firmware file", "@abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to be sent to", "Current status of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype:", "be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a", "def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of the firmware update process.", "configuration: Device's current configuration :type configuration: dict :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self,", "IoT Platform. :param version: Current firmware version :type version: str :returns: message :rtype:", "this file except in compliance with the License. # You may obtain a", "chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\"", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status", "IoT Platform. :param file_name: Name of the file that contains the requested chunk", "that contains the requested chunk :type file_name: str :param chunk_index: Index of the", "WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration):", "ANY KIND, either express or implied. # See the License for the specific", ":param alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "to WolkAbout IoT Platform. :param actuator: Actuator status to be serialized :type actuator:", "sent to WolkAbout IoT Platform. :param configuration: Device's current configuration :type configuration: dict", "@abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to be sent to", "def make_from_keep_alive_message(self): \"\"\" Make a ping message to be sent to WolkAbout IoT", "make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to be sent to WolkAbout IoT", "wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize", "make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to be sent to WolkAbout IoT", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "@abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be sent to WolkAbout", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to", "file that contains the requested chunk :type file_name: str :param chunk_index: Index of", "configuration to be sent to WolkAbout IoT Platform. :param configuration: Device's current configuration", "OF ANY KIND, either express or implied. # See the License for the", "\"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current firmware version", "be sent to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "WolkAbout IoT Platform. :param alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns:", "wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize", "@abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current firmware version to WolkAbout IoT", "IoT Platform. :param reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message", "str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a", ":param configuration: Device's current configuration :type configuration: dict :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "the requested chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report", "governing permissions and # limitations under the License. from abc import ABC, abstractmethod", "an actuator status to be sent to WolkAbout IoT Platform. :param actuator: Actuator", "Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout IoT Platform.\"\"\"", "IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to be", "permissions and # limitations under the License. from abc import ABC, abstractmethod \"\"\"", "Platform. :param configuration: Device's current configuration :type configuration: dict :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "@abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of the firmware update", "file_name: str :param chunk_index: Index of the requested chunk :type chunk_index: int :param", "from WolkAbout IoT Platform. :param file_name: Name of the file that contains the", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "to WolkAbout IoT Platform. :param reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading", "the specific language governing permissions and # limitations under the License. from abc", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "the current status of the firmware update process. :param firmware_status: Current status of", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Serialize a sensor reading to be sent to WolkAbout IoT Platform. :param reading:", "configuration): \"\"\" Serialize device's configuration to be sent to WolkAbout IoT Platform. :param", "limitations under the License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\"", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an", ":param chunk_size: Size of the requested chunk :type chunk_size: int :returns: message :rtype:", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to be sent", "\"\"\" Request a chunk of the firmware file from WolkAbout IoT Platform. :param", "\"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod", "required by applicable law or agreed to in writing, software # distributed under", "Make a ping message to be sent to WolkAbout IoT Platform. :returns: message", ":param firmware_status: Current status of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns:", "\"\"\" Serialize device's configuration to be sent to WolkAbout IoT Platform. :param configuration:", "ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent", "update process. :param firmware_status: Current status of the firmware update process :type firmware_status:", "applicable law or agreed to in writing, software # distributed under the License", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk", "messages to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\"", "of the firmware update process. :param firmware_status: Current status of the firmware update", "requested chunk :type file_name: str :param chunk_index: Index of the requested chunk :type", "WolkAbout IoT Platform. :param reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns:", "pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to be sent", "to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "or agreed to in writing, software # distributed under the License is distributed", "firmware version to WolkAbout IoT Platform. :param version: Current firmware version :type version:", "to be sent to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm", "Platform. :param actuator: Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message", "\"\"\" Serialize an actuator status to be sent to WolkAbout IoT Platform. :param", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", ":type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status):", "\"\"\" Make a ping message to be sent to WolkAbout IoT Platform. :returns:", "the requested chunk :type file_name: str :param chunk_index: Index of the requested chunk", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "event to be sent to WolkAbout IoT Platform. :param alarm: Alarm to be", "device's configuration to be sent to WolkAbout IoT Platform. :param configuration: Device's current", "License. # You may obtain a copy of the License at # #", "@abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message to be sent to WolkAbout", "alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\"", "sent to WolkAbout IoT Platform. :param actuator: Actuator status to be serialized :type", "the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "Report the current firmware version to WolkAbout IoT Platform. :param version: Current firmware", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message to be", ":type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version):", "compliance with the License. # You may obtain a copy of the License", "Platform. :param alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype:", "requested chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "WolkAbout Technology s.r.o. # # Licensed under the Apache License, Version 2.0 (the", "\"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk of", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", ":param file_name: Name of the file that contains the requested chunk :type file_name:", "pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to be sent", ":param actuator: Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype:", "not use this file except in compliance with the License. # You may", "Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize", "wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size):", "License, Version 2.0 (the \"License\"); # you may not use this file except", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\"", "\"\"\" Serialize an alarm event to be sent to WolkAbout IoT Platform. :param", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request", "# you may not use this file except in compliance with the License.", "agreed to in writing, software # distributed under the License is distributed on", "chunk_index: int :param chunk_size: Size of the requested chunk :type chunk_size: int :returns:", "to be sent to WolkAbout IoT Platform. :param alarm: Alarm to be serialized", "firmware update process. :param firmware_status: Current status of the firmware update process :type", "the requested chunk :type chunk_index: int :param chunk_size: Size of the requested chunk", "be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\"", "(the \"License\"); # you may not use this file except in compliance with", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current firmware", "WolkAbout IoT Platform. :param version: Current firmware version :type version: str :returns: message", "to be sent to WolkAbout IoT Platform. :param configuration: Device's current configuration :type", "# Unless required by applicable law or agreed to in writing, software #", "of the firmware file from WolkAbout IoT Platform. :param file_name: Name of the", "by applicable law or agreed to in writing, software # distributed under the", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current", "status of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "@abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk of the firmware", "Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self):", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "chunk :type file_name: str :param chunk_index: Index of the requested chunk :type chunk_index:", "firmware file from WolkAbout IoT Platform. :param file_name: Name of the file that", "2018 WolkAbout Technology s.r.o. # # Licensed under the Apache License, Version 2.0", "sensor reading to be sent to WolkAbout IoT Platform. :param reading: Reading to", "\"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be sent", "file except in compliance with the License. # You may obtain a copy", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be", "to WolkAbout IoT Platform. :param version: Current firmware version :type version: str :returns:", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the", "reading to be sent to WolkAbout IoT Platform. :param reading: Reading to be", "def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to be sent to WolkAbout", "License for the specific language governing permissions and # limitations under the License.", "to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize", "alarm): \"\"\" Serialize an alarm event to be sent to WolkAbout IoT Platform.", "to in writing, software # distributed under the License is distributed on an", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to", "\"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to be", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "@abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to be sent to", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message to", "chunk :type chunk_index: int :param chunk_size: Size of the requested chunk :type chunk_size:", ":type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\"", "class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def", "Report the current status of the firmware update process. :param firmware_status: Current status", "Platform. :param version: Current firmware version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "the file that contains the requested chunk :type file_name: str :param chunk_index: Index", "or implied. # See the License for the specific language governing permissions and", "to WolkAbout IoT Platform. :param configuration: Device's current configuration :type configuration: dict :returns:", "a sensor reading to be sent to WolkAbout IoT Platform. :param reading: Reading", "be sent to WolkAbout IoT Platform. :param reading: Reading to be serialized :type", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "and # limitations under the License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Current firmware version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "to WolkAbout IoT Platform. :param alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the", "License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize", "in writing, software # distributed under the License is distributed on an \"AS", "Platform. :param file_name: Name of the file that contains the requested chunk :type", "process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self,", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "a ping message to be sent to WolkAbout IoT Platform. :returns: message :rtype:", "\"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message to be sent", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator", "version): \"\"\" Report the current firmware version to WolkAbout IoT Platform. :param version:", "current firmware version to WolkAbout IoT Platform. :param version: Current firmware version :type", "# limitations under the License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module.", "abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's", "# Copyright 2018 WolkAbout Technology s.r.o. # # Licensed under the Apache License,", ":param reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index, chunk_size): \"\"\" Request a chunk of the", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "WolkAbout IoT Platform. :param actuator: Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus", "of the requested chunk :type chunk_index: int :param chunk_size: Size of the requested", "ping message to be sent to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "firmware_status): \"\"\" Report the current status of the firmware update process. :param firmware_status:", ":type file_name: str :param chunk_index: Index of the requested chunk :type chunk_index: int", "use this file except in compliance with the License. # You may obtain", "contains the requested chunk :type file_name: str :param chunk_index: Index of the requested", "sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor", ":type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm):", "\"\"\" Serialize a sensor reading to be sent to WolkAbout IoT Platform. :param", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "IoT Platform. :param alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message", "of the file that contains the requested chunk :type file_name: str :param chunk_index:", "int :param chunk_size: Size of the requested chunk :type chunk_size: int :returns: message", "Platform. :param reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype:", "IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\"", "2.0 (the \"License\"); # you may not use this file except in compliance", "Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_version(self,", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "the License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC):", "# # Unless required by applicable law or agreed to in writing, software", "express or implied. # See the License for the specific language governing permissions", "actuator status to be sent to WolkAbout IoT Platform. :param actuator: Actuator status", "Copyright 2018 WolkAbout Technology s.r.o. # # Licensed under the Apache License, Version", "status to be sent to WolkAbout IoT Platform. :param actuator: Actuator status to", ":param version: Current firmware version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading", "\"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of the", "be sent to WolkAbout IoT Platform. :param configuration: Device's current configuration :type configuration:", "\"\"\"Serialize messages to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading):", "either express or implied. # See the License for the specific language governing", "def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to be sent to WolkAbout", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "sent to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "IoT Platform. :param actuator: Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns:", "def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to be sent to WolkAbout", "Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "chunk of the firmware file from WolkAbout IoT Platform. :param file_name: Name of", "be sent to WolkAbout IoT Platform. :param alarm: Alarm to be serialized :type", "make_from_firmware_version(self, version): \"\"\" Report the current firmware version to WolkAbout IoT Platform. :param", "the License. # You may obtain a copy of the License at #", "actuator): \"\"\" Serialize an actuator status to be sent to WolkAbout IoT Platform.", "serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self,", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "version to WolkAbout IoT Platform. :param version: Current firmware version :type version: str", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self,", "pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be sent to", "wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to", "chunk_size: Size of the requested chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self,", "version: Current firmware version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "firmware_status: Current status of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message", "firmware version :type version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "reading): \"\"\" Serialize a sensor reading to be sent to WolkAbout IoT Platform.", "process. :param firmware_status: Current status of the firmware update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus", "to be sent to WolkAbout IoT Platform. :param reading: Reading to be serialized", "update process :type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "specific language governing permissions and # limitations under the License. from abc import", ":type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator):", "with the License. # You may obtain a copy of the License at", "Serialize device's configuration to be sent to WolkAbout IoT Platform. :param configuration: Device's", "Name of the file that contains the requested chunk :type file_name: str :param", "alarm: Alarm to be serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current", "firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name, chunk_index,", "Size of the requested chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "chunk_size): \"\"\" Request a chunk of the firmware file from WolkAbout IoT Platform.", "the firmware file from WolkAbout IoT Platform. :param file_name: Name of the file", "chunk_index: Index of the requested chunk :type chunk_index: int :param chunk_size: Size of", "law or agreed to in writing, software # distributed under the License is", "be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def", "the License for the specific language governing permissions and # limitations under the", "message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message", "pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current firmware version to WolkAbout", "make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be sent to WolkAbout IoT Platform.", "WolkAbout IoT Platform. :param configuration: Device's current configuration :type configuration: dict :returns: message", "import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to", "make_from_keep_alive_message(self): \"\"\" Make a ping message to be sent to WolkAbout IoT Platform.", ":param chunk_index: Index of the requested chunk :type chunk_index: int :param chunk_size: Size", "file from WolkAbout IoT Platform. :param file_name: Name of the file that contains", "Serialize an alarm event to be sent to WolkAbout IoT Platform. :param alarm:", "file_name, chunk_index, chunk_size): \"\"\" Request a chunk of the firmware file from WolkAbout", "actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\"", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "serialized :type alarm: wolk.models.Alarm.Alarm :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "str :param chunk_index: Index of the requested chunk :type chunk_index: int :param chunk_size:", "sent to WolkAbout IoT Platform. :param reading: Reading to be serialized :type reading:", "version: str :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make", "def make_from_configuration(self, configuration): \"\"\" Serialize device's configuration to be sent to WolkAbout IoT", "requested chunk :type chunk_index: int :param chunk_size: Size of the requested chunk :type", "See the License for the specific language governing permissions and # limitations under", "a chunk of the firmware file from WolkAbout IoT Platform. :param file_name: Name", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "Technology s.r.o. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "\"\"\" pass @abstractmethod def make_from_firmware_version(self, version): \"\"\" Report the current firmware version to", "Index of the requested chunk :type chunk_index: int :param chunk_size: Size of the", "the current firmware version to WolkAbout IoT Platform. :param version: Current firmware version", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "WolkAbout IoT Platform.\"\"\" @abstractmethod def make_from_sensor_reading(self, reading): \"\"\" Serialize a sensor reading to", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of the firmware", "pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping message to be sent to", "\"\"\" Report the current firmware version to WolkAbout IoT Platform. :param version: Current", "be sent to WolkAbout IoT Platform. :param actuator: Actuator status to be serialized", "actuator: Actuator status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage", "Request a chunk of the firmware file from WolkAbout IoT Platform. :param file_name:", ":returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_keep_alive_message(self): \"\"\" Make a ping", "s.r.o. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages to be sent to WolkAbout IoT", "Version 2.0 (the \"License\"); # you may not use this file except in", "for the specific language governing permissions and # limitations under the License. from", "reading: Reading to be serialized :type reading: wolk.models.SensorReading.SensorReading :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", "except in compliance with the License. # You may obtain a copy of", "to be sent to WolkAbout IoT Platform. :param actuator: Actuator status to be", "\"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status to be", "IoT Platform. :param configuration: Device's current configuration :type configuration: dict :returns: message :rtype:", "sent to WolkAbout IoT Platform. :param alarm: Alarm to be serialized :type alarm:", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "status to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "\"\"\" Report the current status of the firmware update process. :param firmware_status: Current", "language governing permissions and # limitations under the License. from abc import ABC,", "to be serialized :type actuator: wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod", "alarm event to be sent to WolkAbout IoT Platform. :param alarm: Alarm to", "from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class OutboundMessageFactory(ABC): \"\"\"Serialize messages", "WolkAbout IoT Platform. :param file_name: Name of the file that contains the requested", "current status of the firmware update process. :param firmware_status: Current status of the", "make_from_firmware_status(self, firmware_status): \"\"\" Report the current status of the firmware update process. :param", "make_from_alarm(self, alarm): \"\"\" Serialize an alarm event to be sent to WolkAbout IoT", "of the requested chunk :type chunk_size: int :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass", "Serialize an actuator status to be sent to WolkAbout IoT Platform. :param actuator:", "under the License. from abc import ABC, abstractmethod \"\"\" OutboundMessageFactory Module. \"\"\" class", "chunk_index, chunk_size): \"\"\" Request a chunk of the firmware file from WolkAbout IoT", "status of the firmware update process. :param firmware_status: Current status of the firmware", "file_name: Name of the file that contains the requested chunk :type file_name: str", ":type chunk_index: int :param chunk_size: Size of the requested chunk :type chunk_size: int", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "message to be sent to WolkAbout IoT Platform. :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\"", ":rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_actuator_status(self, actuator): \"\"\" Serialize an actuator status", ":type firmware_status: wolk.models.FirmwareStatus.FirmwareStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_chunk_request(self, file_name,", "wolk.models.ActuatorStatus.ActuatorStatus :returns: message :rtype: wolk.models.OutboundMessage.OutboundMessage \"\"\" pass @abstractmethod def make_from_firmware_status(self, firmware_status): \"\"\" Report", "the firmware update process. :param firmware_status: Current status of the firmware update process" ]
[ "input() in1 = int(in1) list1 = [] if in1 >= 0: print(in1) else:", "= [] if in1 >= 0: print(in1) else: x = abs(in1)//10 list1.append(-x) y", "else: x = abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y) z =", ">= 0: print(in1) else: x = abs(in1)//10 list1.append(-x) y = abs(in1) % 10", "print(in1) else: x = abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y) z", "in1 = input() in1 = int(in1) list1 = [] if in1 >= 0:", "= abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z)", "Mon Sep 13 20:23:31 2021 @author: Easin \"\"\" in1 = input() in1 =", "coding: utf-8 -*- \"\"\" Created on Mon Sep 13 20:23:31 2021 @author: Easin", "Sep 13 20:23:31 2021 @author: Easin \"\"\" in1 = input() in1 = int(in1)", "= int(in1) list1 = [] if in1 >= 0: print(in1) else: x =", "list1 = [] if in1 >= 0: print(in1) else: x = abs(in1)//10 list1.append(-x)", "Easin \"\"\" in1 = input() in1 = int(in1) list1 = [] if in1", "= input() in1 = int(in1) list1 = [] if in1 >= 0: print(in1)", "-*- \"\"\" Created on Mon Sep 13 20:23:31 2021 @author: Easin \"\"\" in1", "@author: Easin \"\"\" in1 = input() in1 = int(in1) list1 = [] if", "0: print(in1) else: x = abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y)", "x = abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y) z = abs(in1)//100", "list1.append(-x) y = abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z) m =", "2021 @author: Easin \"\"\" in1 = input() in1 = int(in1) list1 = []", "\"\"\" Created on Mon Sep 13 20:23:31 2021 @author: Easin \"\"\" in1 =", "-*- coding: utf-8 -*- \"\"\" Created on Mon Sep 13 20:23:31 2021 @author:", "= abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z) m = str(z)+str(y) list1.append(-int(m))", "\"\"\" in1 = input() in1 = int(in1) list1 = [] if in1 >=", "utf-8 -*- \"\"\" Created on Mon Sep 13 20:23:31 2021 @author: Easin \"\"\"", "13 20:23:31 2021 @author: Easin \"\"\" in1 = input() in1 = int(in1) list1", "20:23:31 2021 @author: Easin \"\"\" in1 = input() in1 = int(in1) list1 =", "int(in1) list1 = [] if in1 >= 0: print(in1) else: x = abs(in1)//10", "[] if in1 >= 0: print(in1) else: x = abs(in1)//10 list1.append(-x) y =", "y = abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z) m = str(z)+str(y)", "abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z) m = str(z)+str(y) list1.append(-int(m)) print(max(list1))", "<reponame>mdhasan8/Problem_Solving<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Created on Mon Sep 13 20:23:31", "abs(in1)//10 list1.append(-x) y = abs(in1) % 10 #print(y) z = abs(in1)//100 #print(z) m", "if in1 >= 0: print(in1) else: x = abs(in1)//10 list1.append(-x) y = abs(in1)", "in1 = int(in1) list1 = [] if in1 >= 0: print(in1) else: x", "on Mon Sep 13 20:23:31 2021 @author: Easin \"\"\" in1 = input() in1", "in1 >= 0: print(in1) else: x = abs(in1)//10 list1.append(-x) y = abs(in1) %", "# -*- coding: utf-8 -*- \"\"\" Created on Mon Sep 13 20:23:31 2021", "Created on Mon Sep 13 20:23:31 2021 @author: Easin \"\"\" in1 = input()" ]
[ "oo def wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else (pos-radius)/abs(vel) if vel<0.0", "sympy import oo def wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else (pos-radius)/abs(vel)", "def wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else (pos-radius)/abs(vel) if vel<0.0 else", "import oo def wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else (pos-radius)/abs(vel) if", "from sympy import oo def wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else", "wall_time(pos, vel, radius): return (1.0-radius-pos)/vel if vel>0.0 else (pos-radius)/abs(vel) if vel<0.0 else float(oo)" ]
[ "verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group',", "name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True,", "'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'],", "[ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')),", "blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group', field=models.ManyToManyField(default=None, to='users.UserGroup', blank=True), ),", "'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True,", "field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup',", "to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group', field=models.ManyToManyField(default=None, to='users.UserGroup', blank=True), ), ]", "verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering':", "'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile',", "__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [", "'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ),", "), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ),", "migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField(", "on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'],", "auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group", "], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions(", "('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name':", "model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None,", "Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField(", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations", "model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group', field=models.ManyToManyField(default=None,", "'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile',", "models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups',", "import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations =", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class", "<filename>users/migrations/0002_auto_20150708_1621.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True,", "serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300,", "field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group', field=models.ManyToManyField(default=None, to='users.UserGroup', blank=True),", "migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on',", "), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile',", "import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users',", "['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None,", "from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ]", "utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):", "Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField(", "blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True,", "primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')),", "models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [", "models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name',", "name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True,", "'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural':", "name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup',", "'0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),", "verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ),", "class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup',", "('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')),", "Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User", "('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ],", "migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent',", "migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group',", "unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'),", "Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ),", "to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent", "= [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID',", "django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations", "['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name',", "('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User", "[ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,", "fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated", "models.DateTimeField(auto_now_add=True, verbose_name='Created on')), ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={", "('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True,", "}, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'},", "-*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies", "models.DateTimeField(auto_now=True, verbose_name='Updated on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User", "verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', },", "'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name':", "from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies =", "), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup',", "= [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created", "null=True, verbose_name='Group Manager'), ), migrations.AddField( model_name='usergroup', name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'),", "name='parent', field=models.ForeignKey(default=None, blank=True, to='users.UserGroup', null=True, verbose_name='Parent Group'), ), migrations.AddField( model_name='userprofile', name='group', field=models.ManyToManyField(default=None, to='users.UserGroup',", "Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group", "migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel(", "'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True,", "options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User Profile', 'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager',", "options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile',", "'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering':", "'verbose_name_plural': 'User Profiles'}, ), migrations.AddField( model_name='usergroup', name='manager', field=models.ForeignKey(default=None, blank=True, to='users.UserProfile', null=True, verbose_name='Group Manager'),", "] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on',", "Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[", "dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='UserGroup', fields=[ ('id',", "on')), ('name', models.CharField(max_length=300, verbose_name='Group Name')), ], options={ 'ordering': ['name'], 'verbose_name': 'User Group', 'verbose_name_plural':", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models,", "Group', 'verbose_name_plural': 'User Groups', }, ), migrations.AlterModelOptions( name='userprofile', options={'ordering': ['user__first_name', 'created_on'], 'verbose_name': 'User" ]
[ "array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda: 'foo')", "from marshmallow import ( Schema, fields ) import datetime from collections import OrderedDict", "X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True)", "'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name", "1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda:", "('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name =", "import ( Schema, fields ) import datetime from collections import OrderedDict class X(Schema):", "fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object =", "missing=lambda: [1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda: 'foo') age = fields.Integer(missing=lambda:", "Schema, fields ) import datetime from collections import OrderedDict class X(Schema): string =", "datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda:", "'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000,", "fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda: 'foo') age =", "marshmallow import ( Schema, fields ) import datetime from collections import OrderedDict class", "fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3])", "datetime.datetime(2000, 1, 1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age',", "import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean", "1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array", "<reponame>dotness/swagger-marshmallow-codegen<filename>swagger_marshmallow_codegen/tests/dst/00default.py from marshmallow import ( Schema, fields ) import datetime from collections import", "object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1,", "OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema):", "fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1,", "class X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda:", "= fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1,", "from collections import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda:", "collections import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10)", "fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda:", "integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1,", "10) boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1,", "missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class", "1, 1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)]))", "string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime", "= fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda: 'foo') age", "( Schema, fields ) import datetime from collections import OrderedDict class X(Schema): string", "fields ) import datetime from collections import OrderedDict class X(Schema): string = fields.String(missing=lambda:", "= fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object", "True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object = fields.Nested('XObject',", "= fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name',", "import datetime from collections import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer", "OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean =", "20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda:", "datetime from collections import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default') integer =", "fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'),", "= fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(), missing=lambda: [1, 2,", "[1, 2, 3]) class XObject(Schema): name = fields.String(missing=lambda: 'foo') age = fields.Integer(missing=lambda: 20)", ") import datetime from collections import OrderedDict class X(Schema): string = fields.String(missing=lambda: 'default')", "= fields.String(missing=lambda: 'default') integer = fields.Integer(missing=lambda: 10) boolean = fields.Boolean(missing=lambda: True) datetime =", "1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array = fields.List(fields.Integer(),", "1, 1, 1)) object = fields.Nested('XObject', missing=lambda: OrderedDict([('name', 'foo'), ('age', 20)])) array =", "boolean = fields.Boolean(missing=lambda: True) datetime = fields.DateTime(missing=lambda: datetime.datetime(2000, 1, 1, 1, 1, 1))" ]
[ "alignment\") print(\"If you don't want it to appear again enter\") print(\" \") def", "spaces between this div print(\" \") ## the text before and after him.", "error occurs print(\"We're sorry but this error occured:\") ## and if we want", "typo class, be sure to understand the fact that it creates spaces only", "creates a div with hash. times = int(times) ## It adds spaces between", "WRITING #### ############################################################################## class typo: def __init__(self, warning=False): self.type = self self.warn =", "!= None: ## We can also write some text print(text) ## to write", "class typo: def __init__(self, warning=False): self.type = self self.warn = warning if self.warn:", "## the text before and after him. print(times*\"#\") ## We have the possibility", "some informations. print(\" \") def hashsep(self, text=None, times=33): ## It creates a div", "if any error occurs print(\"We're sorry but an error occured.... Please retry\") print(\"If", "= self self.warn = warning if self.warn: ## We print this warning if", "or if you encounter another error\") print(\"please contact us at <EMAIL>\") print(\" \")", "error occurs print(\"We're sorry but an error occured.... Please retry\") print(\"If this error", "\") def hashsep(self, text=None, times=33): ## It creates a div with hash. times", "div print(\" \") ## the text before and after him. print(times*\"#\") ## We", "\") ## the text before and after him. print(times*\"#\") ## We have the", "print(\" \") def vspace(self, text=None, times=33): ## It creates a space letting the", "but this error occured:\") ## and if we want more informations print(error) print(\"If", "text in bold except Exception as e: ## It's actually not working self.ErrorPrecisedPrint(e)", "print(times*\"/\") ## We have the possibility to write if text != None: ##", "text print(text) ## to write some informations. print(\" \") def hashsep(self, text=None, times=33):", "class, be sure to understand the fact that it creates spaces only in", "actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed if any", "hash. times = int(times) ## It adds spaces between this div print(\" \")", "\") ### Functions for printing text def printg(self, text=\"Text Sample\"): ## It's still", "printg(self, text=\"Text Sample\"): ## It's still in development try: print(c.color.bold + ' Hello", "if we want more informations print(error) print(\"If this error persists or if you", "It's still in development try: print(c.color.bold + ' Hello World ! ' +", "times=33): ## It creates a div with hash. times = int(times) ## It", "############################################################################## class typo: def __init__(self, warning=False): self.type = self self.warn = warning if", "## We print this warning if self.warn is True print(\"You initialised a typo", "self self.warn = warning if self.warn: ## We print this warning if self.warn", "= int(times) ## It adds spaces between this div print(\" \") ## the", "text != None: ## some text as args to write informations print(text) print(times*\"#\")", "bold except Exception as e: ## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self):", "# -*- coding: utf-8 -*- try: import modules.typo_colors as c; except Exception as", "after him. print(times*\"#\") ## We have the possibility to write if text !=", "### Functions for printing text def printg(self, text=\"Text Sample\"): ## It's still in", "as args to write informations print(text) print(times*\"/\") print(\" \") ### Functions for printing", "!= None: ## some text as args to write informations print(text) print(times*\"/\") print(\"", "' + c.color.end) ##Normally, it prints the text in bold except Exception as", "def vspace(self, text=None, times=33): ## It creates a space letting the dev print(\"", "working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed if any error occurs", "another error\") print(\"please contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\"", "warning if self.warn is True print(\"You initialised a typo class, be sure to", "print(\" \") ### Functions for printing text def printg(self, text=\"Text Sample\"): ## It's", "print(\" \") ## It's executed if any error occurs print(\"We're sorry but this", "## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed", "spaces between text. if text != None: ## We can also write some", "-*- try: import modules.typo_colors as c; except Exception as e: print(e) ############################################################################## ####", "if any error occurs print(\"We're sorry but this error occured:\") ## and if", "print(times*\"#\") ## We have the possibility to write if text != None: ##", "space letting the dev print(\" \") ## to have spaces between text. if", "warning if self.warn: ## We print this warning if self.warn is True print(\"You", "try: import modules.typo_colors as c; except Exception as e: print(e) ############################################################################## #### ####", "-*- coding: utf-8 -*- try: import modules.typo_colors as c; except Exception as e:", "in development try: print(c.color.bold + ' Hello World ! ' + c.color.end) ##Normally,", "self.type = self self.warn = warning if self.warn: ## We print this warning", "but an error occured.... Please retry\") print(\"If this error persists or if you", "e: ## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's", "prints the text in bold except Exception as e: ## It's actually not", "the possibility to write if text != None: ## some text as args", "creates a space letting the dev print(\" \") ## to have spaces between", "print(text) print(times*\"/\") print(\" \") ### Functions for printing text def printg(self, text=\"Text Sample\"):", "if text != None: ## some text as args to write informations print(text)", "text != None: ## We can also write some text print(text) ## to", "between this div print(\" \") ## the text before and after him. print(times*\"#\")", "occurs print(\"We're sorry but an error occured.... Please retry\") print(\"If this error persists", "error\") print(\"please contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \")", "c; except Exception as e: print(e) ############################################################################## #### #### CLASS OF TYPOS USED", "initialised a typo class, be sure to understand the fact that it creates", "print(\"please contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ##", "error persists or if you encounter another error\") print(\"please contact us at <EMAIL>\")", "contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ## It's", "times = int(times) ## It adds spaces between this div print(\" \") ##", "def barsep(self, text=None, times=33): ## It creates a div with bars. times =", "as args to write informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33):", "print(\" \") ## the text before and after him. print(times*\"/\") ## We have", "us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed", "args to write informations print(text) print(times*\"/\") print(\" \") ### Functions for printing text", "def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if any error occurs print(\"We're", "you don't want it to appear again enter\") print(\" \") def vspace(self, text=None,", "bars. times = int(times) ## It adds spaces between this div print(\" \")", "\") def vspace(self, text=None, times=33): ## It creates a space letting the dev", "again enter\") print(\" \") def vspace(self, text=None, times=33): ## It creates a space", "the text before and after him. print(times*\"/\") ## We have the possibility to", "\") ## to have spaces between text. if text != None: ## We", "if text != None: ## We can also write some text print(text) ##", "executed if any error occurs print(\"We're sorry but an error occured.... Please retry\")", "retry\") print(\"If this error persists or if you encounter another error\") print(\"please contact", "creates a div with bars. times = int(times) ## It adds spaces between", "print(\" \") ## to have spaces between text. if text != None: ##", "to have spaces between text. if text != None: ## We can also", "OF TYPOS USED FOR WRITING #### ############################################################################## class typo: def __init__(self, warning=False): self.type", "it creates spaces only in the vertical alignment\") print(\"If you don't want it", "## It creates a div with bars. times = int(times) ## It adds", "USED FOR WRITING #### ############################################################################## class typo: def __init__(self, warning=False): self.type = self", "hashsep(self, text=None, times=33): ## It creates a div with hash. times = int(times)", "## some text as args to write informations print(text) print(times*\"#\") print(\" \") def", "write some informations. print(\" \") def hashsep(self, text=None, times=33): ## It creates a", "def ErrorPrint(self): print(\" \") ## It's executed if any error occurs print(\"We're sorry", "we want more informations print(error) print(\"If this error persists or if you encounter", "It creates a div with hash. times = int(times) ## It adds spaces", "text=None, times=33): ## It creates a div with bars. times = int(times) ##", "TYPOS USED FOR WRITING #### ############################################################################## class typo: def __init__(self, warning=False): self.type =", "text != None: ## some text as args to write informations print(text) print(times*\"/\")", "letting the dev print(\" \") ## to have spaces between text. if text", "It creates a div with bars. times = int(times) ## It adds spaces", "print(\" \") def barsep(self, text=None, times=33): ## It creates a div with bars.", "print this warning if self.warn is True print(\"You initialised a typo class, be", "it to appear again enter\") print(\" \") def vspace(self, text=None, times=33): ## It", "appear again enter\") print(\" \") def vspace(self, text=None, times=33): ## It creates a", "understand the fact that it creates spaces only in the vertical alignment\") print(\"If", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- try: import modules.typo_colors as c; except", "error occured.... Please retry\") print(\"If this error persists or if you encounter another", "development try: print(c.color.bold + ' Hello World ! ' + c.color.end) ##Normally, it", "self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed if any error occurs print(\"We're", "!= None: ## some text as args to write informations print(text) print(times*\"#\") print(\"", "It adds spaces between this div print(\" \") ## the text before and", "True print(\"You initialised a typo class, be sure to understand the fact that", "to write some informations. print(\" \") def hashsep(self, text=None, times=33): ## It creates", "dev print(\" \") ## to have spaces between text. if text != None:", "div with hash. times = int(times) ## It adds spaces between this div", "text. if text != None: ## We can also write some text print(text)", "a div with hash. times = int(times) ## It adds spaces between this", "## It adds spaces between this div print(\" \") ## the text before", "executed if any error occurs print(\"We're sorry but this error occured:\") ## and", "sure to understand the fact that it creates spaces only in the vertical", "if you encounter another error\") print(\"please contact us at <EMAIL>\") print(\" \") def", "a space letting the dev print(\" \") ## to have spaces between text.", "if self.warn: ## We print this warning if self.warn is True print(\"You initialised", "to appear again enter\") print(\" \") def vspace(self, text=None, times=33): ## It creates", "try: print(c.color.bold + ' Hello World ! ' + c.color.end) ##Normally, it prints", "warning=False): self.type = self self.warn = warning if self.warn: ## We print this", "to write informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ## It", "c.color.end) ##Normally, it prints the text in bold except Exception as e: ##", "for printing text def printg(self, text=\"Text Sample\"): ## It's still in development try:", "text before and after him. print(times*\"/\") ## We have the possibility to write", "text as args to write informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None,", "the fact that it creates spaces only in the vertical alignment\") print(\"If you", "print(\"If you don't want it to appear again enter\") print(\" \") def vspace(self,", "him. print(times*\"/\") ## We have the possibility to write if text != None:", "We have the possibility to write if text != None: ## some text", "print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ## It creates a div with", "It creates a space letting the dev print(\" \") ## to have spaces", "modules.typo_colors as c; except Exception as e: print(e) ############################################################################## #### #### CLASS OF", "print(\"If this error persists or if you encounter another error\") print(\"please contact us", "text=None, times=33): ## It creates a space letting the dev print(\" \") ##", "more informations print(error) print(\"If this error persists or if you encounter another error\")", "## the text before and after him. print(times*\"/\") ## We have the possibility", "Sample\"): ## It's still in development try: print(c.color.bold + ' Hello World !", "None: ## some text as args to write informations print(text) print(times*\"#\") print(\" \")", "It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed if", "the dev print(\" \") ## to have spaces between text. if text !=", "spaces only in the vertical alignment\") print(\"If you don't want it to appear", "print(\" \") def hashsep(self, text=None, times=33): ## It creates a div with hash.", "occured.... Please retry\") print(\"If this error persists or if you encounter another error\")", "and after him. print(times*\"/\") ## We have the possibility to write if text", "## It's executed if any error occurs print(\"We're sorry but this error occured:\")", "as e: print(e) ############################################################################## #### #### CLASS OF TYPOS USED FOR WRITING ####", "None: ## We can also write some text print(text) ## to write some", "write some text print(text) ## to write some informations. print(\" \") def hashsep(self,", "#### CLASS OF TYPOS USED FOR WRITING #### ############################################################################## class typo: def __init__(self,", "some text print(text) ## to write some informations. print(\" \") def hashsep(self, text=None,", "<EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if any", "informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ## It creates a", "error): print(\" \") ## It's executed if any error occurs print(\"We're sorry but", "this error persists or if you encounter another error\") print(\"please contact us at", "only in the vertical alignment\") print(\"If you don't want it to appear again", "this warning if self.warn is True print(\"You initialised a typo class, be sure", "occured:\") ## and if we want more informations print(error) print(\"If this error persists", "a div with bars. times = int(times) ## It adds spaces between this", "def __init__(self, warning=False): self.type = self self.warn = warning if self.warn: ## We", "text as args to write informations print(text) print(times*\"/\") print(\" \") ### Functions for", "print(\" \") ## It's executed if any error occurs print(\"We're sorry but an", "None: ## some text as args to write informations print(text) print(times*\"/\") print(\" \")", "as c; except Exception as e: print(e) ############################################################################## #### #### CLASS OF TYPOS", "text before and after him. print(times*\"#\") ## We have the possibility to write", "World ! ' + c.color.end) ##Normally, it prints the text in bold except", "some text as args to write informations print(text) print(times*\"#\") print(\" \") def barsep(self,", "#### #### CLASS OF TYPOS USED FOR WRITING #### ############################################################################## class typo: def", "have the possibility to write if text != None: ## some text as", "Functions for printing text def printg(self, text=\"Text Sample\"): ## It's still in development", "print(\"You initialised a typo class, be sure to understand the fact that it", "with bars. times = int(times) ## It adds spaces between this div print(\"", "\") ## the text before and after him. print(times*\"/\") ## We have the", "## We have the possibility to write if text != None: ## some", "+ ' Hello World ! ' + c.color.end) ##Normally, it prints the text", "print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if any error", "write informations print(text) print(times*\"/\") print(\" \") ### Functions for printing text def printg(self,", "FOR WRITING #### ############################################################################## class typo: def __init__(self, warning=False): self.type = self self.warn", "and after him. print(times*\"#\") ## We have the possibility to write if text", "is True print(\"You initialised a typo class, be sure to understand the fact", "write informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ## It creates", "you encounter another error\") print(\"please contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self,", "Exception as e: ## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \")", "\") ## It's executed if any error occurs print(\"We're sorry but an error", "It's executed if any error occurs print(\"We're sorry but an error occured.... Please", "print(c.color.bold + ' Hello World ! ' + c.color.end) ##Normally, it prints the", "informations. print(\" \") def hashsep(self, text=None, times=33): ## It creates a div with", "self.warn: ## We print this warning if self.warn is True print(\"You initialised a", "if self.warn is True print(\"You initialised a typo class, be sure to understand", "the vertical alignment\") print(\"If you don't want it to appear again enter\") print(\"", "have spaces between text. if text != None: ## We can also write", "at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if", "## We can also write some text print(text) ## to write some informations.", "e: print(e) ############################################################################## #### #### CLASS OF TYPOS USED FOR WRITING #### ##############################################################################", "text def printg(self, text=\"Text Sample\"): ## It's still in development try: print(c.color.bold +", "some text as args to write informations print(text) print(times*\"/\") print(\" \") ### Functions", "write if text != None: ## some text as args to write informations", "a typo class, be sure to understand the fact that it creates spaces", "#### ############################################################################## class typo: def __init__(self, warning=False): self.type = self self.warn = warning", "\") def ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if any error occurs", "print(times*\"/\") print(\" \") ### Functions for printing text def printg(self, text=\"Text Sample\"): ##", "between text. if text != None: ## We can also write some text", "between this div print(\" \") ## the text before and after him. print(times*\"/\")", "that it creates spaces only in the vertical alignment\") print(\"If you don't want", "Hello World ! ' + c.color.end) ##Normally, it prints the text in bold", "## It's executed if any error occurs print(\"We're sorry but an error occured....", "before and after him. print(times*\"#\") ## We have the possibility to write if", "It's executed if any error occurs print(\"We're sorry but this error occured:\") ##", "error occured:\") ## and if we want more informations print(error) print(\"If this error", "= warning if self.warn: ## We print this warning if self.warn is True", "print(e) ############################################################################## #### #### CLASS OF TYPOS USED FOR WRITING #### ############################################################################## class", "ErrorPrint(self): print(\" \") ## It's executed if any error occurs print(\"We're sorry but", "printing text def printg(self, text=\"Text Sample\"): ## It's still in development try: print(c.color.bold", "in the vertical alignment\") print(\"If you don't want it to appear again enter\")", "print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ## It creates a div", "as e: ## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ##", "fact that it creates spaces only in the vertical alignment\") print(\"If you don't", "print(\"We're sorry but an error occured.... Please retry\") print(\"If this error persists or", "' Hello World ! ' + c.color.end) ##Normally, it prints the text in", "div print(\" \") ## the text before and after him. print(times*\"/\") ## We", "to write if text != None: ## some text as args to write", "def printg(self, text=\"Text Sample\"): ## It's still in development try: print(c.color.bold + '", "creates spaces only in the vertical alignment\") print(\"If you don't want it to", "## and if we want more informations print(error) print(\"If this error persists or", "## It's still in development try: print(c.color.bold + ' Hello World ! '", "the text in bold except Exception as e: ## It's actually not working", "the text before and after him. print(times*\"#\") ## We have the possibility to", "times=33): ## It creates a space letting the dev print(\" \") ## to", "\") ## It's executed if any error occurs print(\"We're sorry but this error", "##Normally, it prints the text in bold except Exception as e: ## It's", "__init__(self, warning=False): self.type = self self.warn = warning if self.warn: ## We print", "informations print(error) print(\"If this error persists or if you encounter another error\") print(\"please", "print(\" \") ## the text before and after him. print(times*\"#\") ## We have", "int(times) ## It adds spaces between this div print(\" \") ## the text", "############################################################################## #### #### CLASS OF TYPOS USED FOR WRITING #### ############################################################################## class typo:", "! ' + c.color.end) ##Normally, it prints the text in bold except Exception", "except Exception as e: ## It's actually not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\"", "in bold except Exception as e: ## It's actually not working self.ErrorPrecisedPrint(e) def", "with hash. times = int(times) ## It adds spaces between this div print(\"", "after him. print(times*\"/\") ## We have the possibility to write if text !=", "before and after him. print(times*\"/\") ## We have the possibility to write if", "Please retry\") print(\"If this error persists or if you encounter another error\") print(\"please", "occurs print(\"We're sorry but this error occured:\") ## and if we want more", "self.warn = warning if self.warn: ## We print this warning if self.warn is", "## to write some informations. print(\" \") def hashsep(self, text=None, times=33): ## It", "possibility to write if text != None: ## some text as args to", "We print this warning if self.warn is True print(\"You initialised a typo class,", "CLASS OF TYPOS USED FOR WRITING #### ############################################################################## class typo: def __init__(self, warning=False):", "def hashsep(self, text=None, times=33): ## It creates a div with hash. times =", "this div print(\" \") ## the text before and after him. print(times*\"/\") ##", "vspace(self, text=None, times=33): ## It creates a space letting the dev print(\" \")", "times=33): ## It creates a div with bars. times = int(times) ## It", "not working self.ErrorPrecisedPrint(e) def ErrorPrint(self): print(\" \") ## It's executed if any error", "text=None, times=33): ## It creates a div with hash. times = int(times) ##", "typo: def __init__(self, warning=False): self.type = self self.warn = warning if self.warn: ##", "an error occured.... Please retry\") print(\"If this error persists or if you encounter", "informations print(text) print(times*\"/\") print(\" \") ### Functions for printing text def printg(self, text=\"Text", "it prints the text in bold except Exception as e: ## It's actually", "this div print(\" \") ## the text before and after him. print(times*\"#\") ##", "div with bars. times = int(times) ## It adds spaces between this div", "## to have spaces between text. if text != None: ## We can", "adds spaces between this div print(\" \") ## the text before and after", "text=\"Text Sample\"): ## It's still in development try: print(c.color.bold + ' Hello World", "print(text) ## to write some informations. print(\" \") def hashsep(self, text=None, times=33): ##", "print(\"We're sorry but this error occured:\") ## and if we want more informations", "coding: utf-8 -*- try: import modules.typo_colors as c; except Exception as e: print(e)", "persists or if you encounter another error\") print(\"please contact us at <EMAIL>\") print(\"", "to write informations print(text) print(times*\"/\") print(\" \") ### Functions for printing text def", "import modules.typo_colors as c; except Exception as e: print(e) ############################################################################## #### #### CLASS", "also write some text print(text) ## to write some informations. print(\" \") def", "be sure to understand the fact that it creates spaces only in the", "print(error) print(\"If this error persists or if you encounter another error\") print(\"please contact", "## some text as args to write informations print(text) print(times*\"/\") print(\" \") ###", "## It creates a div with hash. times = int(times) ## It adds", "any error occurs print(\"We're sorry but an error occured.... Please retry\") print(\"If this", "sorry but an error occured.... Please retry\") print(\"If this error persists or if", "this error occured:\") ## and if we want more informations print(error) print(\"If this", "vertical alignment\") print(\"If you don't want it to appear again enter\") print(\" \")", "can also write some text print(text) ## to write some informations. print(\" \")", "self.warn is True print(\"You initialised a typo class, be sure to understand the", "We can also write some text print(text) ## to write some informations. print(\"", "## It creates a space letting the dev print(\" \") ## to have", "want it to appear again enter\") print(\" \") def vspace(self, text=None, times=33): ##", "barsep(self, text=None, times=33): ## It creates a div with bars. times = int(times)", "sorry but this error occured:\") ## and if we want more informations print(error)", "to understand the fact that it creates spaces only in the vertical alignment\")", "don't want it to appear again enter\") print(\" \") def vspace(self, text=None, times=33):", "utf-8 -*- try: import modules.typo_colors as c; except Exception as e: print(e) ##############################################################################", "Exception as e: print(e) ############################################################################## #### #### CLASS OF TYPOS USED FOR WRITING", "him. print(times*\"#\") ## We have the possibility to write if text != None:", "\") def barsep(self, text=None, times=33): ## It creates a div with bars. times", "want more informations print(error) print(\"If this error persists or if you encounter another", "args to write informations print(text) print(times*\"#\") print(\" \") def barsep(self, text=None, times=33): ##", "ErrorPrecisedPrint(self, error): print(\" \") ## It's executed if any error occurs print(\"We're sorry", "encounter another error\") print(\"please contact us at <EMAIL>\") print(\" \") def ErrorPrecisedPrint(self, error):", "still in development try: print(c.color.bold + ' Hello World ! ' + c.color.end)", "any error occurs print(\"We're sorry but this error occured:\") ## and if we", "except Exception as e: print(e) ############################################################################## #### #### CLASS OF TYPOS USED FOR", "python3 # -*- coding: utf-8 -*- try: import modules.typo_colors as c; except Exception", "+ c.color.end) ##Normally, it prints the text in bold except Exception as e:", "and if we want more informations print(error) print(\"If this error persists or if", "enter\") print(\" \") def vspace(self, text=None, times=33): ## It creates a space letting" ]
[ "eyr (Expiration Year) - four digits; at least 2020 and at most 2030.", "# cid (Country ID) - ignored, missing or not. def height_validator(x): match =", "most 2030. # hgt (Height) - a number followed by either cm or", "match is not None: value = match.group(1) unit = match.group(2) if unit ==", "of code 2020 day 4/2 \"\"\" import logging import math from os import", "None and (2010 <= int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\":", "at most 2030. # hgt (Height) - a number followed by either cm", "brn gry grn hzl oth. # pid (Passport ID) - a nine-digit number,", "pid (Passport ID) - a nine-digit number, including leading zeroes. # cid (Country", "59 <= int(value) <= 76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda x:", "If cm, the number must be at least 150 and at most 193.", "59 and at most 76. # hcl (Hair Color) - a # followed", "x) is not None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\", "(Hair Color) - a # followed by exactly six characters 0-9 or a-f.", "76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not", "{\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair", "+= 1 if all([self.validate_field(record, field) for field in expected_fields]) else 0 return result", "a nine-digit number, including leading zeroes. # cid (Country ID) - ignored, missing", "<= 76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is", "not None and (1920 <= int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr',", "\":\") for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return", "'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2020 <=", "(Country ID), ] class PassportProcessor(object): def __init__(self, records): self.records = records def validate_field(self,", "{\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2020", "= re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value = match.group(1) unit =", "and (2010 <= int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda", "characters 0-9 or a-f. # ecl (Eye Color) - exactly one of: amb", "return result def solve(self): result = 0 for record in self.records: result +=", "# True}, # (Country ID), ] class PassportProcessor(object): def __init__(self, records): self.records =", "# (Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not", "is not None and (2020 <= int(x) <= 2030)}, # (Expiration Year) {\"key\":", "print(result, record) return result def solve(self): result = 0 for record in self.records:", "def solve(self): result = 0 for record in self.records: result += 1 if", "of: amb blu brn gry grn hzl oth. # pid (Passport ID) -", "the number must be at least 150 and at most 193. # If", "2020. # eyr (Expiration Year) - four digits; at least 2020 and at", "If in, the number must be at least 59 and at most 76.", "\"validator\": lambda x: \\ # True}, # (Country ID), ] class PassportProcessor(object): def", "x) is not None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\", "if match is not None: value = match.group(1) unit = match.group(2) if unit", "Field info: # byr (Birth Year) - four digits; at least 1920 and", "(Issue Year) - four digits; at least 2010 and at most 2020. #", "re.match(r'^\\d{4}$', x) is not None and (1920 <= int(x) <= 2002)}, # (Birth", "\"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2020 <= int(x)", "cm or in: # If cm, the number must be at least 150", "- a # followed by exactly six characters 0-9 or a-f. # ecl", "\"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color) {\"key\":", "# print(result, record) return result def solve(self): result = 0 for record in", "# (Country ID), ] class PassportProcessor(object): def __init__(self, records): self.records = records def", "2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is", "in self.records: result += 1 if all([self.validate_field(record, field) for field in expected_fields]) else", "missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is not", "from the records. lines = [{key: value for [key, value] in [field.split( \":\")", "Solution to the problem \"\"\" # split records by empty lines, split fields", "(1920 <= int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda x:", "match = re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value = match.group(1) unit", "digits; at least 2010 and at most 2020. # eyr (Expiration Year) -", "in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self): result =", "day 4/2 \"\"\" import logging import math from os import path import re", "most 2020. # eyr (Expiration Year) - four digits; at least 2020 and", "lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color) {\"key\": 'ecl',", "is not None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$',", "by \":\"-s, create a list of dictionaries from the records. lines = [{key:", "= match.group(1) unit = match.group(2) if unit == \"cm\": return 150 <= int(value)", "info: # byr (Birth Year) - four digits; at least 1920 and at", "2020 day 4/2 \"\"\" import logging import math from os import path import", "4/2 \"\"\" import logging import math from os import path import re record_splitter", "x) is not None}, # (Passport ID) # {\"key\": 'cid', \"validator\": lambda x:", "lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color) {\"key\": 'pid',", "cid (Country ID) - ignored, missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$',", "None and (1920 <= int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\":", "six characters 0-9 or a-f. # ecl (Eye Color) - exactly one of:", "record_splitter = re.compile(' |\\n') # Field info: # byr (Birth Year) - four", "- four digits; at least 2020 and at most 2030. # hgt (Height)", "unit = match.group(2) if unit == \"cm\": return 150 <= int(value) <= 193", "2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\":", "# (Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not", "for record in self.records: result += 1 if all([self.validate_field(record, field) for field in", "\"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None and (1920 <= int(x) <=", "value for [key, value] in [field.split( \":\") for field in record_splitter.split(record)]} for record", "<= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x)", "from os import path import re record_splitter = re.compile(' |\\n') # Field info:", "= field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self):", "hzl oth. # pid (Passport ID) - a nine-digit number, including leading zeroes.", "records): self.records = records def validate_field(self, record, field): result = field[\"key\"] in record", "- four digits; at least 1920 and at most 2002. # iyr (Issue", "Color) - exactly one of: amb blu brn gry grn hzl oth. #", "\"\"\" Advent of code 2020 day 4/2 \"\"\" import logging import math from", "(Passport ID) - a nine-digit number, including leading zeroes. # cid (Country ID)", "\"in\": return 59 <= int(value) <= 76 expected_fields = [ {\"key\": 'byr', \"validator\":", "record) return result def solve(self): result = 0 for record in self.records: result", "class PassportProcessor(object): def __init__(self, records): self.records = records def validate_field(self, record, field): result", "re.match(r'^\\d{4}$', x) is not None and (2010 <= int(x) <= 2020)}, # (Issue", "grn hzl oth. # pid (Passport ID) - a nine-digit number, including leading", "unit == \"cm\": return 150 <= int(value) <= 193 elif unit == \"in\":", "re.compile(' |\\n') # Field info: # byr (Birth Year) - four digits; at", "[key, value] in [field.split( \":\") for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")]", "in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__", "by exactly six characters 0-9 or a-f. # ecl (Eye Color) - exactly", "# followed by exactly six characters 0-9 or a-f. # ecl (Eye Color)", "self.records = records def validate_field(self, record, field): result = field[\"key\"] in record and", "(Height) - a number followed by either cm or in: # If cm,", "least 2010 and at most 2020. # eyr (Expiration Year) - four digits;", "True}, # (Country ID), ] class PassportProcessor(object): def __init__(self, records): self.records = records", "dictionaries from the records. lines = [{key: value for [key, value] in [field.split(", "a # followed by exactly six characters 0-9 or a-f. # ecl (Eye", "PassportProcessor(object): def __init__(self, records): self.records = records def validate_field(self, record, field): result =", "= records def validate_field(self, record, field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]])", "unit == \"in\": return 59 <= int(value) <= 76 expected_fields = [ {\"key\":", "not None: value = match.group(1) unit = match.group(2) if unit == \"cm\": return", "byr (Birth Year) - four digits; at least 1920 and at most 2002.", "amb blu brn gry grn hzl oth. # pid (Passport ID) - a", "record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__),", "re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda x:", "solve(self): result = 0 for record in self.records: result += 1 if all([self.validate_field(record,", "one of: amb blu brn gry grn hzl oth. # pid (Passport ID)", "x: \\ re.match(r'^\\d{4}$', x) is not None and (2020 <= int(x) <= 2030)},", "is not None: value = match.group(1) unit = match.group(2) if unit == \"cm\":", "digits; at least 2020 and at most 2030. # hgt (Height) - a", "ID) - a nine-digit number, including leading zeroes. # cid (Country ID) -", "\\ re.match(r'^\\d{9}$', x) is not None}, # (Passport ID) # {\"key\": 'cid', \"validator\":", "== \"cm\": return 150 <= int(value) <= 193 elif unit == \"in\": return", "- a nine-digit number, including leading zeroes. # cid (Country ID) - ignored,", "record in self.records: result += 1 if all([self.validate_field(record, field) for field in expected_fields])", "- a number followed by either cm or in: # If cm, the", "least 1920 and at most 2002. # iyr (Issue Year) - four digits;", "= [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None and", "or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is not None:", "'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color)", "# If in, the number must be at least 59 and at most", "'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2010 <=", "most 2002. # iyr (Issue Year) - four digits; at least 2010 and", "list of dictionaries from the records. lines = [{key: value for [key, value]", "(Passport ID) # {\"key\": 'cid', \"validator\": lambda x: \\ # True}, # (Country", "most 76. # hcl (Hair Color) - a # followed by exactly six", "- four digits; at least 2010 and at most 2020. # eyr (Expiration", "re.match(r'^\\d{4}$', x) is not None and (2020 <= int(x) <= 2030)}, # (Expiration", "in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__), 'input.txt'),", "blu brn gry grn hzl oth. # pid (Passport ID) - a nine-digit", "all([self.validate_field(record, field) for field in expected_fields]) else 0 return result def solution(data): \"\"\"", "Year) - four digits; at least 2010 and at most 2020. # eyr", "or in: # If cm, the number must be at least 150 and", "fields by \":\"-s, create a list of dictionaries from the records. lines =", "value = match.group(1) unit = match.group(2) if unit == \"cm\": return 150 <=", "(Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x:", "1 if all([self.validate_field(record, field) for field in expected_fields]) else 0 return result def", "four digits; at least 2020 and at most 2030. # hgt (Height) -", "value] in [field.split( \":\") for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver", "\":\"-s, create a list of dictionaries from the records. lines = [{key: value", "in: # If cm, the number must be at least 150 and at", "int(value) <= 193 elif unit == \"in\": return 59 <= int(value) <= 76", "lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2010 <= int(x) <=", "number, including leading zeroes. # cid (Country ID) - ignored, missing or not.", "def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value =", "least 2020 and at most 2030. # hgt (Height) - a number followed", "\"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not None}, # (Passport ID) #", "Year) - four digits; at least 1920 and at most 2002. # iyr", "least 59 and at most 76. # hcl (Hair Color) - a #", "and (2020 <= int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator},", "the records. lines = [{key: value for [key, value] in [field.split( \":\") for", "Year) - four digits; at least 2020 and at most 2030. # hgt", "# (Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not", "- ignored, missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match", "2002. # iyr (Issue Year) - four digits; at least 2010 and at", "four digits; at least 1920 and at most 2002. # iyr (Issue Year)", "{\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$',", "== \"in\": return 59 <= int(value) <= 76 expected_fields = [ {\"key\": 'byr',", "return result def solution(data): \"\"\" Solution to the problem \"\"\" # split records", "at most 193. # If in, the number must be at least 59", "result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def", "at most 76. # hcl (Hair Color) - a # followed by exactly", "{\"key\": 'cid', \"validator\": lambda x: \\ # True}, # (Country ID), ] class", "a list of dictionaries from the records. lines = [{key: value for [key,", "None}, # (Passport ID) # {\"key\": 'cid', \"validator\": lambda x: \\ # True},", "including leading zeroes. # cid (Country ID) - ignored, missing or not. def", "193. # If in, the number must be at least 59 and at", "not None and (2010 <= int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr',", "\\ re.match(r'^\\d{4}$', x) is not None and (2010 <= int(x) <= 2020)}, #", "to the problem \"\"\" # split records by empty lines, split fields by", "and at most 2002. # iyr (Issue Year) - four digits; at least", "'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None and (1920 <= int(x)", "<= int(value) <= 193 elif unit == \"in\": return 59 <= int(value) <=", "ID) - ignored, missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if", "# {\"key\": 'cid', \"validator\": lambda x: \\ # True}, # (Country ID), ]", "is not None and (1920 <= int(x) <= 2002)}, # (Birth Year) {\"key\":", "result def solve(self): result = 0 for record in self.records: result += 1", "Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, #", "(Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, #", "def __init__(self, records): self.records = records def validate_field(self, record, field): result = field[\"key\"]", "import math from os import path import re record_splitter = re.compile(' |\\n') #", "and at most 2030. # hgt (Height) - a number followed by either", "= match.group(2) if unit == \"cm\": return 150 <= int(value) <= 193 elif", "\"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is", "at least 2010 and at most 2020. # eyr (Expiration Year) - four", "# (Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None},", "150 <= int(value) <= 193 elif unit == \"in\": return 59 <= int(value)", "<= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x)", "(2020 <= int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, #", "] class PassportProcessor(object): def __init__(self, records): self.records = records def validate_field(self, record, field):", "field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self): result = 0 for record", "is not None}, # (Passport ID) # {\"key\": 'cid', \"validator\": lambda x: \\", "\"cm\": return 150 <= int(value) <= 193 elif unit == \"in\": return 59", "at least 59 and at most 76. # hcl (Hair Color) - a", "{\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not None}, # (Passport", "x: re.match(r'^\\d{4}$', x) is not None and (1920 <= int(x) <= 2002)}, #", "in expected_fields]) else 0 return result def solution(data): \"\"\" Solution to the problem", "and at most 2020. # eyr (Expiration Year) - four digits; at least", "records. lines = [{key: value for [key, value] in [field.split( \":\") for field", "most 193. # If in, the number must be at least 59 and", "the number must be at least 59 and at most 76. # hcl", "int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$',", "field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result", "(Eye Color) - exactly one of: amb blu brn gry grn hzl oth.", "0-9 or a-f. # ecl (Eye Color) - exactly one of: amb blu", "\\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda", "76. # hcl (Hair Color) - a # followed by exactly six characters", "or a-f. # ecl (Eye Color) - exactly one of: amb blu brn", "a number followed by either cm or in: # If cm, the number", "number must be at least 150 and at most 193. # If in,", "records def validate_field(self, record, field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) #", "iyr (Issue Year) - four digits; at least 2010 and at most 2020.", "result += 1 if all([self.validate_field(record, field) for field in expected_fields]) else 0 return", "lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2020 <= int(x) <=", "# (Passport ID) # {\"key\": 'cid', \"validator\": lambda x: \\ # True}, #", "<= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl',", "\\ re.match(r'^\\d{4}$', x) is not None and (2020 <= int(x) <= 2030)}, #", "= [{key: value for [key, value] in [field.split( \":\") for field in record_splitter.split(record)]}", "193 elif unit == \"in\": return 59 <= int(value) <= 76 expected_fields =", "# iyr (Issue Year) - four digits; at least 2010 and at most", "\"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color) {\"key\":", "in [field.split( \":\") for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver =", "create a list of dictionaries from the records. lines = [{key: value for", "field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self): result", "must be at least 150 and at most 193. # If in, the", "x: \\ re.match(r'^\\d{9}$', x) is not None}, # (Passport ID) # {\"key\": 'cid',", "not None}, # (Passport ID) # {\"key\": 'cid', \"validator\": lambda x: \\ #", "x) is not None and (1920 <= int(x) <= 2002)}, # (Birth Year)", "\\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda", "followed by either cm or in: # If cm, the number must be", "<= int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height)", "None: value = match.group(1) unit = match.group(2) if unit == \"cm\": return 150", "return 150 <= int(value) <= 193 elif unit == \"in\": return 59 <=", "in, the number must be at least 59 and at most 76. #", "least 150 and at most 193. # If in, the number must be", "record, field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return", "# eyr (Expiration Year) - four digits; at least 2020 and at most", "lines = [{key: value for [key, value] in [field.split( \":\") for field in", "not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value", "and (1920 <= int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda", "either cm or in: # If cm, the number must be at least", "if unit == \"cm\": return 150 <= int(value) <= 193 elif unit ==", "at most 2020. # eyr (Expiration Year) - four digits; at least 2020", "ID), ] class PassportProcessor(object): def __init__(self, records): self.records = records def validate_field(self, record,", "def validate_field(self, record, field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result,", "lambda x: \\ # True}, # (Country ID), ] class PassportProcessor(object): def __init__(self,", "data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__), 'input.txt'), 'r'))", "__init__(self, records): self.records = records def validate_field(self, record, field): result = field[\"key\"] in", "result def solution(data): \"\"\" Solution to the problem \"\"\" # split records by", "\"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2010 <= int(x)", "at least 2020 and at most 2030. # hgt (Height) - a number", "# hgt (Height) - a number followed by either cm or in: #", "is not None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$',", "at least 150 and at most 193. # If in, the number must", "math from os import path import re record_splitter = re.compile(' |\\n') # Field", "logging import math from os import path import re record_splitter = re.compile(' |\\n')", "leading zeroes. # cid (Country ID) - ignored, missing or not. def height_validator(x):", "re.match(r'^\\d{9}$', x) is not None}, # (Passport ID) # {\"key\": 'cid', \"validator\": lambda", "gry grn hzl oth. # pid (Passport ID) - a nine-digit number, including", "records by empty lines, split fields by \":\"-s, create a list of dictionaries", "150 and at most 193. # If in, the number must be at", "int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$',", "empty lines, split fields by \":\"-s, create a list of dictionaries from the", "for field in expected_fields]) else 0 return result def solution(data): \"\"\" Solution to", "lambda x: re.match(r'^\\d{4}$', x) is not None and (1920 <= int(x) <= 2002)},", "not None and (2020 <= int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt',", "x: \\ # True}, # (Country ID), ] class PassportProcessor(object): def __init__(self, records):", "= 0 for record in self.records: result += 1 if all([self.validate_field(record, field) for", "= re.compile(' |\\n') # Field info: # byr (Birth Year) - four digits;", "oth. # pid (Passport ID) - a nine-digit number, including leading zeroes. #", "self.records: result += 1 if all([self.validate_field(record, field) for field in expected_fields]) else 0", "must be at least 59 and at most 76. # hcl (Hair Color)", "hcl (Hair Color) - a # followed by exactly six characters 0-9 or", "# split records by empty lines, split fields by \":\"-s, create a list", "x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color) {\"key\": 'pid', \"validator\":", "<= int(x) <= 2002)}, # (Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\", "{\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye", "0 for record in self.records: result += 1 if all([self.validate_field(record, field) for field", "of dictionaries from the records. lines = [{key: value for [key, value] in", "(Birth Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None", "ID) # {\"key\": 'cid', \"validator\": lambda x: \\ # True}, # (Country ID),", "x) is not None and (2020 <= int(x) <= 2030)}, # (Expiration Year)", "zeroes. # cid (Country ID) - ignored, missing or not. def height_validator(x): match", "followed by exactly six characters 0-9 or a-f. # ecl (Eye Color) -", "validate_field(self, record, field): result = field[\"key\"] in record and field[\"validator\"](record[field[\"key\"]]) # print(result, record)", "hgt (Height) - a number followed by either cm or in: # If", "else 0 return result def solution(data): \"\"\" Solution to the problem \"\"\" #", "def solution(data): \"\"\" Solution to the problem \"\"\" # split records by empty", "\"\"\" Solution to the problem \"\"\" # split records by empty lines, split", "None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is", "field) for field in expected_fields]) else 0 return result def solution(data): \"\"\" Solution", "(Birth Year) - four digits; at least 1920 and at most 2002. #", "record and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self): result = 0", "solution(data): \"\"\" Solution to the problem \"\"\" # split records by empty lines,", "<= 193 elif unit == \"in\": return 59 <= int(value) <= 76 expected_fields", "not None}, # (Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x)", "1920 and at most 2002. # iyr (Issue Year) - four digits; at", "Year) {\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and", "[ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None and (1920", "2030. # hgt (Height) - a number followed by either cm or in:", "and at most 193. # If in, the number must be at least", "height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not", "for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve()", "\"\"\" import logging import math from os import path import re record_splitter =", "be at least 59 and at most 76. # hcl (Hair Color) -", "import path import re record_splitter = re.compile(' |\\n') # Field info: # byr", "cm, the number must be at least 150 and at most 193. #", "by either cm or in: # If cm, the number must be at", "Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not None}, #", "0 return result def solution(data): \"\"\" Solution to the problem \"\"\" # split", "os import path import re record_splitter = re.compile(' |\\n') # Field info: #", "field in expected_fields]) else 0 return result def solution(data): \"\"\" Solution to the", "Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and", "= PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__), 'input.txt'), 'r')) as input_file:", "'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not None}, # (Passport ID)", "'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x: \\ re.match(r'^#[a-f0-9]{6}$', x)", "{\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None and (1920 <=", "not None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x)", "be at least 150 and at most 193. # If in, the number", "(2010 <= int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda x:", "'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None}, # (Eye Color)", "None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is", "match.group(1) unit = match.group(2) if unit == \"cm\": return 150 <= int(value) <=", "- exactly one of: amb blu brn gry grn hzl oth. # pid", "ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl", "Color) - a # followed by exactly six characters 0-9 or a-f. #", "re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value = match.group(1) unit = match.group(2)", "is not None and (2010 <= int(x) <= 2020)}, # (Issue Year) {\"key\":", "# (Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not", "None and (2020 <= int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\":", "2010 and at most 2020. # eyr (Expiration Year) - four digits; at", "elif unit == \"in\": return 59 <= int(value) <= 76 expected_fields = [", "expected_fields]) else 0 return result def solution(data): \"\"\" Solution to the problem \"\"\"", "x) if match is not None: value = match.group(1) unit = match.group(2) if", "# Field info: # byr (Birth Year) - four digits; at least 1920", "for [key, value] in [field.split( \":\") for field in record_splitter.split(record)]} for record in", "problem \"\"\" # split records by empty lines, split fields by \":\"-s, create", "# ecl (Eye Color) - exactly one of: amb blu brn gry grn", "{\"key\": 'iyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None and (2010", "int(x) <= 2030)}, # (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\":", "result = 0 for record in self.records: result += 1 if all([self.validate_field(record, field)", "nine-digit number, including leading zeroes. # cid (Country ID) - ignored, missing or", "the problem \"\"\" # split records by empty lines, split fields by \":\"-s,", "path import re record_splitter = re.compile(' |\\n') # Field info: # byr (Birth", "2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is", "number followed by either cm or in: # If cm, the number must", "expected_fields = [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x) is not None", "digits; at least 1920 and at most 2002. # iyr (Issue Year) -", "<= int(value) <= 76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$',", "int(value) <= 76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda x: re.match(r'^\\d{4}$', x)", "PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__), 'input.txt'), 'r')) as input_file: print(solution(input_file.read()))", "lines, split fields by \":\"-s, create a list of dictionaries from the records.", "[field.split( \":\") for field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines)", "at least 1920 and at most 2002. # iyr (Issue Year) - four", "(Country ID) - ignored, missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x)", "and field[\"validator\"](record[field[\"key\"]]) # print(result, record) return result def solve(self): result = 0 for", "# hcl (Hair Color) - a # followed by exactly six characters 0-9", "ignored, missing or not. def height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is", "height_validator(x): match = re.match(r'^(\\d+)(cm|in)$', x) if match is not None: value = match.group(1)", "'cid', \"validator\": lambda x: \\ # True}, # (Country ID), ] class PassportProcessor(object):", "x) is not None and (2010 <= int(x) <= 2020)}, # (Issue Year)", "re record_splitter = re.compile(' |\\n') # Field info: # byr (Birth Year) -", "number must be at least 59 and at most 76. # hcl (Hair", "solver = PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\": with(open(path.join(path.dirname(__file__), 'input.txt'), 'r')) as", "# byr (Birth Year) - four digits; at least 1920 and at most", "at most 2002. # iyr (Issue Year) - four digits; at least 2010", "and at most 76. # hcl (Hair Color) - a # followed by", "(Expiration Year) - four digits; at least 2020 and at most 2030. #", "|\\n') # Field info: # byr (Birth Year) - four digits; at least", "match.group(2) if unit == \"cm\": return 150 <= int(value) <= 193 elif unit", "# pid (Passport ID) - a nine-digit number, including leading zeroes. # cid", "x: \\ re.match(r'^\\d{4}$', x) is not None and (2010 <= int(x) <= 2020)},", "by empty lines, split fields by \":\"-s, create a list of dictionaries from", "re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color) {\"key\": 'ecl', \"validator\": lambda x:", "<= int(x) <= 2020)}, # (Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\", "(Issue Year) {\"key\": 'eyr', \"validator\": lambda x: \\ re.match(r'^\\d{4}$', x) is not None", "import re record_splitter = re.compile(' |\\n') # Field info: # byr (Birth Year)", "(Hair Color) {\"key\": 'ecl', \"validator\": lambda x: \\ re.match(r'^amb|blu|brn|gry|grn|hzl|oth$', x) is not None},", "exactly one of: amb blu brn gry grn hzl oth. # pid (Passport", "a-f. # ecl (Eye Color) - exactly one of: amb blu brn gry", "lambda x: \\ re.match(r'^\\d{9}$', x) is not None}, # (Passport ID) # {\"key\":", "return 59 <= int(value) <= 76 expected_fields = [ {\"key\": 'byr', \"validator\": lambda", "# (Expiration Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda", "Advent of code 2020 day 4/2 \"\"\" import logging import math from os", "2020 and at most 2030. # hgt (Height) - a number followed by", "# If cm, the number must be at least 150 and at most", "(Eye Color) {\"key\": 'pid', \"validator\": lambda x: \\ re.match(r'^\\d{9}$', x) is not None},", "\\ # True}, # (Country ID), ] class PassportProcessor(object): def __init__(self, records): self.records", "code 2020 day 4/2 \"\"\" import logging import math from os import path", "record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__ ==", "if all([self.validate_field(record, field) for field in expected_fields]) else 0 return result def solution(data):", "Year) {\"key\": 'hgt', \"validator\": height_validator}, # (Height) {\"key\": 'hcl', \"validator\": lambda x: \\", "[{key: value for [key, value] in [field.split( \":\") for field in record_splitter.split(record)]} for", "x: \\ re.match(r'^#[a-f0-9]{6}$', x) is not None}, # (Hair Color) {\"key\": 'ecl', \"validator\":", "split fields by \":\"-s, create a list of dictionaries from the records. lines", "field in record_splitter.split(record)]} for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if", "for record in data.split(\"\\n\\n\")] solver = PassportProcessor(lines) return solver.solve() if __name__ == \"__main__\":", "import logging import math from os import path import re record_splitter = re.compile('", "\"\"\" # split records by empty lines, split fields by \":\"-s, create a", "four digits; at least 2010 and at most 2020. # eyr (Expiration Year)", "split records by empty lines, split fields by \":\"-s, create a list of", "exactly six characters 0-9 or a-f. # ecl (Eye Color) - exactly one" ]
[ "\"\"\" helps['storage blob service-properties update'] = \"\"\" type: command short-summary: Update storage blob", "-d \"path/to/file\" - name: Download a virtual directory from a container. text: az", "azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload", "short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: | Open issues here:", "--account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the contents of", "information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage account", "\"path/to/file\" - name: Download a virtual directory from a container. text: az storage", "The SKU of the storage account defaults to 'Standard_RAGRS'. examples: - name: Create", "name: Create a storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in the West", "resource group 'MyResourceGroup' in the West US region with locally redundant storage. text:", "-c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] =", "virtual directory from a container. text: az storage azcopy blob download -c MyContainer", "--recursive - name: Download the contents of a container onto a local file", "- name: Delete a single blob from a container. text: az storage azcopy", "West US region with locally redundant storage. text: az storage account create -n", "Update the properties of a storage account. \"\"\" helps['storage blob service-properties'] = \"\"\"", "- name: Upload a directory to a container. text: az storage azcopy blob", "helps['storage account management-policy update'] = \"\"\" type: command short-summary: Updates the data policy", "storage account. \"\"\" helps['storage account management-policy update'] = \"\"\" type: command short-summary: Updates", "Upload a single blob to a container. text: az storage azcopy blob upload", "= \"\"\" type: command short-summary: Upload blobs to a storage blob container using", "update'] = \"\"\" type: command short-summary: Update storage blob service properties. \"\"\" helps['storage", "= \"\"\" type: group short-summary: Manage storage account management policies. \"\"\" helps['storage account", "-t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type: command short-summary: Run", "azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive -", "a container. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t", "account management-policy update'] = \"\"\" type: command short-summary: Updates the data policy rules", "az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\"", "specified storage account. \"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL]", "--account-name MyStorageAccount -t TargetBlob - name: Delete all blobs from a container. text:", "disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type: command short-summary: Create a storage", "- name: Download a single blob from a container. text: az storage azcopy", "[EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\"", "long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type:", "Manage storage operations utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage", "-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the", "Run a command directly using the AzCopy CLI. Please use SAS tokens for", "update'] = \"\"\" type: command short-summary: Update the properties of a storage account.", "\"\"\" type: command short-summary: Update storage blob service properties. \"\"\" helps['storage account management-policy']", "storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage", "azcopy blob upload'] = \"\"\" type: command short-summary: Upload blobs to a storage", "MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------", "Create a storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in the West US", "License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import", "'MyResourceGroup' in the West US region with locally redundant storage. text: az storage", "associated with the specified storage account. \"\"\" helps['storage account management-policy update'] = \"\"\"", "a storage blob container using AzCopy. examples: - name: Upload a single blob", "a storage blob container using AzCopy. examples: - name: Delete a single blob", "account create'] = \"\"\" type: command short-summary: Create a storage account. long-summary: >", "\"\"\" type: group short-summary: Manage storage account management policies. \"\"\" helps['storage account management-policy", "-s \"path/to/file\" -d NewBlob - name: Upload a directory to a container. text:", "MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download a virtual directory", "the contents of a container onto a local file system. text: az storage", "MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type: command short-summary:", "name: Download the contents of a container onto a local file system. text:", "helps['storage azcopy run-command'] = \"\"\" type: command short-summary: Run a command directly using", "Download the contents of a container onto a local file system. text: az", "account. \"\"\" helps['storage account management-policy update'] = \"\"\" type: command short-summary: Updates the", "here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type: group short-summary: Manage object", "AzCopy. examples: - name: Upload a single blob to a container. text: az", "name: Delete all blobs in a virtual directory. text: az storage azcopy blob", "create -n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account update']", "account 'MyStorageAccount' in resource group 'MyResourceGroup' in the West US region with locally", "from a container. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount", "MyStorageAccount -t TargetBlob - name: Delete all blobs from a container. text: az", "--recursive - name: Upload the contents of a directory to a container. text:", "container. text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\"", "utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] =", "name: Download a virtual directory from a container. text: az storage azcopy blob", "group 'MyResourceGroup' in the West US region with locally redundant storage. text: az", "container using AzCopy. examples: - name: Download a single blob from a container.", "a container. text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s", "knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type:", "short-summary: Delete blobs from a storage blob container using AzCopy. examples: - name:", "single blob to a container. text: az storage azcopy blob upload -c MyContainer", "Download blobs from a storage blob container using AzCopy. examples: - name: Download", "MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload a directory to a container.", "azcopy blob download'] = \"\"\" type: command short-summary: Download blobs from a storage", "storage blob service properties. \"\"\" helps['storage blob service-properties update'] = \"\"\" type: command", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT", "helps['storage azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing", "blob upload'] = \"\"\" type: command short-summary: Upload blobs to a storage blob", "to 'Standard_RAGRS'. examples: - name: Create a storage account 'MyStorageAccount' in resource group", "\"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: |", "text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive", "using AzCopy. examples: - name: Download a single blob from a container. text:", "= \"\"\" type: command short-summary: Update the properties of a storage account. \"\"\"", "storage account. \"\"\" helps['storage blob service-properties'] = \"\"\" type: group short-summary: Manage storage", "account. long-summary: > The SKU of the storage account defaults to 'Standard_RAGRS'. examples:", "upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download']", "text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d", "--recursive \"\"\" helps['storage azcopy blob download'] = \"\"\" type: command short-summary: Download blobs", "-c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the contents of", "storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive", "rules associated with the specified storage account. \"\"\" helps['storage azcopy'] = \"\"\" type:", "the data policy rules associated with the specified storage account. \"\"\" helps['storage account", "upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload a", "= \"\"\" type: command short-summary: Download blobs from a storage blob container using", "MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type: command", "- name: Delete all blobs in a virtual directory. text: az storage azcopy", "- name: Create a storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in the", "-l westus --sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type: command short-summary:", "blob delete'] = \"\"\" type: command short-summary: Delete blobs from a storage blob", "US region with locally redundant storage. text: az storage account create -n MyStorageAccount", "storage blob container using AzCopy. examples: - name: Download a single blob from", "MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the contents of a", "command short-summary: Run a command directly using the AzCopy CLI. Please use SAS", "with the specified storage account. \"\"\" helps['storage account management-policy update'] = \"\"\" type:", "rules associated with the specified storage account. \"\"\" helps['storage account management-policy update'] =", "policies. \"\"\" helps['storage account management-policy create'] = \"\"\" type: command short-summary: Creates the", "command short-summary: Download blobs from a storage blob container using AzCopy. examples: -", "service-properties update'] = \"\"\" type: command short-summary: Update storage blob service properties. \"\"\"", "\"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the contents of a container onto", "helps['storage blob service-properties'] = \"\"\" type: group short-summary: Manage storage blob service properties.", "for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines", "command short-summary: Update storage blob service properties. \"\"\" helps['storage account management-policy'] = \"\"\"", "in a virtual directory. text: az storage azcopy blob delete -c MyContainer --account-name", "type: command short-summary: Creates the data policy rules associated with the specified storage", "text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive - name:", "westus --sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type: command short-summary: Update", "-c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\"", "type: command short-summary: Download blobs from a storage blob container using AzCopy. examples:", "virtual directory. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t", "the MIT License. See License.txt in the project root for license information. #", "text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive", "https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type: group short-summary: Manage object storage", "blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the", "blobs in a virtual directory. text: az storage azcopy blob delete -c MyContainer", "\"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type: command short-summary: Run a", "\"\"\" type: command short-summary: Upload blobs to a storage blob container using AzCopy.", "directory. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\"", "helps['storage blob service-properties update'] = \"\"\" type: command short-summary: Update storage blob service", "properties. \"\"\" helps['storage blob service-properties update'] = \"\"\" type: command short-summary: Update storage", "type: command short-summary: Updates the data policy rules associated with the specified storage", "-c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the", "of a directory to a container. text: az storage azcopy blob upload -c", "-d NewBlob - name: Upload a directory to a container. text: az storage", "reserved. # Licensed under the MIT License. See License.txt in the project root", "name: Download a single blob from a container. text: az storage azcopy blob", "blob service properties. \"\"\" helps['storage account management-policy'] = \"\"\" type: group short-summary: Manage", "azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive - name: Delete all blobs", "blob service properties. \"\"\" helps['storage blob service-properties update'] = \"\"\" type: command short-summary:", "data policy rules associated with the specified storage account. \"\"\" helps['storage azcopy'] =", "-s \"path/to/blob\" -d \"path/to/file\" - name: Download a virtual directory from a container.", "| Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type: group", "for unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\"", "license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage", "blob download -c MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage", "type: group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: | Open", "AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\"", "# -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage account create']", "- name: Download a virtual directory from a container. text: az storage azcopy", "storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive", "storage blob container using AzCopy. examples: - name: Upload a single blob to", "-c MyContainer --account-name MyStorageAccount --recursive - name: Delete all blobs in a virtual", "storage account create -n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage", "create'] = \"\"\" type: command short-summary: Create a storage account. long-summary: > The", "-s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] = \"\"\" type: command short-summary:", "account management-policy'] = \"\"\" type: group short-summary: Manage storage account management policies. \"\"\"", "- name: Delete all blobs from a container. text: az storage azcopy blob", "blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name:", "(blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\" type: command short-summary:", "= \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary:", "container. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob", "See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files", "'Standard_RAGRS'. examples: - name: Create a storage account 'MyStorageAccount' in resource group 'MyResourceGroup'", "a single blob from a container. text: az storage azcopy blob delete -c", "blob service-properties'] = \"\"\" type: group short-summary: Manage storage blob service properties. \"\"\"", "= \"\"\" type: command short-summary: Creates the data policy rules associated with the", "\"\"\" type: command short-summary: Create a storage account. long-summary: > The SKU of", "container. text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\"", "a command directly using the AzCopy CLI. Please use SAS tokens for authentication.", "storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name:", "the specified storage account. \"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary: |", "Update storage blob service properties. \"\"\" helps['storage account management-policy'] = \"\"\" type: group", "= \"\"\" type: command short-summary: Update storage blob service properties. \"\"\" helps['storage account", "blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload", "type: command short-summary: Run a command directly using the AzCopy CLI. Please use", "az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob", "system. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s *", "examples: - name: Create a storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in", "-t TargetBlob - name: Delete all blobs from a container. text: az storage", "name: Delete all blobs from a container. text: az storage azcopy blob delete", "Upload the contents of a directory to a container. text: az storage azcopy", "command short-summary: Creates the data policy rules associated with the specified storage account.", "object storage for unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload']", "using AzCopy. examples: - name: Delete a single blob from a container. text:", "create'] = \"\"\" type: command short-summary: Creates the data policy rules associated with", "MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the contents of a directory to", "command short-summary: Updates the data policy rules associated with the specified storage account.", "single blob from a container. text: az storage azcopy blob download -c MyContainer", "examples: - name: Delete a single blob from a container. text: az storage", "\"\"\" helps['storage azcopy blob download'] = \"\"\" type: command short-summary: Download blobs from", "\"\"\" helps['storage account management-policy'] = \"\"\" type: group short-summary: Manage storage account management", "the data policy rules associated with the specified storage account. \"\"\" helps['storage azcopy']", "# pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type: command short-summary: Create", "blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete all blobs", "of the storage account defaults to 'Standard_RAGRS'. examples: - name: Create a storage", "Delete all blobs from a container. text: az storage azcopy blob delete -c", "= \"\"\" type: command short-summary: Run a command directly using the AzCopy CLI.", "the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps #", "blob container using AzCopy. examples: - name: Delete a single blob from a", "to a container. text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount", "All rights reserved. # Licensed under the MIT License. See License.txt in the", "Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt", "Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type: command short-summary: Update the properties", "policy rules associated with the specified storage account. \"\"\" helps['storage azcopy'] = \"\"\"", "AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\" type: command short-summary: Upload blobs", "= \"\"\" type: command short-summary: Create a storage account. long-summary: > The SKU", "group short-summary: Manage storage blob service properties. \"\"\" helps['storage blob service-properties update'] =", "the West US region with locally redundant storage. text: az storage account create", "a virtual directory. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount", "storage operations utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy", "\"\"\" type: command short-summary: Update the properties of a storage account. \"\"\" helps['storage", "command short-summary: Update the properties of a storage account. \"\"\" helps['storage blob service-properties']", "name: Upload a single blob to a container. text: az storage azcopy blob", "az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\"", "container. text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\"", "Delete blobs from a storage blob container using AzCopy. examples: - name: Delete", "az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive -", "Manage storage blob service properties. \"\"\" helps['storage blob service-properties update'] = \"\"\" type:", "azcopy blob download -c MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\"", "-c MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete all blobs from a", "a virtual directory from a container. text: az storage azcopy blob download -c", "a single blob from a container. text: az storage azcopy blob download -c", "= \"\"\" type: command short-summary: Delete blobs from a storage blob container using", "a container onto a local file system. text: az storage azcopy blob download", "storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in the West US region with", "container. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\"", "-c MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob", "azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name:", "az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\"", "MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download a virtual directory from a", "download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download", "Delete a single blob from a container. text: az storage azcopy blob delete", "az storage account create -n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\"", "AzCopy. examples: - name: Delete a single blob from a container. text: az", "blob from a container. text: az storage azcopy blob delete -c MyContainer --account-name", "helps['storage azcopy blob upload'] = \"\"\" type: command short-summary: Upload blobs to a", "--account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] = \"\"\" type:", "using AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\" type: command short-summary: Upload", "coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "contents of a directory to a container. text: az storage azcopy blob upload", "upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the contents", "name: Upload the contents of a directory to a container. text: az storage", "--account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] =", "blob container using AzCopy. examples: - name: Upload a single blob to a", "text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob -", "type: command short-summary: Update storage blob service properties. \"\"\" helps['storage account management-policy'] =", "Upload a directory to a container. text: az storage azcopy blob upload -c", "-n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account update'] =", "blob container using AzCopy. examples: - name: Download a single blob from a", "# Licensed under the MIT License. See License.txt in the project root for", "\"\"\" helps['storage account update'] = \"\"\" type: command short-summary: Update the properties of", "az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s * -d \"download/path\"", "blob'] = \"\"\" type: group short-summary: Manage object storage for unstructured data (blobs)", "= \"\"\" type: group short-summary: Manage object storage for unstructured data (blobs) using", "blob to a container. text: az storage azcopy blob upload -c MyContainer --account-name", "MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type:", "examples: - name: Download a single blob from a container. text: az storage", "run-command'] = \"\"\" type: command short-summary: Run a command directly using the AzCopy", "SKU of the storage account defaults to 'Standard_RAGRS'. examples: - name: Create a", "\"\"\" helps['storage azcopy blob'] = \"\"\" type: group short-summary: Manage object storage for", "from a container. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount", "Manage storage account management policies. \"\"\" helps['storage account management-policy create'] = \"\"\" type:", "-s \"path/to/directory\" --recursive - name: Upload the contents of a directory to a", "helps['storage account create'] = \"\"\" type: command short-summary: Create a storage account. long-summary:", "policy rules associated with the specified storage account. \"\"\" helps['storage account management-policy update']", "NewBlob - name: Upload a directory to a container. text: az storage azcopy", "-c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload a directory", "all blobs from a container. text: az storage azcopy blob delete -c MyContainer", "account defaults to 'Standard_RAGRS'. examples: - name: Create a storage account 'MyStorageAccount' in", "group short-summary: Manage storage account management policies. \"\"\" helps['storage account management-policy create'] =", "account. \"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage", "account update'] = \"\"\" type: command short-summary: Update the properties of a storage", "region with locally redundant storage. text: az storage account create -n MyStorageAccount -g", "helps['storage azcopy blob'] = \"\"\" type: group short-summary: Manage object storage for unstructured", "of a storage account. \"\"\" helps['storage blob service-properties'] = \"\"\" type: group short-summary:", "service properties. \"\"\" helps['storage account management-policy'] = \"\"\" type: group short-summary: Manage storage", "name: Upload a directory to a container. text: az storage azcopy blob upload", "helps['storage account management-policy create'] = \"\"\" type: command short-summary: Creates the data policy", "data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\" type: command", "directory from a container. text: az storage azcopy blob download -c MyContainer --account-name", "\"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\" type: command short-summary: Delete", "properties of a storage account. \"\"\" helps['storage blob service-properties'] = \"\"\" type: group", "group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: | Open issues", "a directory to a container. text: az storage azcopy blob upload -c MyContainer", "azcopy blob delete'] = \"\"\" type: command short-summary: Delete blobs from a storage", "delete'] = \"\"\" type: command short-summary: Delete blobs from a storage blob container", "az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob - name:", "type: command short-summary: Upload blobs to a storage blob container using AzCopy. examples:", "blob delete -c MyContainer --account-name MyStorageAccount --recursive - name: Delete all blobs in", "with the specified storage account. \"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary:", "storage account. \"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage", "service properties. \"\"\" helps['storage blob service-properties update'] = \"\"\" type: command short-summary: Update", "| [EXPERIMENTAL] Manage storage operations utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy", "MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete']", "\"path/to/directory\" --recursive - name: Upload the contents of a directory to a container.", "-s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the contents of a container", "> The SKU of the storage account defaults to 'Standard_RAGRS'. examples: - name:", "storage account management policies. \"\"\" helps['storage account management-policy create'] = \"\"\" type: command", "delete -c MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete all blobs from", "Manage object storage for unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob", "\"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] = \"\"\" type: command short-summary: Download", "\"download/path\" --recursive - name: Download the contents of a container onto a local", "storage azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive - name: Delete all", "specified storage account. \"\"\" helps['storage account management-policy update'] = \"\"\" type: command short-summary:", "container onto a local file system. text: az storage azcopy blob download -c", "account management policies. \"\"\" helps['storage account management-policy create'] = \"\"\" type: command short-summary:", "blobs to a storage blob container using AzCopy. examples: - name: Upload a", "\"\"\" type: command short-summary: Download blobs from a storage blob container using AzCopy.", "--account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type: command", "type: command short-summary: Create a storage account. long-summary: > The SKU of the", "\"\"\" type: command short-summary: Creates the data policy rules associated with the specified", "delete -c MyContainer --account-name MyStorageAccount --recursive - name: Delete all blobs in a", "file system. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s", "Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type: group short-summary:", "Delete all blobs in a virtual directory. text: az storage azcopy blob delete", "--account-name MyStorageAccount --recursive - name: Delete all blobs in a virtual directory. text:", "the storage account defaults to 'Standard_RAGRS'. examples: - name: Create a storage account", "short-summary: Create a storage account. long-summary: > The SKU of the storage account", "locally redundant storage. text: az storage account create -n MyStorageAccount -g MyResourceGroup -l", "download -c MyContainer --account-name MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy", "in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps", "\"\"\" type: command short-summary: Run a command directly using the AzCopy CLI. Please", "\"\"\" helps['storage azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage operations", "root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long,", "to a storage blob container using AzCopy. examples: - name: Upload a single", "issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob'] = \"\"\" type: group short-summary: Manage", "azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy", "command short-summary: Delete blobs from a storage blob container using AzCopy. examples: -", "--recursive - name: Delete all blobs in a virtual directory. text: az storage", "type: command short-summary: Update the properties of a storage account. \"\"\" helps['storage blob", "blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob", "(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See", "Creates the data policy rules associated with the specified storage account. \"\"\" helps['storage", "type: group short-summary: Manage object storage for unstructured data (blobs) using AzCopy. \"\"\"", "MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the contents of a", "storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" -", "azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name:", "storage. text: az storage account create -n MyStorageAccount -g MyResourceGroup -l westus --sku", "# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] = \"\"\"", "Download a virtual directory from a container. text: az storage azcopy blob download", "-c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download a virtual", "directory to a container. text: az storage azcopy blob upload -c MyContainer --account-name", "in resource group 'MyResourceGroup' in the West US region with locally redundant storage.", "a storage account. \"\"\" helps['storage blob service-properties'] = \"\"\" type: group short-summary: Manage", "from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\"", "\"path/to/file\" -d NewBlob - name: Upload a directory to a container. text: az", "command short-summary: Create a storage account. long-summary: > The SKU of the storage", "download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download a", "blobs from a storage blob container using AzCopy. examples: - name: Download a", "azcopy run-command'] = \"\"\" type: command short-summary: Run a command directly using the", "text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s * -d", "storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage", "storage blob container using AzCopy. examples: - name: Delete a single blob from", "\"\"\" type: command short-summary: Delete blobs from a storage blob container using AzCopy.", "the specified storage account. \"\"\" helps['storage account management-policy update'] = \"\"\" type: command", "all blobs in a virtual directory. text: az storage azcopy blob delete -c", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.", "management policies. \"\"\" helps['storage account management-policy create'] = \"\"\" type: command short-summary: Creates", "- name: Upload the contents of a directory to a container. text: az", "container using AzCopy. examples: - name: Delete a single blob from a container.", "short-summary: Download blobs from a storage blob container using AzCopy. examples: - name:", "blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command']", "short-summary: Creates the data policy rules associated with the specified storage account. \"\"\"", "MyStorageAccount -s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\"", "type: command short-summary: Delete blobs from a storage blob container using AzCopy. examples:", "short-summary: Manage object storage for unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy", "from a storage blob container using AzCopy. examples: - name: Delete a single", "TargetBlob - name: Delete all blobs from a container. text: az storage azcopy", "a container. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s", "--recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\" type: command short-summary: Delete blobs", "storage account defaults to 'Standard_RAGRS'. examples: - name: Create a storage account 'MyStorageAccount'", "storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete", "--recursive \"\"\" helps['storage azcopy run-command'] = \"\"\" type: command short-summary: Run a command", "\"\"\" type: group short-summary: Manage storage blob service properties. \"\"\" helps['storage blob service-properties", "container using AzCopy. examples: - name: Upload a single blob to a container.", "command directly using the AzCopy CLI. Please use SAS tokens for authentication. \"\"\"", "defaults to 'Standard_RAGRS'. examples: - name: Create a storage account 'MyStorageAccount' in resource", "\"\"\" helps['storage azcopy blob upload'] = \"\"\" type: command short-summary: Upload blobs to", "command short-summary: Upload blobs to a storage blob container using AzCopy. examples: -", "= \"\"\" type: group short-summary: Manage storage blob service properties. \"\"\" helps['storage blob", "of a container onto a local file system. text: az storage azcopy blob", "the contents of a directory to a container. text: az storage azcopy blob", "--account-name MyStorageAccount -s \"path/to/directory\" --recursive - name: Upload the contents of a directory", "short-summary: Manage storage account management policies. \"\"\" helps['storage account management-policy create'] = \"\"\"", "azcopy'] = \"\"\" type: group short-summary: | [EXPERIMENTAL] Manage storage operations utilizing AzCopy.", "using AzCopy. examples: - name: Upload a single blob to a container. text:", "helps['storage azcopy blob delete'] = \"\"\" type: command short-summary: Delete blobs from a", "short-summary: Update storage blob service properties. \"\"\" helps['storage account management-policy'] = \"\"\" type:", "MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete all blobs from a container.", "= \"\"\" type: command short-summary: Updates the data policy rules associated with the", "under the MIT License. See License.txt in the project root for license information.", "download'] = \"\"\" type: command short-summary: Download blobs from a storage blob container", "account create -n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account", "helps['storage account update'] = \"\"\" type: command short-summary: Update the properties of a", "azcopy blob'] = \"\"\" type: group short-summary: Manage object storage for unstructured data", "short-summary: Manage storage blob service properties. \"\"\" helps['storage blob service-properties update'] = \"\"\"", "blob service-properties update'] = \"\"\" type: command short-summary: Update storage blob service properties.", "a storage blob container using AzCopy. examples: - name: Download a single blob", "MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d \"download/path\" --recursive - name: Download the contents", "\"\"\" type: group short-summary: Manage object storage for unstructured data (blobs) using AzCopy.", "project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint:", "text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d", "\"\"\" helps['storage blob service-properties'] = \"\"\" type: group short-summary: Manage storage blob service", "a container. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive", "service-properties'] = \"\"\" type: group short-summary: Manage storage blob service properties. \"\"\" helps['storage", "License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from", "local file system. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount", "-------------------------------------------------------------------------------------------- from knack.help_files import helps # pylint: disable=line-too-long, too-many-lines helps['storage account create'] =", "Upload blobs to a storage blob container using AzCopy. examples: - name: Upload", "azcopy blob delete -c MyContainer --account-name MyStorageAccount -t TargetBlob - name: Delete all", "azcopy blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy", "from a storage blob container using AzCopy. examples: - name: Download a single", "storage blob service properties. \"\"\" helps['storage account management-policy'] = \"\"\" type: group short-summary:", "account management-policy create'] = \"\"\" type: command short-summary: Creates the data policy rules", "Download a single blob from a container. text: az storage azcopy blob download", "examples: - name: Upload a single blob to a container. text: az storage", "group short-summary: Manage object storage for unstructured data (blobs) using AzCopy. \"\"\" helps['storage", "Create a storage account. long-summary: > The SKU of the storage account defaults", "management-policy update'] = \"\"\" type: command short-summary: Updates the data policy rules associated", "storage for unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload'] =", "<reponame>mboersma/azure-cli-extensions # coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "container. text: az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive -", "a single blob to a container. text: az storage azcopy blob upload -c", "helps['storage account management-policy'] = \"\"\" type: group short-summary: Manage storage account management policies.", "with locally redundant storage. text: az storage account create -n MyStorageAccount -g MyResourceGroup", "-s * -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\" type:", "MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\"", "az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount --recursive - name: Delete", "Updates the data policy rules associated with the specified storage account. \"\"\" helps['storage", "\"\"\" helps['storage account management-policy create'] = \"\"\" type: command short-summary: Creates the data", "Licensed under the MIT License. See License.txt in the project root for license", "-d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\" type: command short-summary:", "blob download'] = \"\"\" type: command short-summary: Download blobs from a storage blob", "storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob -", "az storage azcopy blob delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\"", "Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in", "in the West US region with locally redundant storage. text: az storage account", "a local file system. text: az storage azcopy blob download -c MyContainer --account-name", "type: group short-summary: Manage storage account management policies. \"\"\" helps['storage account management-policy create']", "text: az storage account create -n MyStorageAccount -g MyResourceGroup -l westus --sku Standard_LRS", "--account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload a directory to a", "MyStorageAccount -s \"path/to/directory/*\" --recursive \"\"\" helps['storage azcopy blob download'] = \"\"\" type: command", "- name: Upload a single blob to a container. text: az storage azcopy", "container. text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\"", "MyContainer --account-name MyStorageAccount --recursive - name: Delete all blobs in a virtual directory.", "pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type: command short-summary: Create a", "\"\"\" helps['storage account management-policy update'] = \"\"\" type: command short-summary: Updates the data", "text: az storage azcopy blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/virtual_directory\" -d", "properties. \"\"\" helps['storage account management-policy'] = \"\"\" type: group short-summary: Manage storage account", "rights reserved. # Licensed under the MIT License. See License.txt in the project", "a storage account 'MyStorageAccount' in resource group 'MyResourceGroup' in the West US region", "--sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type: command short-summary: Update the", "the properties of a storage account. \"\"\" helps['storage blob service-properties'] = \"\"\" type:", "helps['storage azcopy blob download'] = \"\"\" type: command short-summary: Download blobs from a", "--account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download a virtual directory from", "single blob from a container. text: az storage azcopy blob delete -c MyContainer", "management-policy create'] = \"\"\" type: command short-summary: Creates the data policy rules associated", "account. \"\"\" helps['storage blob service-properties'] = \"\"\" type: group short-summary: Manage storage blob", "management-policy'] = \"\"\" type: group short-summary: Manage storage account management policies. \"\"\" helps['storage", "AzCopy. examples: - name: Download a single blob from a container. text: az", "\"\"\" type: command short-summary: Updates the data policy rules associated with the specified", "type: group short-summary: Manage storage blob service properties. \"\"\" helps['storage blob service-properties update']", "text: az storage azcopy blob upload -c MyContainer --account-name MyStorageAccount -s \"path/to/directory\" --recursive", "blobs from a storage blob container using AzCopy. examples: - name: Delete a", "short-summary: Run a command directly using the AzCopy CLI. Please use SAS tokens", "\"path/to/blob\" -d \"path/to/file\" - name: Download a virtual directory from a container. text:", "associated with the specified storage account. \"\"\" helps['storage azcopy'] = \"\"\" type: group", "import helps # pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type: command", "short-summary: Upload blobs to a storage blob container using AzCopy. examples: - name:", "a storage account. long-summary: > The SKU of the storage account defaults to", "- name: Download the contents of a container onto a local file system.", "\"\"\" helps['storage azcopy run-command'] = \"\"\" type: command short-summary: Run a command directly", "-d \"download/path\" --recursive - name: Download the contents of a container onto a", "long-summary: > The SKU of the storage account defaults to 'Standard_RAGRS'. examples: -", "blob from a container. text: az storage azcopy blob download -c MyContainer --account-name", "* -d \"download/path\" --recursive \"\"\" helps['storage azcopy blob delete'] = \"\"\" type: command", "short-summary: Update the properties of a storage account. \"\"\" helps['storage blob service-properties'] =", "delete -c MyContainer --account-name MyStorageAccount -t \"path/to/virtual_directory\" --recursive \"\"\" helps['storage azcopy run-command'] =", "blob download -c MyContainer --account-name MyStorageAccount -s \"path/to/blob\" -d \"path/to/file\" - name: Download", "MyStorageAccount --recursive - name: Delete all blobs in a virtual directory. text: az", "name: Delete a single blob from a container. text: az storage azcopy blob", "short-summary: Updates the data policy rules associated with the specified storage account. \"\"\"", "update'] = \"\"\" type: command short-summary: Updates the data policy rules associated with", "onto a local file system. text: az storage azcopy blob download -c MyContainer", "MyContainer --account-name MyStorageAccount -s \"path/to/file\" -d NewBlob - name: Upload a directory to", "# coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "helps # pylint: disable=line-too-long, too-many-lines helps['storage account create'] = \"\"\" type: command short-summary:", "storage account. long-summary: > The SKU of the storage account defaults to 'Standard_RAGRS'.", "too-many-lines helps['storage account create'] = \"\"\" type: command short-summary: Create a storage account.", "data policy rules associated with the specified storage account. \"\"\" helps['storage account management-policy", "-g MyResourceGroup -l westus --sku Standard_LRS \"\"\" helps['storage account update'] = \"\"\" type:", "operations utilizing AzCopy. long-summary: | Open issues here: https://github.com/Azure/azure-storage-azcopy \"\"\" helps['storage azcopy blob']", "\"\"\" helps['storage azcopy blob delete'] = \"\"\" type: command short-summary: Delete blobs from", "redundant storage. text: az storage account create -n MyStorageAccount -g MyResourceGroup -l westus", "blobs from a container. text: az storage azcopy blob delete -c MyContainer --account-name", "'MyStorageAccount' in resource group 'MyResourceGroup' in the West US region with locally redundant", "contents of a container onto a local file system. text: az storage azcopy", "upload'] = \"\"\" type: command short-summary: Upload blobs to a storage blob container", "unstructured data (blobs) using AzCopy. \"\"\" helps['storage azcopy blob upload'] = \"\"\" type:" ]
[ "{} for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input):", "input[property] else {} return result def to_dict(self): result = {} if self.last_state: result['last_state']", "SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not source: return None result =", "result = {} if self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at']", "def from_dict(source): if not source: return None result = ReflectorConfig() result.timestamp = source.get('timestamp')", "result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not source: return None", "not source: return None result = {} for key in source: result[key] =", "source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for", "to_dict(self): result = {} if self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version:", "schema class\"\"\" def __init__(self): self.timestamp = None self.version = None self.setup = None", "if input[property] else {} return result def to_dict(self): result = {} if self.timestamp:", "def from_dict(source): if not source: return None result = SetupReflectorConfig() result.last_state = source.get('last_state')", "return result @staticmethod def expand_dict(input): result = {} for property in input: result[property]", "from_dict(source): if not source: return None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at", "class\"\"\" def __init__(self): self.timestamp = None self.version = None self.setup = None @staticmethod", "self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp", "self.version = None self.setup = None @staticmethod def from_dict(source): if not source: return", "= self.version # 5 if self.setup: result['setup'] = self.setup.to_dict() # 4 return result", "in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {}", "class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at = None", "= SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not source: return None result", "source: return None result = {} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key])", "None result = {} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result", "result = {} if self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version: result['version']", "= SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property in", "None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup'))", "for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result", "self.deployed_at = None @staticmethod def from_dict(source): if not source: return None result =", "= {} for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def", "key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result =", "None @staticmethod def from_dict(source): if not source: return None result = ReflectorConfig() result.timestamp", "not source: return None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at')", "in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {}", "= None self.version = None self.setup = None @staticmethod def from_dict(source): if not", "if self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version: result['version'] = self.version #", "{} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input):", "= {} if self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version: result['version'] =", "result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source): if not source: return None", "= self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result", "@staticmethod def from_dict(source): if not source: return None result = ReflectorConfig() result.timestamp =", "result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property", "5 if self.version: result['version'] = self.version # 5 if self.setup: result['setup'] = self.setup.to_dict()", "= input[property].to_dict() if input[property] else {} return result def to_dict(self): result = {}", "# 5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result class ReflectorConfig:", "= SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source):", "return result def to_dict(self): result = {} if self.last_state: result['last_state'] = self.last_state #", "None self.setup = None @staticmethod def from_dict(source): if not source: return None result", "self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\"", "source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for", "self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result class", "if not source: return None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version =", "for reflect_config.json\"\"\" class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at", "return None result = {} for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return", "SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source): if", "= source.get('deployed_at') return result @staticmethod def map_from(source): if not source: return None result", "= ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result", "# 5 if self.version: result['version'] = self.version # 5 if self.setup: result['setup'] =", "def expand_dict(input): result = {} for property in input: result[property] = input[property].to_dict() if", "result['version'] = self.version # 5 if self.setup: result['setup'] = self.setup.to_dict() # 4 return", "<filename>gencode/python/udmi/schema/reflect_config.py<gh_stars>1-10 \"\"\"Generated class for reflect_config.json\"\"\" class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state", "result['timestamp'] = self.timestamp # 5 if self.version: result['version'] = self.version # 5 if", "reflect_config.json\"\"\" class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at =", "= None self.setup = None @staticmethod def from_dict(source): if not source: return None", "def map_from(source): if not source: return None result = {} for key in", "def __init__(self): self.timestamp = None self.version = None self.setup = None @staticmethod def", "= ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property in", "for property in input: result[property] = input[property].to_dict() if input[property] else {} return result", "result = {} for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod", "if self.version: result['version'] = self.version # 5 if self.setup: result['setup'] = self.setup.to_dict() #", "result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return", "5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated", "None self.deployed_at = None @staticmethod def from_dict(source): if not source: return None result", "def __init__(self): self.last_state = None self.deployed_at = None @staticmethod def from_dict(source): if not", "None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod", "return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None self.version", "source: return None result = {} for key in source: result[key] = ReflectorConfig.from_dict(source[key])", "= source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source): if not source:", "return None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result", "result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def", "source.get('deployed_at') return result @staticmethod def map_from(source): if not source: return None result =", "input[property].to_dict() if input[property] else {} return result def to_dict(self): result = {} if", "property in input: result[property] = input[property].to_dict() if input[property] else {} return result def", "return result @staticmethod def map_from(source): if not source: return None result = {}", "map_from(source): if not source: return None result = {} for key in source:", "= source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source):", "key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result =", "\"\"\"Generated class for reflect_config.json\"\"\" class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state =", "result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source): if not", "self.version: result['version'] = self.version # 5 if self.setup: result['setup'] = self.setup.to_dict() # 4", "result[property] = input[property].to_dict() if input[property] else {} return result def to_dict(self): result =", "class for reflect_config.json\"\"\" class SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None", "result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not", "source: return None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at = source.get('deployed_at') return", "if self.deployed_at: result['deployed_at'] = self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated schema", "source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if", "source: return None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup", "schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at = None @staticmethod def from_dict(source):", "source.get('last_state') result.deployed_at = source.get('deployed_at') return result @staticmethod def map_from(source): if not source: return", "= None @staticmethod def from_dict(source): if not source: return None result = SetupReflectorConfig()", "= {} if self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at'] =", "not source: return None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version')", "= None self.deployed_at = None @staticmethod def from_dict(source): if not source: return None", "class\"\"\" def __init__(self): self.last_state = None self.deployed_at = None @staticmethod def from_dict(source): if", "= source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not source:", "result['deployed_at'] = self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def", "\"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at = None @staticmethod def", "__init__(self): self.last_state = None self.deployed_at = None @staticmethod def from_dict(source): if not source:", "if not source: return None result = SetupReflectorConfig() result.last_state = source.get('last_state') result.deployed_at =", "class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None self.version = None", "if self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at #", "def to_dict(self): result = {} if self.timestamp: result['timestamp'] = self.timestamp # 5 if", "return None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup =", "if not source: return None result = {} for key in source: result[key]", "SetupReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.last_state = None self.deployed_at = None @staticmethod", "else {} return result def to_dict(self): result = {} if self.timestamp: result['timestamp'] =", "\"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None self.version = None self.setup =", "ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property in input:", "{} if self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version: result['version'] = self.version", "self.timestamp # 5 if self.version: result['version'] = self.version # 5 if self.setup: result['setup']", "None @staticmethod def from_dict(source): if not source: return None result = SetupReflectorConfig() result.last_state", "None self.version = None self.setup = None @staticmethod def from_dict(source): if not source:", "self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at # 5", "else {} return result def to_dict(self): result = {} if self.last_state: result['last_state'] =", "{} return result def to_dict(self): result = {} if self.last_state: result['last_state'] = self.last_state", "{} if self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at: result['deployed_at'] = self.deployed_at", "= self.timestamp # 5 if self.version: result['version'] = self.version # 5 if self.setup:", "result @staticmethod def map_from(source): if not source: return None result = {} for", "input: result[property] = input[property].to_dict() if input[property] else {} return result def to_dict(self): result", "__init__(self): self.timestamp = None self.version = None self.setup = None @staticmethod def from_dict(source):", "source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def map_from(source): if not source: return", "result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property", "if input[property] else {} return result def to_dict(self): result = {} if self.last_state:", "from_dict(source): if not source: return None result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version", "= {} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def", "return None result = {} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return", "SetupReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result = {} for property in input:", "@staticmethod def from_dict(source): if not source: return None result = SetupReflectorConfig() result.last_state =", "return result def to_dict(self): result = {} if self.timestamp: result['timestamp'] = self.timestamp #", "self.setup = None @staticmethod def from_dict(source): if not source: return None result =", "result = ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return", "result = {} for property in input: result[property] = input[property].to_dict() if input[property] else", "5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None", "{} for property in input: result[property] = input[property].to_dict() if input[property] else {} return", "result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod def", "= self.deployed_at # 5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self):", "ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None self.version = None self.setup", "= None @staticmethod def from_dict(source): if not source: return None result = ReflectorConfig()", "result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp = None self.version =", "result def to_dict(self): result = {} if self.timestamp: result['timestamp'] = self.timestamp # 5", "in input: result[property] = input[property].to_dict() if input[property] else {} return result def to_dict(self):", "self.timestamp = None self.version = None self.setup = None @staticmethod def from_dict(source): if", "# 5 return result class ReflectorConfig: \"\"\"Generated schema class\"\"\" def __init__(self): self.timestamp =", "result = {} for key in source: result[key] = SetupReflectorConfig.from_dict(source[key]) return result @staticmethod", "@staticmethod def map_from(source): if not source: return None result = {} for key", "ReflectorConfig() result.timestamp = source.get('timestamp') result.version = source.get('version') result.setup = SetupReflectorConfig.from_dict(source.get('setup')) return result @staticmethod", "for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result @staticmethod def expand_dict(input): result", "None result = {} for key in source: result[key] = ReflectorConfig.from_dict(source[key]) return result", "to_dict(self): result = {} if self.last_state: result['last_state'] = self.last_state # 5 if self.deployed_at:", "def to_dict(self): result = {} if self.last_state: result['last_state'] = self.last_state # 5 if", "result def to_dict(self): result = {} if self.last_state: result['last_state'] = self.last_state # 5", "self.timestamp: result['timestamp'] = self.timestamp # 5 if self.version: result['version'] = self.version # 5", "= {} for property in input: result[property] = input[property].to_dict() if input[property] else {}", "{} return result def to_dict(self): result = {} if self.timestamp: result['timestamp'] = self.timestamp", "@staticmethod def expand_dict(input): result = {} for property in input: result[property] = input[property].to_dict()", "result @staticmethod def expand_dict(input): result = {} for property in input: result[property] =", "input[property] else {} return result def to_dict(self): result = {} if self.timestamp: result['timestamp']", "expand_dict(input): result = {} for property in input: result[property] = input[property].to_dict() if input[property]", "self.last_state = None self.deployed_at = None @staticmethod def from_dict(source): if not source: return" ]
[ "import os import os.path import sys import re import json import pandas as", "%(levelname)-8s - %(message)s') # create console handler and set level to info handler", "\"all_contig_annotations.json\") sample_data = [record for record in json_data if record['barcode'] in barcode_dict and", "'--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output", "file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1:", "re import json import pandas as pd from collections import OrderedDict def initialize_logger(logfile,", "== 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file,", "sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4)", "type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG)", "hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG", "samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file)", "open(json_file, \"rt\") as fin: data = json.load(fin) for record in data: json_data.append(record) for", "logger.info(\"reading %s\" % json_file) json_data = [] with open(json_file, \"rt\") as fin: data", "fin: data = json.load(fin) for record in data: json_data.append(record) for sample_name in samples_dict.values():", "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') # create console handler", "= os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data =", "parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1)", "json_file) json_data = [] with open(json_file, \"rt\") as fin: data = json.load(fin) for", "= initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger) if __name__ == \"__main__\":", "logging import os import os.path import sys import re import json import pandas", "and set level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger)", "required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store',", "== sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout,", "pd from collections import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel =", "logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s -", "- %(levelname)-8s - %(message)s') # create console handler and set level to info", "logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and set level to", "args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input,", "DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone", "exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading", "os import os.path import sys import re import json import pandas as pd", "nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if", "sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file =", "console handler and set level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler)", "'--input', action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?',", "and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as fout:", "action='store', nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args =", "header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data", "not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\"", "def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] ==", "len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input,", "= parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample,", "for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file", "if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger", "if not os. path. isfile(filename): print(\"error: file not exists: \" + filename) parser.print_help()", "parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser)", "\" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\"", "logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict)", "% cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading", "clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store',", "DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\"", "to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser):", "logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os. path. isfile(filename): print(\"error: file not", "required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store',", "json.load(fin) for record in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder,", "sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in json_data if record['barcode']", "check_file(filename, parser): if not os. path. isfile(filename): print(\"error: file not exists: \" +", "data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder):", "in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder,", "def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG =", "os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in json_data if", "sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser", "action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag", "import argparse import logging import os import os.path import sys import re import", "- %(message)s') # create console handler and set level to info handler =", "= False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type", "handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and set level to error", "import re import json import pandas as pd from collections import OrderedDict def", "args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output,", "%s\" % json_file) json_data = [] with open(json_file, \"rt\") as fin: data =", "check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag,", "cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:,", "import pandas as pd from collections import OrderedDict def initialize_logger(logfile, args): logger =", "logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os. path.", "info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and", "os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in json_data if record['barcode'] in barcode_dict", "data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?',", "pandas as pd from collections import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split')", "json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file)", "import json import pandas as pd from collections import OrderedDict def initialize_logger(logfile, args):", "dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = [] with", "cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" %", "[record for record in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name]", "nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample", "json_data = [] with open(json_file, \"rt\") as fin: data = json.load(fin) for record", "with open(json_file, \"rt\") as fin: data = json.load(fin) for record in data: json_data.append(record)", "args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s", "create console handler and set level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter)", "nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell", "fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG =", "main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not", "= [] with open(json_file, \"rt\") as fin: data = json.load(fin) for record in", "%(name)s - %(levelname)-8s - %(message)s') # create console handler and set level to", "to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler", "logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') # create console", "= [record for record in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] ==", "= dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = []", "in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" %", "help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\",", "in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\")", "# create console handler and set level to info handler = logging.StreamHandler() handler.setLevel(loglevel)", "split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet']", "samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data,", "'--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args", "isfile(filename): print(\"error: file not exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file,", "if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\"", "print(\"error: file not exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file,", "NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json file\",", "argparse import logging import os import os.path import sys import re import json", "indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False", "level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file", "parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?',", "record in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\"", "as pd from collections import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel", "logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG", "data = json.load(fin) for record in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder", "json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder)", "- %(name)s - %(levelname)-8s - %(message)s') # create console handler and set level", "filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file)", "os. path. isfile(filename): print(\"error: file not exists: \" + filename) parser.print_help() sys.exit(1) def", "dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:,", "<filename>lib/scRNA/clonotype_split.py import argparse import logging import os import os.path import sys import re", "nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args()", "set level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def", "json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG", "parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?',", "= logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and set level", "sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag,", "sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG and", "if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record", "parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample,", "cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG)", "= logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s", "os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record", "logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s -", "def check_file(filename, parser): if not os. path. isfile(filename): print(\"error: file not exists: \"", "error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if", "not exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger):", "as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\",", "sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global']", "parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser)", "parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger) if __name__", "help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not", "help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if", "parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG", "args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser)", "hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict =", "args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args)", "%s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict)", "= logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') # create console handler and", "for record in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing", "folder\") if not DEBUG and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG:", "parser): if not os. path. isfile(filename): print(\"error: file not exists: \" + filename)", "%s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading", "parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store',", "handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and set", "from collections import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO", "set level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create error", "and set level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) # create", "\"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype", "check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output,", "hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o',", "#print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0]))", "sys import re import json import pandas as pd from collections import OrderedDict", "logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') # create", "= dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict =", "action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\")", "DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger =", "= logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os.", "cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\"", "in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not", "args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\" check_file(args.input, parser) check_file(args.cell_hashtag, parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"),", "action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input", "import os.path import sys import re import json import pandas as pd from", "[] with open(json_file, \"rt\") as fin: data = json.load(fin) for record in data:", "parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file)", "not os. path. isfile(filename): print(\"error: file not exists: \" + filename) parser.print_help() sys.exit(1)", "1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = [] with open(json_file,", "= argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i',", "argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input',", "return(logger) def check_file(filename, parser): if not os. path. isfile(filename): print(\"error: file not exists:", "'--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input", "0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1],", "handler.setFormatter(formatter) logger.addHandler(handler) # create error file handler and set level to error handler", "not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c',", "json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s',", "'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None)", "if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with", "path. isfile(filename): print(\"error: file not exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file,", "samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = [] with open(json_file, \"rt\")", "create error file handler and set level to error handler = logging.FileHandler(logfile, \"w\")", "record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file,", "False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json", "file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample', action='store', nargs='?', help=\"Input hashtag sample file\", required=NOT_DEBUG) parser.add_argument('-o', '--output',", "level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename,", "sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for", "logger.addHandler(handler) # create error file handler and set level to error handler =", "fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge clonotype data\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)", "handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os. path. isfile(filename): print(\"error:", "with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser =", "logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0],", "logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\")", "handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not", "samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\")", "required=NOT_DEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help=\"Output folder\") if not DEBUG and len(sys.argv)==1: parser.print_help()", "collections import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel)", "def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s", "# create error file handler and set level to error handler = logging.FileHandler(logfile,", "logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO))", "handler and set level to info handler = logging.StreamHandler() handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) #", "hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" %", "cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict", "for record in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name)", "initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s -", "sample_folder = os.path.join(output_folder, sample_name) if not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data", "parser) check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger)", "handler and set level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler)", "check_file(args.hashtag_sample, parser) logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger) if", "= not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG)", "logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') # create console handler and set", "% hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\"", "%s\" % sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def", "as fin: data = json.load(fin) for record in data: json_data.append(record) for sample_name in", "help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag", "initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger) if __name__ == \"__main__\": main()", "= logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') #", "json import pandas as pd from collections import OrderedDict def initialize_logger(logfile, args): logger", "import OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter", "handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os. path. isfile(filename): print(\"error: file", "barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file) samples=pd.read_table(hashtag_sample_file, header=None) samples_dict", "print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = [] with open(json_file, \"rt\") as fin:", "output_folder, logger): logger.info(\"reading %s\" % cell_hashtag_file) cells=pd.read_csv(cell_hashtag_file) cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:,", "0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data = [] with open(json_file, \"rt\") as", "import sys import re import json import pandas as pd from collections import", "%(message)s') # create console handler and set level to info handler = logging.StreamHandler()", "samples_dict = dict(zip(samples.iloc[:, 1], samples.iloc[:, 0])) print(samples_dict) logger.info(\"reading %s\" % json_file) json_data =", "loglevel = logging.INFO logger.setLevel(loglevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s')", "% json_file) json_data = [] with open(json_file, \"rt\") as fin: data = json.load(fin)", "= json.load(fin) for record in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder =", "os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in json_data", "% sample_file) with open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main():", "file handler and set level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel) handler.setFormatter(formatter)", "\"rt\") as fin: data = json.load(fin) for record in data: json_data.append(record) for sample_name", "record in data: json_data.append(record) for sample_name in samples_dict.values(): sample_folder = os.path.join(output_folder, sample_name) if", "sample_data = [record for record in json_data if record['barcode'] in barcode_dict and samples_dict[barcode_dict[record['barcode']]]", "not os.path.isdir(sample_folder): os.mkdir(sample_folder) sample_file = os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in", "DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag',", "file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\", required=NOT_DEBUG) parser.add_argument('-s', '--hashtag_sample',", "import logging import os import os.path import sys import re import json import", "error file handler and set level to error handler = logging.FileHandler(logfile, \"w\") handler.setLevel(loglevel)", "OrderedDict def initialize_logger(logfile, args): logger = logging.getLogger('clonotype_split') loglevel = logging.INFO logger.setLevel(loglevel) formatter =", "cells=cells.loc[cells['HTO.global'] == 'Singlet'] barcode_dict = dict(zip(cells.iloc[:, 0], cells.HTO)) #print(barcode_dict) logger.info(\"reading %s\" % hashtag_sample_file)", "os.path import sys import re import json import pandas as pd from collections", "and len(sys.argv)==1: parser.print_help() sys.exit(1) args = parser.parse_args() if DEBUG: args.input=\"/data/cqs/alexander_gelbard_data/AG_5126_10X/VDJ/5126-AG-4/all_contig_annotations.json\" args.cell_hashtag=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_samples/result/COVID/COVID.HTO.csv\" args.hashtag_sample=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/split_bam/result/fileList_3_COVID.txt\" args.output=\"/scratch/cqs/alexander_gelbard_projects/20201202_5126_scRNA_split/clonotype_split/result/\"", "formatter_class=argparse.ArgumentDefaultsHelpFormatter) DEBUG = False NOT_DEBUG = not DEBUG parser.add_argument('-i', '--input', action='store', nargs='?', help=\"Input", "\"w\") handler.setLevel(loglevel) handler.setFormatter(formatter) logger.addHandler(handler) return(logger) def check_file(filename, parser): if not os. path. isfile(filename):", "+ filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder, logger): logger.info(\"reading %s\" %", "barcode_dict and samples_dict[barcode_dict[record['barcode']]] == sample_name] logger.info(\"writing %s\" % sample_file) with open(sample_file, \"wt\") as", "file not exists: \" + filename) parser.print_help() sys.exit(1) def split(json_file, cell_hashtag_file, hashtag_sample_file, output_folder,", "= os.path.join(sample_folder, \"all_contig_annotations.json\") sample_data = [record for record in json_data if record['barcode'] in", "open(sample_file, \"wt\") as fout: json.dump(sample_data, fout, indent=4) logger.info(\"done\") def main(): parser = argparse.ArgumentParser(description=\"merge", "logger = initialize_logger(os.path.join(args.output, \"clonotype_split.log\"), args) split(args.input, args.cell_hashtag, args.hashtag_sample, args.output, logger) if __name__ ==", "clone type json file\", required=NOT_DEBUG) parser.add_argument('-c', '--cell_hashtag', action='store', nargs='?', help=\"Input cell hashtag file\"," ]
[ "if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters >", "scripture do you want to look at? 1. Old Testament 2. New Testament", "Great Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book =", "{book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The", "\"Pearl of Great Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip()", "look at? 1. Old Testament 2. New Testament 3. Book of Mormon 4.", "Pearl of Great Price \"\"\") if user_choice == \"1\": chosen_b_section = \"Old Testament\"", "New Testament 3. Book of Mormon 4. Doctrine and Covenants 5. Pearl of", "clean_list = line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section", "int(book[1]) book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters:", "if book_chapters > largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest", "\"\" user_choice = input(\"\"\" What volume of scripture do you want to look", "Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\")", "= input(\"\"\" What volume of scripture do you want to look at? 1.", "chosen_b_section = \"Pearl of Great Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list", "\"3\": chosen_b_section = \"Book of Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine", "Testament\" elif user_choice == \"2\": chosen_b_section = \"New Testament\" elif user_choice == \"3\":", "book[0] book_chapters = int(book[1]) book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section},", "elif user_choice == \"3\": chosen_b_section = \"Book of Mormon\" elif user_choice == \"4\":", "1. Old Testament 2. New Testament 3. Book of Mormon 4. Doctrine and", "Testament clean_list = line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1])", "book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\")", "user_choice == \"3\": chosen_b_section = \"Book of Mormon\" elif user_choice == \"4\": chosen_b_section", "you want to look at? 1. Old Testament 2. New Testament 3. Book", "{book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters largest_book_name = book_name", "= 0 largest_book_name = \"\" chosen_b_section = \"\" user_choice = input(\"\"\" What volume", "\"Book of Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\" elif", "book_chapters = int(book[1]) book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book:", "== chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book", "\"New Testament\" elif user_choice == \"3\": chosen_b_section = \"Book of Mormon\" elif user_choice", "\"\" chosen_b_section = \"\" user_choice = input(\"\"\" What volume of scripture do you", "largest_book_name = \"\" chosen_b_section = \"\" user_choice = input(\"\"\" What volume of scripture", "\"2\": chosen_b_section = \"New Testament\" elif user_choice == \"3\": chosen_b_section = \"Book of", "scripture_list: largest_book = 0 largest_book_name = \"\" chosen_b_section = \"\" user_choice = input(\"\"\"", "== \"2\": chosen_b_section = \"New Testament\" elif user_choice == \"3\": chosen_b_section = \"Book", "elif user_choice == \"5\": chosen_b_section = \"Pearl of Great Price\" for line in", "line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section = book[2]", "print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters", "Price \"\"\") if user_choice == \"1\": chosen_b_section = \"Old Testament\" elif user_choice ==", "\"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl", "chosen_b_section = \"Book of Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine and", "= line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section =", "book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book is {largest_book_name} with {largest_book} chapters\")", "in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\") book_name = book[0]", "user_choice == \"5\": chosen_b_section = \"Pearl of Great Price\" for line in scripture_list:", "3. Book of Mormon 4. Doctrine and Covenants 5. Pearl of Great Price", "= int(book[1]) book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name},", "What volume of scripture do you want to look at? 1. Old Testament", "\"5\": chosen_b_section = \"Pearl of Great Price\" for line in scripture_list: #Genesis:50:Old Testament", "= \"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl of Great", "Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl of Great Price\" for line", "\"\"\") if user_choice == \"1\": chosen_b_section = \"Old Testament\" elif user_choice == \"2\":", "book_chapters > largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book", "chosen_b_section = \"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl of", "= \"Book of Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\"", "user_choice == \"2\": chosen_b_section = \"New Testament\" elif user_choice == \"3\": chosen_b_section =", "Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice ==", "{book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters largest_book_name", "= \"Old Testament\" elif user_choice == \"2\": chosen_b_section = \"New Testament\" elif user_choice", "= book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if", "if user_choice == \"1\": chosen_b_section = \"Old Testament\" elif user_choice == \"2\": chosen_b_section", "clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section = book[2] if book_section ==", "Testament\" elif user_choice == \"3\": chosen_b_section = \"Book of Mormon\" elif user_choice ==", "#Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters =", "of Great Price \"\"\") if user_choice == \"1\": chosen_b_section = \"Old Testament\" elif", "at? 1. Old Testament 2. New Testament 3. Book of Mormon 4. Doctrine", "\"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl of Great Price\"", "chosen_b_section = \"New Testament\" elif user_choice == \"3\": chosen_b_section = \"Book of Mormon\"", "of Great Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book", "\"1\": chosen_b_section = \"Old Testament\" elif user_choice == \"2\": chosen_b_section = \"New Testament\"", "of Mormon\" elif user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice", "= \"Pearl of Great Price\" for line in scripture_list: #Genesis:50:Old Testament clean_list =", "open(\"week 12/books_and_chapters.txt\") as scripture_list: largest_book = 0 largest_book_name = \"\" chosen_b_section = \"\"", "book = clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section = book[2] if", "user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section", "Doctrine and Covenants 5. Pearl of Great Price \"\"\") if user_choice == \"1\":", "largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book is {largest_book_name} with", "chosen_b_section = \"\" user_choice = input(\"\"\" What volume of scripture do you want", "12/books_and_chapters.txt\") as scripture_list: largest_book = 0 largest_book_name = \"\" chosen_b_section = \"\" user_choice", "do you want to look at? 1. Old Testament 2. New Testament 3.", "Covenants 5. Pearl of Great Price \"\"\") if user_choice == \"1\": chosen_b_section =", "> largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book is", "chosen_b_section = \"Old Testament\" elif user_choice == \"2\": chosen_b_section = \"New Testament\" elif", "== \"3\": chosen_b_section = \"Book of Mormon\" elif user_choice == \"4\": chosen_b_section =", "largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book is {largest_book_name}", "Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters largest_book_name =", "Old Testament 2. New Testament 3. Book of Mormon 4. Doctrine and Covenants", "5. Pearl of Great Price \"\"\") if user_choice == \"1\": chosen_b_section = \"Old", "Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book = book_chapters largest_book_name = book_name print(\"*\"*20)", "input(\"\"\" What volume of scripture do you want to look at? 1. Old", "4. Doctrine and Covenants 5. Pearl of Great Price \"\"\") if user_choice ==", "= \"\" chosen_b_section = \"\" user_choice = input(\"\"\" What volume of scripture do", "Mormon 4. Doctrine and Covenants 5. Pearl of Great Price \"\"\") if user_choice", "== \"5\": chosen_b_section = \"Pearl of Great Price\" for line in scripture_list: #Genesis:50:Old", "of Mormon 4. Doctrine and Covenants 5. Pearl of Great Price \"\"\") if", "elif user_choice == \"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice == \"5\":", "= book_chapters largest_book_name = book_name print(\"*\"*20) print(f\"The largest book is {largest_book_name} with {largest_book}", "of scripture do you want to look at? 1. Old Testament 2. New", "scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\") book_name = book[0] book_chapters", "2. New Testament 3. Book of Mormon 4. Doctrine and Covenants 5. Pearl", "elif user_choice == \"2\": chosen_b_section = \"New Testament\" elif user_choice == \"3\": chosen_b_section", "user_choice == \"1\": chosen_b_section = \"Old Testament\" elif user_choice == \"2\": chosen_b_section =", "to look at? 1. Old Testament 2. New Testament 3. Book of Mormon", "\"Old Testament\" elif user_choice == \"2\": chosen_b_section = \"New Testament\" elif user_choice ==", "Great Price \"\"\") if user_choice == \"1\": chosen_b_section = \"Old Testament\" elif user_choice", "volume of scripture do you want to look at? 1. Old Testament 2.", "want to look at? 1. Old Testament 2. New Testament 3. Book of", "= clean_list.split(\":\") book_name = book[0] book_chapters = int(book[1]) book_section = book[2] if book_section", "= \"New Testament\" elif user_choice == \"3\": chosen_b_section = \"Book of Mormon\" elif", "0 largest_book_name = \"\" chosen_b_section = \"\" user_choice = input(\"\"\" What volume of", "= \"\" user_choice = input(\"\"\" What volume of scripture do you want to", "== \"1\": chosen_b_section = \"Old Testament\" elif user_choice == \"2\": chosen_b_section = \"New", "Book of Mormon 4. Doctrine and Covenants 5. Pearl of Great Price \"\"\")", "chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book: largest_book =", "== \"4\": chosen_b_section = \"Doctrine and Covenants\" elif user_choice == \"5\": chosen_b_section =", "Testament 2. New Testament 3. Book of Mormon 4. Doctrine and Covenants 5.", "book[2] if book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters", "largest_book = 0 largest_book_name = \"\" chosen_b_section = \"\" user_choice = input(\"\"\" What", "and Covenants\" elif user_choice == \"5\": chosen_b_section = \"Pearl of Great Price\" for", "book_section == chosen_b_section: print(f\"Scripture: {book_section}, Book: {book_name}, Chapters: {book_chapters}\") if book_chapters > largest_book:", "line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\") book_name =", "as scripture_list: largest_book = 0 largest_book_name = \"\" chosen_b_section = \"\" user_choice =", "and Covenants 5. Pearl of Great Price \"\"\") if user_choice == \"1\": chosen_b_section", "= book[0] book_chapters = int(book[1]) book_section = book[2] if book_section == chosen_b_section: print(f\"Scripture:", "book_name = book[0] book_chapters = int(book[1]) book_section = book[2] if book_section == chosen_b_section:", "with open(\"week 12/books_and_chapters.txt\") as scripture_list: largest_book = 0 largest_book_name = \"\" chosen_b_section =", "for line in scripture_list: #Genesis:50:Old Testament clean_list = line.strip() book = clean_list.split(\":\") book_name", "Testament 3. Book of Mormon 4. Doctrine and Covenants 5. Pearl of Great", "user_choice = input(\"\"\" What volume of scripture do you want to look at?" ]
[ "= result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE)", "{}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None] =", "{} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where is None: where", "handles failure of the command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile()", "= subprocess.run(cmd, cwd = where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result", "executing commands, optionally in the given directory with the reporting global reporting option.", "stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd,", "type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None]", "== REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad", "configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY)", "if not isinstance(cmd, list): raise ValueError(\"cmd must be a list\") # exec_cmd handles", "shows no output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr", "stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd:", "in realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY =", "logger # # This module executes commands, manages output from those commands and", "= arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where:", "stdout # REPORTING_OPTION_NEITHER : shows no output either from stdout or stderr #", "pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and", "False options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False)", "a failure and prints an X for each line # of stdout -", "-> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option))", "is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count =", "TextIO, List, AnyStr import smpl.log_module as logger # # This module executes commands,", "# REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple", "defaults; no dry-run and report everything # configure() should be called before any", "kw-args and have defaults; no dry-run and report everything # configure() should be", "# exec_cmd handles failure of the command exec_cmd(cmd, where) if __name__ == '__main__':", "__name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False,", "stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where)", "result = subprocess.run(cmd, cwd = where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY:", "logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\", \"/home/robert/Projects/smpl\"])", "those commands and provides a dry-run capability. # # The primary function is", "logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\"", "command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"],", "only on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure", "REPORTING_OPTION_NEITHER : shows no output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS :", "os import sys import subprocess from typing import Union, TextIO, List, AnyStr import", "only on a failure and prints an X for each line # of", "result.stderr else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode", "sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return", "result.poll() is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count", "= where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY:", "50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode =", "# # The primary function is # # def run(cmd, where) # #", "except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while", "return code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error", "where is None: where = os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option ==", "0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) % 50", "commands, optionally in the given directory with the reporting global reporting option. On", "{}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running command [{}] error type: {}\\n\".format(\",", "arg_reporting_option) # # both arguments can ge provided as kw-args and have defaults;", "subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if", "= 4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options:", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR", "options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE,", "any calls to run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple", "directory with the reporting global reporting option. On failure of the command it", "failure of the command it quits the program \"\"\" logger.debugln(\" cmd: {} where:", "import os import sys import subprocess from typing import Union, TextIO, List, AnyStr", "running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd:", "result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr", "failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure and does not", "= result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd", "def run(cmd: List[str], where: Union[str, None] = None) -> None: logger.debugln(\" cmd: {}", "show stderr only on a failure and does not show any stdout #", "before any calls to run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR :", "cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\")", "__init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options() def configure(arg_reporting_option", "count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1)", "program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run:", "or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure and prints", "# configure() should be called before any calls to run() # # Output", "= Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option", "code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as", "an X for each line # of stdout - does this in realtime", "stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show any stderr output", "and report everything # configure() should be called before any calls to run()", "stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on", "both arguments can ge provided as kw-args and have defaults; no dry-run and", "REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output =", "everything # configure() should be called before any calls to run() # #", "the hard work of executing commands, optionally in the given directory with the", "\".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd", "cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where", "self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options() def configure(arg_reporting_option =", "stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result =", "0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None:", "{} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd must be a", "None] = None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not", "cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count == 0:", "as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running command", "sys.stderr.write( \"An error occurred while running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__))", "where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count", "return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception", "stderr_output = result.stderr else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode", "REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show any stderr output only on", "can ge provided as kw-args and have defaults; no dry-run and report everything", "options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd,", "error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str,", "(count + 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() #", "# REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure and does not show", "if where is None: where = os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option", "1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\")", "retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd was", "= 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options:", "where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\",", "if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr", "a list\") # exec_cmd handles failure of the command exec_cmd(cmd, where) if __name__", "X for each line # of stdout - does this in realtime while", "REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER", "retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd,", "dry-run and output options are controlled by: # # def configure(arg_dry_run, arg_reporting_option) #", "stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure and prints an", "ValueError(\"cmd must be a list\") # exec_cmd handles failure of the command exec_cmd(cmd,", "list\") # exec_cmd handles failure of the command exec_cmd(cmd, where) if __name__ ==", "REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY", "code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred", "command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str],", "and does not show any stdout # REPORTING_OPTION_NEITHER : shows no output either", "cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option ==", "elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd = where,", "and prints an X for each line # of stdout - does this", "where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where is None:", "dry-run and report everything # configure() should be called before any calls to", "= REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option = arg_reporting_option options.dry_run =", "The primary function is # # def run(cmd, where) # # dry-run and", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline =", "result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "with the reporting global reporting option. On failure of the command it quits", "logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if", "cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if retcode", "failure of the command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False,", "REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run", "{} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where is", "result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output =", "\".join(cmd))) sys.stderr.write( \"An error occurred while running command [{}] error type: {}\\n\".format(\", \".join(cmd),", "options.dry_run)) if options.dry_run: return if where is None: where = os.getcwd() try: stderr_output", "occurred while running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit()", "Union[str, None] = None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if", "shows stderr only on a failure and prints an X for each line", "None: \"\"\" Does the hard work of executing commands, optionally in the given", "work of executing commands, optionally in the given directory with the reporting global", "closed\") retcode = result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd, cwd =", "1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4", "else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output", "where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if retcode > 0:", "error occurred while running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception)))", "are controlled by: # # def configure(arg_dry_run, arg_reporting_option) # # both arguments can", "where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result", "be a list\") # exec_cmd handles failure of the command exec_cmd(cmd, where) if", "in the given directory with the reporting global reporting option. On failure of", "REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False", "of stdout - does this in realtime while the command is executing #", "show any stdout # REPORTING_OPTION_NEITHER : shows no output either from stdout or", "Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr #", "sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None] = None) -> None:", "def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does the hard work of", "configure() should be called before any calls to run() # # Output options", "subprocess.run(cmd, cwd = where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result =", "options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does the hard work", "# sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr else:", "None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list):", "result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output =", "arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"tree\",", "\".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None] = None)", "# REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5", "= where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd", "= result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd),", "optionally in the given directory with the reporting global reporting option. On failure", "stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where,", "while the command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY", "as logger # # This module executes commands, manages output from those commands", "from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure", "False) -> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run,", "typing import Union, TextIO, List, AnyStr import smpl.log_module as logger # # This", "through stdout and show any stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY", "does this in realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR = 1", "realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2", "while result.poll() is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\")", "commands and provides a dry-run capability. # # The primary function is #", "must be a list\") # exec_cmd handles failure of the command exec_cmd(cmd, where)", "None]) -> None: \"\"\" Does the hard work of executing commands, optionally in", "the reporting global reporting option. On failure of the command it quits the", "exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None)", "be called before any calls to run() # # Output options are: #", "# # dry-run and output options are controlled by: # # def configure(arg_dry_run,", "line # of stdout - does this in realtime while the command is", "# # This module executes commands, manages output from those commands and provides", "subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option", "= 0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is", "None: where = os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result", "a dry-run capability. # # The primary function is # # def run(cmd,", "-> None: \"\"\" Does the hard work of executing commands, optionally in the", "# def run(cmd, where) # # dry-run and output options are controlled by:", "are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY :", "given directory with the reporting global reporting option. On failure of the command", "stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show any", "stdout and show any stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY :", "not isinstance(cmd, list): raise ValueError(\"cmd must be a list\") # exec_cmd handles failure", "3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option =", "for each line # of stdout - does this in realtime while the", "class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options =", "options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode", "import smpl.log_module as logger # # This module executes commands, manages output from", "{}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd)))", "# This module executes commands, manages output from those commands and provides a", "None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd", "os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd", "= result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result", "dry-run capability. # # The primary function is # # def run(cmd, where)", "the command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY =", "is None: where = os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR:", "and output options are controlled by: # # def configure(arg_dry_run, arg_reporting_option) # #", "== REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output", "\"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return", "sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running command [{}] error", "REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass", "while running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def", "reporting option. On failure of the command it quits the program \"\"\" logger.debugln(\"", "function is # # def run(cmd, where) # # dry-run and output options", "sys import subprocess from typing import Union, TextIO, List, AnyStr import smpl.log_module as", ": shows no output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows", "Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option =", "stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\",", "called before any calls to run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR", ": show stderr only on a failure and does not show any stdout", "# print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd,", "try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd =", "configure(arg_dry_run, arg_reporting_option) # # both arguments can ge provided as kw-args and have", "\\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None] = None) -> None: logger.debugln(\"", "command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3", "logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd must", "provided as kw-args and have defaults; no dry-run and report everything # configure()", "where)) if not isinstance(cmd, list): raise ValueError(\"cmd must be a list\") # exec_cmd", "quits the program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run))", "= 5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run", "on a failure and does not show any stdout # REPORTING_OPTION_NEITHER : shows", "% 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode", "provides a dry-run capability. # # The primary function is # # def", "REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output =", "manages output from those commands and provides a dry-run capability. # # The", "= result.returncode stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return", "stderr=subprocess.PIPE) while result.poll() is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline()", "REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class", "cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option ==", "run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"tree\", \"/xhome/robert/Projects/smpl\"])", "elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode =", "= (count + 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close()", "output options are controlled by: # # def configure(arg_dry_run, arg_reporting_option) # # both", "result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr else: result =", "options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None])", "any stdout # REPORTING_OPTION_NEITHER : shows no output either from stdout or stderr", "this in realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY", "{}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as exception:", "configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option = arg_reporting_option options.dry_run", "# both arguments can ge provided as kw-args and have defaults; no dry-run", "subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count ==", "where: Union[str, None]) -> None: \"\"\" Does the hard work of executing commands,", "REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self):", "where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd must be a list\")", "= subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count", "= result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) % 50 flush = result.stdout.read()", "a failure and does not show any stdout # REPORTING_OPTION_NEITHER : shows no", "elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode =", "and provides a dry-run capability. # # The primary function is # #", "\"\"\" Does the hard work of executing commands, optionally in the given directory", "the program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if", "stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count =", "retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where,", "= False) -> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting:", "result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd =", "# REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure and prints an X", "result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode))", "is executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS", "only on a failure and does not show any stdout # REPORTING_OPTION_NEITHER :", "command it quits the program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd),", "import Union, TextIO, List, AnyStr import smpl.log_module as logger # # This module", "and show any stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY : show", "2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options: def", "simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout", "if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode = result.returncode", "= os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd,", "= False options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool =", "where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd =", "sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr else: result", "run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout", "5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run =", "not show any stdout # REPORTING_OPTION_NEITHER : shows no output either from stdout", "subprocess from typing import Union, TextIO, List, AnyStr import smpl.log_module as logger #", "= result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE,", "of executing commands, optionally in the given directory with the reporting global reporting", "Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running", "global reporting option. On failure of the command it quits the program \"\"\"", "# The primary function is # # def run(cmd, where) # # dry-run", "cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd must be", "output from those commands and provides a dry-run capability. # # The primary", "smpl.log_module as logger # # This module executes commands, manages output from those", "== REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output", "and have defaults; no dry-run and report everything # configure() should be called", "arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str,", "On failure of the command it quits the program \"\"\" logger.debugln(\" cmd: {}", "and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show any stderr", "sys.stdout.write(\"X\") count = (count + 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") #", "does not show any stdout # REPORTING_OPTION_NEITHER : shows no output either from", "= where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count == 0: sys.stdout.write(\"\\n\")", "result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if", "{}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise ValueError(\"cmd must be a list\") #", "calls to run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass", "return if where is None: where = os.getcwd() try: stderr_output = \"unassigned\" if", "result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr", "isinstance(cmd, list): raise ValueError(\"cmd must be a list\") # exec_cmd handles failure of", "ge provided as kw-args and have defaults; no dry-run and report everything #", "a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure and does", "= result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd", "+ 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout", "was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running command [{}] error type:", "= where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS:", "sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) % 50 flush", "from typing import Union, TextIO, List, AnyStr import smpl.log_module as logger # #", "# dry-run and output options are controlled by: # # def configure(arg_dry_run, arg_reporting_option)", "executes commands, manages output from those commands and provides a dry-run capability. #", "> 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise", "print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd, cwd", "exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does the hard work of executing", "# # both arguments can ge provided as kw-args and have defaults; no", "stderr only on a failure and does not show any stdout # REPORTING_OPTION_NEITHER", "dry_run: {}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where is None: where =", "of the command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY)", "options are controlled by: # # def configure(arg_dry_run, arg_reporting_option) # # both arguments", "if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"])", "subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif options.reporting_option", "= where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr if retcode >", "have defaults; no dry-run and report everything # configure() should be called before", "# # def run(cmd, where) # # dry-run and output options are controlled", "retcode = result.returncode stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {}", "def configure(arg_dry_run, arg_reporting_option) # # both arguments can ge provided as kw-args and", "it quits the program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run: {}\".format(\",\".join(cmd), where,", "where = os.getcwd() try: stderr_output = \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result =", "output only on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on a", "controlled by: # # def configure(arg_dry_run, arg_reporting_option) # # both arguments can ge", "stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure and", "= subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif", "exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An error occurred while running command [{}]", "type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where: Union[str, None] = None) ->", "Union, TextIO, List, AnyStr import smpl.log_module as logger # # This module executes", "Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None:", "= subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr elif", "no dry-run and report everything # configure() should be called before any calls", "result.returncode stderr_output = result.stderr if retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code", "result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result =", "# def configure(arg_dry_run, arg_reporting_option) # # both arguments can ge provided as kw-args", "result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd, cwd = where, stderr=subprocess.PIPE) retcode", "is # # def run(cmd, where) # # dry-run and output options are", "as kw-args and have defaults; no dry-run and report everything # configure() should", "options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode = result.returncode", "output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on", "where) # # dry-run and output options are controlled by: # # def", "commands, manages output from those commands and provides a dry-run capability. # #", "pass through stdout and show any stderr output only on a failure #", "hard work of executing commands, optionally in the given directory with the reporting", "retcode = result.returncode stderr_output = result.stderr else: result = subprocess.run(cmd, cwd = where,", "import subprocess from typing import Union, TextIO, List, AnyStr import smpl.log_module as logger", "Union[str, None]) -> None: \"\"\" Does the hard work of executing commands, optionally", "if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count +", "def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options() def", "cwd = where) retcode = result.returncode elif options.reporting_option == REPORTING_OPT_STDOUT_ONLY: result = subprocess.run(cmd,", "failure and does not show any stdout # REPORTING_OPTION_NEITHER : shows no output", "prints an X for each line # of stdout - does this in", "of the command it quits the program \"\"\" logger.debugln(\" cmd: {} where: {}", "capability. # # The primary function is # # def run(cmd, where) #", "where: Union[str, None] = None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where))", "= result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output", "failure and prints an X for each line # of stdout - does", "reporting global reporting option. On failure of the command it quits the program", "no output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only", "'__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\",", "report everything # configure() should be called before any calls to run() #", "quit() def run(cmd: List[str], where: Union[str, None] = None) -> None: logger.debugln(\" cmd:", "each line # of stdout - does this in realtime while the command", "= REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR,", "stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) % 50 flush =", "= result.stderr else: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode =", "REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode = result.returncode elif options.reporting_option ==", "the command it quits the program \"\"\" logger.debugln(\" cmd: {} where: {} dry_run:", "bool = False) -> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {}", "simple pass through stdout and show any stderr output only on a failure", "module executes commands, manages output from those commands and provides a dry-run capability.", "# # def configure(arg_dry_run, arg_reporting_option) # # both arguments can ge provided as", "count = 0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll()", "to run() # # Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through", "raise ValueError(\"cmd must be a list\") # exec_cmd handles failure of the command", "arg_dry_run: bool = False) -> None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run:", "== '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS)", "{}\".format(\",\".join(cmd), where, options.dry_run)) if options.dry_run: return if where is None: where = os.getcwd()", "4 class Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options", "= arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) ->", "List, AnyStr import smpl.log_module as logger # # This module executes commands, manages", "# of stdout - does this in realtime while the command is executing", "REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run:", "# REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show any stderr output only", "# REPORTING_OPTION_NEITHER : shows no output either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS", "def run(cmd, where) # # dry-run and output options are controlled by: #", "the command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN) logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\",", "def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) -> None: options.reporting_option = arg_reporting_option", "retcode = result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0", "RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write( \"An", "AnyStr import smpl.log_module as logger # # This module executes commands, manages output", "- does this in realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR =", "reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does the", "either from stdout or stderr # REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a", "# # Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and", "retcode > 0: sys.stderr.write(\"ERROR cmd: {} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output))", "Options: def __init__(self): self.reporting_option = REPORTING_OPT_STDOUT_ONLY self.dry_run = False options: Options = Options()", "{} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does", "result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE) retcode", "REPORTING_OPT_STDERR_STDOUT_PROGRESS: count = 0 result = subprocess.Popen(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while", "run(cmd, where) # # dry-run and output options are controlled by: # #", "= result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE)", "logger.set_stdout_logfile() configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDOUT_ONLY) run([\"wget\", \"http://whiteacorn.com\"], None) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False, arg_reporting_option=REPORTING_OPT_STDERR_STDOUT_PROGRESS) run([\"tree\", \"/home/robert/Projects/smpl\"]) configure(arg_dry_run=False,", "from those commands and provides a dry-run capability. # # The primary function", "show any stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr", "\"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode =", "raise RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\", \".join(cmd))) sys.stderr.write(", "= 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER =", "options.dry_run: return if where is None: where = os.getcwd() try: stderr_output = \"unassigned\"", "List[str], where: Union[str, None] = None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd),", "sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode stderr_output = result.stderr", "result.returncode stderr_output = result.stderr elif options.reporting_option == REPORTING_OPT_STDERR_ONLY: result = subprocess.run(cmd, cwd =", "This module executes commands, manages output from those commands and provides a dry-run", "= \"unassigned\" if options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode", "should be called before any calls to run() # # Output options are:", "-> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd, list): raise", "\"An error occurred while running command [{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details:", "option. On failure of the command it quits the program \"\"\" logger.debugln(\" cmd:", "run(cmd: List[str], where: Union[str, None] = None) -> None: logger.debugln(\" cmd: {} where:", "Does the hard work of executing commands, optionally in the given directory with", "by: # # def configure(arg_dry_run, arg_reporting_option) # # both arguments can ge provided", "import sys import subprocess from typing import Union, TextIO, List, AnyStr import smpl.log_module", "where, options.dry_run)) if options.dry_run: return if where is None: where = os.getcwd() try:", "exec_cmd handles failure of the command exec_cmd(cmd, where) if __name__ == '__main__': logger.init(logger.LOG_LEVEL_WARN)", "options.reporting_option == REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode = result.returncode elif", ": shows stderr only on a failure and prints an X for each", "on a failure and prints an X for each line # of stdout", "if options.dry_run: return if where is None: where = os.getcwd() try: stderr_output =", "where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while result.poll() is None: if count == 0: sys.stdout.write(\"\\n\") stdoutline", "== 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) %", "= subprocess.run(cmd, cwd = where, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = result.returncode stderr_output = result.stderr", "list): raise ValueError(\"cmd must be a list\") # exec_cmd handles failure of the", "None: if count == 0: sys.stdout.write(\"\\n\") stdoutline = result.stdout.readline() sys.stdout.write(\"X\") count = (count", "count = (count + 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\")", "self.dry_run = False options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool", "None: options.reporting_option = arg_reporting_option options.dry_run = arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def", "[{}] error type: {}\\n\".format(\", \".join(cmd), type(exception).__name__)) sys.stderr.write(\"Details: \\n{}\\n\".format(str(exception))) quit() def run(cmd: List[str], where:", "flush = result.stdout.read() sys.stdout.write(\"YY\\n\") # sys.stdout.write(\"\\n\") result.stdout.close() # print(\"result.stdout closed\") retcode = result.returncode", "sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except Exception as exception: sys.stderr.write(\"Cmd was {}\\n\".format(\",", "stderr only on a failure and prints an X for each line #", "arguments can ge provided as kw-args and have defaults; no dry-run and report", "primary function is # # def run(cmd, where) # # dry-run and output", "= None) -> None: logger.debugln(\" cmd: {} where: {}\".format(\",\".join(cmd), where)) if not isinstance(cmd,", "executing # REPORTING_OPT_STDOUT_STDERR = 1 REPORTING_OPT_STDOUT_ONLY = 2 REPORTING_OPT_STDERR_ONLY = 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS =", "the given directory with the reporting global reporting option. On failure of the", "through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through stdout and show", "options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY", "arg_dry_run logger.debugln(\"dry_run: {} reporting: {}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None:", "REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure and does not show any", "any stderr output only on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only", "stdout - does this in realtime while the command is executing # REPORTING_OPT_STDOUT_STDERR", "options: Options = Options() def configure(arg_reporting_option = REPORTING_OPT_STDOUT_STDERR, arg_dry_run: bool = False) ->", ": simple pass through stdout and show any stderr output only on a", "= 3 REPORTING_OPT_STDERR_STDOUT_PROGRESS = 5 REPORTING_OPT_NEITHER = 4 class Options: def __init__(self): self.reporting_option", "REPORTING_OPTION_STDERR_STDOUT_PROGRESS : shows stderr only on a failure and prints an X for", "# Output options are: # REPORTING_OPTION_STDOUT_STDERR : simple pass through stdout and stderr", "{} return code {}\\n\".format(\", \".join(cmd), retcode)) sys.stderr.write(\"stderr {}\\n\".format(stderr_output)) raise RuntimeError(\"bad return code\") except", ": simple pass through stdout and stderr # REPORTING_OPTION_STDOUT_ONLY : simple pass through", "== REPORTING_OPT_STDOUT_STDERR: result = subprocess.run(cmd, cwd = where) retcode = result.returncode elif options.reporting_option", "result.stdout.readline() sys.stdout.write(\"X\") count = (count + 1) % 50 flush = result.stdout.read() sys.stdout.write(\"YY\\n\")", "on a failure # REPORTING_OPTION_STDERR_ONLY : show stderr only on a failure and", "{}\".format(options.dry_run, options.reporting_option)) def exec_cmd(cmd, where: Union[str, None]) -> None: \"\"\" Does the hard" ]
[ "block = True, quiet = True): def run_server(): return bottle.run( port = port,", "app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route(", "def run_server(): return bottle.run( port = port, quiet = quiet, host = \"0.0.0.0\",", "connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import bottle def start(port", "_javascript_call from bottle.ext import websocket as bottle_websocket import bottle def start(port = 4949,", "port = port, quiet = quiet, host = \"0.0.0.0\", app = bottle.default_app(), server", "= True): def run_server(): return bottle.run( port = port, quiet = quiet, host", "quiet, host = \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block:", "import connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import bottle def", "run_server(): return bottle.run( port = port, quiet = quiet, host = \"0.0.0.0\", app", "= 4949, block = True, quiet = True): def run_server(): return bottle.run( port", "if block: run_server() else: spawn(run_server) bottle.route( path = '/', callback = connect_websocket, apply", "quiet = quiet, host = \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, )", "bottle def start(port = 4949, block = True, quiet = True): def run_server():", "def start(port = 4949, block = True, quiet = True): def run_server(): return", "\"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server)", "<reponame>JDaniloC/Electronpy from .handler import connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket", "True, quiet = True): def run_server(): return bottle.run( port = port, quiet =", "= port, quiet = quiet, host = \"0.0.0.0\", app = bottle.default_app(), server =", "quiet = True): def run_server(): return bottle.run( port = port, quiet = quiet,", "port, quiet = quiet, host = \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer,", "bottle.ext import websocket as bottle_websocket import bottle def start(port = 4949, block =", "run_server() else: spawn(run_server) bottle.route( path = '/', callback = connect_websocket, apply = (bottle_websocket.websocket,))", "= quiet, host = \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if", "from .handler import connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import", "as bottle_websocket import bottle def start(port = 4949, block = True, quiet =", "websocket as bottle_websocket import bottle def start(port = 4949, block = True, quiet", "= \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else:", ".handler import connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import bottle", "bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route( path =", "import websocket as bottle_websocket import bottle def start(port = 4949, block = True,", "bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route( path = '/', callback =", ") if block: run_server() else: spawn(run_server) bottle.route( path = '/', callback = connect_websocket,", "= bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route( path", "bottle_websocket import bottle def start(port = 4949, block = True, quiet = True):", "True): def run_server(): return bottle.run( port = port, quiet = quiet, host =", "import bottle def start(port = 4949, block = True, quiet = True): def", "return bottle.run( port = port, quiet = quiet, host = \"0.0.0.0\", app =", "from bottle.ext import websocket as bottle_websocket import bottle def start(port = 4949, block", "bottle.run( port = port, quiet = quiet, host = \"0.0.0.0\", app = bottle.default_app(),", "server = bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route( path = '/',", "= True, quiet = True): def run_server(): return bottle.run( port = port, quiet", "start(port = 4949, block = True, quiet = True): def run_server(): return bottle.run(", "4949, block = True, quiet = True): def run_server(): return bottle.run( port =", "host = \"0.0.0.0\", app = bottle.default_app(), server = bottle_websocket.GeventWebSocketServer, ) if block: run_server()", "spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import bottle def start(port =", "block: run_server() else: spawn(run_server) bottle.route( path = '/', callback = connect_websocket, apply =", "= bottle_websocket.GeventWebSocketServer, ) if block: run_server() else: spawn(run_server) bottle.route( path = '/', callback" ]
[ "c in api_name if c.isalpha() or c.isdigit() or c in (\".\", \"_\", \"-\")])", "return \"\".join([c for c in api_name if c.isalpha() or c.isdigit() or c in", "logger = logging.getLogger(__name__) def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use in", "file name\"\"\" return \"\".join([c for c in api_name if c.isalpha() or c.isdigit() or", "logging logger = logging.getLogger(__name__) def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use", "def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use in a file name\"\"\"", "= logging.getLogger(__name__) def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use in a", "\"\"\"Make an api name safe for use in a file name\"\"\" return \"\".join([c", "name\"\"\" return \"\".join([c for c in api_name if c.isalpha() or c.isdigit() or c", "in a file name\"\"\" return \"\".join([c for c in api_name if c.isalpha() or", "for use in a file name\"\"\" return \"\".join([c for c in api_name if", "logging.getLogger(__name__) def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use in a file", "for c in api_name if c.isalpha() or c.isdigit() or c in (\".\", \"_\",", "an api name safe for use in a file name\"\"\" return \"\".join([c for", "safe for use in a file name\"\"\" return \"\".join([c for c in api_name", "a file name\"\"\" return \"\".join([c for c in api_name if c.isalpha() or c.isdigit()", "api name safe for use in a file name\"\"\" return \"\".join([c for c", "\"\".join([c for c in api_name if c.isalpha() or c.isdigit() or c in (\".\",", "import logging logger = logging.getLogger(__name__) def make_file_safe_api_name(api_name): \"\"\"Make an api name safe for", "name safe for use in a file name\"\"\" return \"\".join([c for c in", "use in a file name\"\"\" return \"\".join([c for c in api_name if c.isalpha()", "make_file_safe_api_name(api_name): \"\"\"Make an api name safe for use in a file name\"\"\" return" ]
[ "from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser()", "hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete", "as pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser", "except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date plus hours and minutes:", "False def test_date_plus_hhmm(self): # Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g.", "date plus hours, minutes, seconds and a decimal fraction of a second #", "Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010, <NAME> # License:", "return True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self):", "wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException:", "is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_date_plus_hhmm(self):", "parseAll=True) return True except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date plus", "# Author: mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright", "#coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010 #", "hours, minutes, seconds and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g.", "2010, <NAME> # License: GPLv3 import sys import unittest PYTHON3 = sys.version_info[0] >", "self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\"))", "and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30.45+01:00\")) if", "import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self,", "return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self):", "self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value):", "True except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date plus hours and", "True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\"))", "(C) 2010, <NAME> # License: GPLv3 import sys import unittest PYTHON3 = sys.version_info[0]", "# Copyright (C) 2010, <NAME> # License: GPLv3 import sys import unittest PYTHON3", "YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds", "is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_full_clock_values(self):", "try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete", "PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import", "03.11.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 import sys import unittest", "date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self):", "a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30.45+01:00\")) if __name__=='__main__':", "= sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2", "# Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\"))", "#!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created:", "self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return", "python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010", "import unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp", "License: GPLv3 import sys import unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3:", "self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try:", "test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds and a decimal fraction of", "# Created: 03.11.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 import sys", "= _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return", "self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date", "# Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def", "1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds and a", "except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\"))", "if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser", "test clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010, <NAME> # License: GPLv3", "self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser()", "Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def", "(e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds and", "pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import", "try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\"))", "value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\"))", "_build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return", "clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException:", "TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except", "test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser", "sys import unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as", "parseAll=True) return True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def", "--<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010, <NAME>", "# YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours, minutes", "sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as", "plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): #", "PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import", "self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value,", "decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30.45+01:00\")) if __name__=='__main__': unittest.main()", "_build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False", "minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date", "# YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes,", "pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser =", "(e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours, minutes and seconds:", "clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 import", "def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def", "_build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value):", "svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value,", "return True except pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date plus hours", "Complete date plus hours, minutes, seconds and a decimal fraction of a second", "import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True)", "self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\"))", "Created: 03.11.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 import sys import", "self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds and a decimal", "class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True", "mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010,", "else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser", "test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\"))", "> 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp", "svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from", "svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def", "return False def test_date_plus_hhmm(self): # Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD", "self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD", "Author: mozman --<<EMAIL>> # Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright (C)", "TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except", "import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser", "def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\"))", "class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True", "pp.ParseException: return False def test_date_plus_hhmm(self): # Complete date plus hours and minutes: #", "unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else:", "hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date", "# Purpose: test clock_val_parser # Created: 03.11.2010 # Copyright (C) 2010, <NAME> #", "and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus", "= _build_clock_val_parser() def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return", "plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete", "self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\"))", "value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def test_date_plus_hhmm(self): #", "def test_date_plus_hhmmss_frac(self): # Complete date plus hours, minutes, seconds and a decimal fraction", "minutes, seconds and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00)", "def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase):", "from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser = _build_clock_val_parser() def is_valid(self, value): try:", "def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def", "test_date_plus_hhmm(self): # Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\"))", "1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours, minutes and seconds: #", "Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self):", "self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class", "seconds and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30.45+01:00\"))", "test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self,", "as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase): clock_val_parser", "test_date_plus_hhmmss(self): # Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00)", "and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus", "# License: GPLv3 import sys import unittest PYTHON3 = sys.version_info[0] > 2 if", "pp.ParseException: return False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def", "plus hours, minutes, seconds and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD", "date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): #", "seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20:30+01:00\")) def test_date_plus_hhmmss_frac(self): # Complete date plus hours,", "import svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class", "Copyright (C) 2010, <NAME> # License: GPLv3 import sys import unittest PYTHON3 =", "svgwrite.data.pyparsing_py2 as pp from svgwrite.data.svgparser import _build_clock_val_parser from svgwrite.data.svgparser import _build_wall_clock_val_parser class TestClockValParser(unittest.TestCase):", "self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser = _build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True)", "def test_date_plus_hhmmss(self): # Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (e.g.", "GPLv3 import sys import unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import", "False def test_full_clock_values(self): self.assertTrue(self.is_valid(\"02:30:03\")) self.assertTrue(self.is_valid(\"01:00:00\")) self.assertTrue(self.is_valid(\"50:00:10.25\")) def test_partial_clock_values(self): self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\"))", "import sys import unittest PYTHON3 = sys.version_info[0] > 2 if PYTHON3: import svgwrite.data.pyparsing_py3", "2 if PYTHON3: import svgwrite.data.pyparsing_py3 as pp else: import svgwrite.data.pyparsing_py2 as pp from", "# Complete date plus hours, minutes, seconds and a decimal fraction of a", "YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours, minutes and", "def test_date_plus_hhmm(self): # Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00)", "_build_wall_clock_val_parser() def is_valid(self, value): try: self.wallclock_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False", "<NAME> # License: GPLv3 import sys import unittest PYTHON3 = sys.version_info[0] > 2", "def is_valid(self, value): try: self.clock_val_parser.parseString(value, parseAll=True) return True except pp.ParseException: return False def", "self.assertTrue(self.is_valid(\"02:33\")) self.assertTrue(self.is_valid(\"00:10.5\")) def test_time_count_values(self): self.assertTrue(self.is_valid(\"3.2h\")) self.assertTrue(self.is_valid(\"45min\")) self.assertTrue(self.is_valid(\"30s\")) self.assertTrue(self.is_valid(\"5ms\")) self.assertTrue(self.is_valid(\"12.467\")) class TestWallClockValParser(unittest.TestCase): wallclock_parser =", "minutes: # YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) self.assertTrue(self.is_valid(\"1997-07-16T19:20+01:00\")) def test_date_plus_hhmmss(self): # Complete date plus hours," ]
[ "#!/usr/bin/env python import os from app import create_app,db from app.models import User,Role from", "<reponame>zhangmingkai4315/Flask-Web-App #!/usr/bin/env python import os from app import create_app,db from app.models import User,Role", "from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db)", "import os from app import create_app,db from app.models import User,Role from flask.ext.script import", "create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand", "User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app)", "import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default')", "import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db) manager.add_command('db',MigrateCommand) if", "from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db) manager.add_command('db',MigrateCommand) if __name__=='__main__': manager.run()", "from app import create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell from", "os from app import create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell", "import create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import", "python import os from app import create_app,db from app.models import User,Role from flask.ext.script", "app import create_app,db from app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate", "flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db) manager.add_command('db',MigrateCommand)", "from app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG')", "Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db) manager.add_command('db',MigrateCommand) if __name__=='__main__':", "app.models import User,Role from flask.ext.script import Manager,Shell from flask.ext.migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or" ]
[ "copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by", "writing, software # distributed under the License is distributed on an \"AS IS\"", "ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA):", "job name. :param code_path|str: the increment job code path. :param first_time|datetime: it will", "incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta", "# # Licensed under the Private License (the \"License\"); # you may not", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "= IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta))", "first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the incrment extract job", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "path. :param first_time|datetime: it will be converted to utc time to save. :param", "IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get() if incrextr is None:", "datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr", "Update last extract time :param ie_nme|str: the extractor name :param last_extr_time|datetime: the last", "language governing permissions and # limitations under the License. import datetime from ssguan.ignitor.base", "License. # You may obtain a copy of the License at # #", "to compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all()", "the last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr =", "import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility", "parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract", ":param ie_name|str: the incrment extract job name. :param code_path|str: the increment job code", "first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr =", "float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time = (kind.utcnow()", "start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else", "law or agreed to in writing, software # distributed under the License is", "https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law or agreed to in writing,", "the incrment extract job name. :param code_path|str: the increment job code path. :param", "the License for the specific language governing permissions and # limitations under the", "code path. :param first_time|datetime: it will be converted to utc time to save.", ":return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try:", "incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time,", "License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law or", "compliance with the License. # You may obtain a copy of the License", "incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time =", "extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\",", "None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else", "= incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time", "first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time", "the License. import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from", "name. :param code_path|str: the increment job code path. :param first_time|datetime: it will be", "of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable", "# Copyright 2015 www.suishouguan.com # # Licensed under the Private License (the \"License\");", "import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import", "Get extract timespan. :param ie_name|str: the incrment extract job name. :param code_path|str: the", "code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the incrment extract", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "the specific language governing permissions and # limitations under the License. import datetime", "timespan. :param ie_name|str: the incrment extract job name. :param code_path|str: the increment job", "this file except in compliance with the License. # You may obtain a", "raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time set\", last_extr_time) query.update(context.get_user_id())", "the increment job code path. :param first_time|datetime: it will be converted to utc", "last extract time :param ie_nme|str: the extractor name :param last_extr_time|datetime: the last extract", "you may not use this file except in compliance with the License. #", "for the specific language governing permissions and # limitations under the License. import", "delta to compute extract start time. :param end_delta|float: the delta to compute extract", "__lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param ie_nme|str: the extractor", "(start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get()", "time. :param end_delta|float: the delta to compute extract end time. :return tuple(datetime,datetime): return", "start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the incrment extract job name.", "ie_name) __lock.acquire() try: incrextr = query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA", "= query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name,", "incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time =", "You may obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE #", "# # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law or agreed to", "(kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time = kind.local_to_utc(first_time) first_time", "kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path,", "= incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return", "ANY KIND, either express or implied. # See the License for the specific", "=\", ie_name) __lock.acquire() try: incrextr = query.get() if incrextr is None: start_delta =", "License. import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model", "datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time)", "extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if", "end_delta is None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is", "be converted to utc time to save. :param start_delta|float: the delta to compute", "in compliance with the License. # You may obtain a copy of the", "-*- coding: utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under the", "kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", ":param end_delta|float: the delta to compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time)", "use this file except in compliance with the License. # You may obtain", "try: incrextr = query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta", "= kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time)", "end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name)", "incrextr = query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is", "code_path|str: the increment job code path. :param first_time|datetime: it will be converted to", "not use this file except in compliance with the License. # You may", "time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire()", "it will be converted to utc time to save. :param start_delta|float: the delta", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "- datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time)", "Copyright 2015 www.suishouguan.com # # Licensed under the Private License (the \"License\"); #", "NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time set\", last_extr_time) query.update(context.get_user_id()) return", "(start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param", "# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law or agreed to in", "query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get() if incrextr", "See the License for the specific language governing permissions and # limitations under", "last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get()", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time)", "def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the", "\"\"\" Update last extract time :param ie_nme|str: the extractor name :param last_extr_time|datetime: the", "= (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time = kind.local_to_utc(first_time)", "ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required", "governing permissions and # limitations under the License. import datetime from ssguan.ignitor.base import", "IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if", "is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta)", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is", "if start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None", "query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get() if incrextr is None: start_delta", "# -*- coding: utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under", "at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law or agreed", "2015 www.suishouguan.com # # Licensed under the Private License (the \"License\"); # you", "OF ANY KIND, either express or implied. # See the License for the", "= query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None", "first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time =", "last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() -", "def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param ie_nme|str: the extractor name", "parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str:", "= kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last", "delta to compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query =", "IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time -", "# you may not use this file except in compliance with the License.", "the delta to compute extract start time. :param end_delta|float: the delta to compute", "IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None,", "is None else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time", "agreed to in writing, software # distributed under the License is distributed on", "__lock.acquire() try: incrextr = query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if", "last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time,", "Private License (the \"License\"); # you may not use this file except in", "increment job code path. :param first_time|datetime: it will be converted to utc time", "datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract,", "return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr =", "last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr =", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else first_time", "- datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time)", "if first_time is None else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time", "time :param ie_nme|str: the extractor name :param last_extr_time|datetime: the last extract time \"\"\"", "- datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time = kind.local_to_utc(first_time) first_time =", "the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required by applicable law", "(the \"License\"); # you may not use this file except in compliance with", "may obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # #", "save. :param start_delta|float: the delta to compute extract start time. :param end_delta|float: the", "IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr is None: raise NoFoundError('Extractor',", "time to save. :param start_delta|float: the delta to compute extract start time. :param", "- datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time):", "www.suishouguan.com # # Licensed under the Private License (the \"License\"); # you may", "# # Unless required by applicable law or agreed to in writing, software", "import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name,", "kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get", "Licensed under the Private License (the \"License\"); # you may not use this", "ie_name|str: the incrment extract job name. :param code_path|str: the increment job code path.", "import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock", "start_delta|float: the delta to compute extract start time. :param end_delta|float: the delta to", "extractor name :param last_extr_time|datetime: the last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name", "express or implied. # See the License for the specific language governing permissions", "code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta)", "# Unless required by applicable law or agreed to in writing, software #", "except in compliance with the License. # You may obtain a copy of", "from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog", "by applicable law or agreed to in writing, software # distributed under the", "incrment extract job name. :param code_path|str: the increment job code path. :param first_time|datetime:", "\"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr is", ":param last_extr_time|datetime: the last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name)", "start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if", "extract time :param ie_nme|str: the extractor name :param last_extr_time|datetime: the last extract time", "last_extr_time|datetime: the last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr", "specific language governing permissions and # limitations under the License. import datetime from", "last_extr_time): \"\"\" Update last extract time :param ie_nme|str: the extractor name :param last_extr_time|datetime:", "__lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan.", "None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA", "either express or implied. # See the License for the specific language governing", "tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr", "first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time =", "import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\"", ":param start_delta|float: the delta to compute extract start time. :param end_delta|float: the delta", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "ie_name) incrextr = query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name) log =", "return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time", "datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally:", "kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name,", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "if end_delta is None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time", "end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update", "to compute extract start time. :param end_delta|float: the delta to compute extract end", "extract start time. :param end_delta|float: the delta to compute extract end time. :return", "start time. :param end_delta|float: the delta to compute extract end time. :return tuple(datetime,datetime):", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "job code path. :param first_time|datetime: it will be converted to utc time to", "compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query = IncrExtract.all() query.filter(\"ie_name", "end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param ie_nme|str:", "the extractor name :param last_extr_time|datetime: the last extract time \"\"\" query = IncrExtract.all()", "ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time set\", last_extr_time) query.update(context.get_user_id()) return True", "= IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time", "will be converted to utc time to save. :param start_delta|float: the delta to", "file except in compliance with the License. # You may obtain a copy", "\"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get() if", "the Private License (the \"License\"); # you may not use this file except", "= parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param", "incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta)", "kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time", "permissions and # limitations under the License. import datetime from ssguan.ignitor.base import context", "update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param ie_nme|str: the extractor name :param", ":param ie_nme|str: the extractor name :param last_extr_time|datetime: the last extract time \"\"\" query", "if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta)", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "first_time|datetime: it will be converted to utc time to save. :param start_delta|float: the", "to utc time to save. :param start_delta|float: the delta to compute extract start", "converted to utc time to save. :param start_delta|float: the delta to compute extract", "end_delta|float: the delta to compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\"", "License for the specific language governing permissions and # limitations under the License.", "under the License. import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError", "extract timespan. :param ie_name|str: the incrment extract job name. :param code_path|str: the increment", "from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock()", "ssguan.ignitor.base import context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from", "name :param last_extr_time|datetime: the last extract time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\",", "the License. # You may obtain a copy of the License at #", "= first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta,", "= kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id())", "to in writing, software # distributed under the License is distributed on an", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr is None:", "else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta)", "License (the \"License\"); # you may not use this file except in compliance", "is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta =", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "if incrextr is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id())", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "= IncrExtract.all() query.filter(\"ie_name =\", ie_name) __lock.acquire() try: incrextr = query.get() if incrextr is", "else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time =", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "to save. :param start_delta|float: the delta to compute extract start time. :param end_delta|float:", "incrextr is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time", "required by applicable law or agreed to in writing, software # distributed under", "query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time)", "datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\"", ":param code_path|str: the increment job code path. :param first_time|datetime: it will be converted", "time \"\"\" query = IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr", "applicable law or agreed to in writing, software # distributed under the License", "from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA,", "= IncrExtract.all() query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr is None: raise", "finally: __lock.release() def update_last_extr_time(ie_name, last_extr_time): \"\"\" Update last extract time :param ie_nme|str: the", "coding: utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under the Private", "from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind,", "extract job name. :param code_path|str: the increment job code path. :param first_time|datetime: it", "obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless", "get_extract_timespan(ie_name, code_path, first_time=None, start_delta=IncrExtract.DEFAULT_START_DELTA, end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the incrment", "# Licensed under the Private License (the \"License\"); # you may not use", "None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time set\", last_extr_time)", "# limitations under the License. import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error", "# You may obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE", "IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def get_extract_timespan(ie_name, code_path,", "NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock =", "query.get() if incrextr is None: start_delta = IncrExtract.DEFAULT_START_DELTA if start_delta is None else", "-*- # Copyright 2015 www.suishouguan.com # # Licensed under the Private License (the", "under the Private License (the \"License\"); # you may not use this file", "or agreed to in writing, software # distributed under the License is distributed", "end_delta=IncrExtract.DEFAULT_END_DELTA): \"\"\" Get extract timespan. :param ie_name|str: the incrment extract job name. :param", "end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time = (kind.utcnow() -", "float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None else first_time first_time", "or implied. # See the License for the specific language governing permissions and", "limitations under the License. import datetime from ssguan.ignitor.base import context from ssguan.ignitor.base.error import", "is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(), ie_name=ie_name, extr_time=last_extr_time) log.create(context.get_user_id()) query.set(\"last_time set\",", ":param first_time|datetime: it will be converted to utc time to save. :param start_delta|float:", "\"\"\" Get extract timespan. :param ie_name|str: the incrment extract job name. :param code_path|str:", "utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under the Private License", "the delta to compute extract end time. :return tuple(datetime,datetime): return (start_time,end_time) \"\"\" query", "first_time is None else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time =", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "= IncrExtract.DEFAULT_START_DELTA if start_delta is None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta", "None else first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time -", "compute extract start time. :param end_delta|float: the delta to compute extract end time.", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import kind, parallel __lock = parallel.create_lock() def", "context from ssguan.ignitor.base.error import NoFoundError from ssguan.ignitor.etl.model import IncrExtract, IncrExtractLog from ssguan.ignitor.utility import", "= kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name,", "end_time = kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release()", "kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr", "incrextr = query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name) log = IncrExtractLog(ie_id=incrextr.key(),", "with the License. # You may obtain a copy of the License at", "None else float(start_delta) end_delta = IncrExtract.DEFAULT_END_DELTA if end_delta is None else float(end_delta) first_time", "first_time - datetime.timedelta(seconds=start_delta) last_time = kind.datetime_floor(first_time) incrextr = IncrExtract(ie_name=ie_name, code_path=code_path, first_time=first_time, start_delta=start_delta, end_delta=end_delta,", "end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time = kind.utcnow()", "= kind.utcnow() - datetime.timedelta(seconds=incrextr.end_delta) end_time = kind.datetime_floor(end_time) return (start_time, end_time) finally: __lock.release() def", "in writing, software # distributed under the License is distributed on an \"AS", "and # limitations under the License. import datetime from ssguan.ignitor.base import context from", "first_time first_time = kind.local_to_utc(first_time) first_time = kind.datetime_floor(first_time) last_time = first_time - datetime.timedelta(seconds=start_delta) last_time", "start_delta=start_delta, end_delta=end_delta, last_time=last_time) incrextr = incrextr.create(context.get_user_id()) start_time = incrextr.last_time - datetime.timedelta(seconds=incrextr.start_delta) end_time =", "ie_nme|str: the extractor name :param last_extr_time|datetime: the last extract time \"\"\" query =", "utc time to save. :param start_delta|float: the delta to compute extract start time.", "=\", ie_name) incrextr = query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name) log", "is None else float(end_delta) first_time = (kind.utcnow() - datetime.timedelta(seconds=end_delta)) if first_time is None", "query.filter(\"ie_name =\", ie_name) incrextr = query.get() if incrextr is None: raise NoFoundError('Extractor', ie_name)" ]
[ "response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token await", "= client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at", "client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token access_token =", "new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient):", "client.sign_in(email=email) assert response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio", "assert response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__])", "@pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await client.init_recover()", "await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code == 400 assert", ") as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with", "assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert", "from gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\")", "isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert", "assert new_client.current_session.access_token == access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\"", "\"all can't be None.\" ) try: await client.sign_in() assert False except ValueError as", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = (", "\"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError", "test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User) assert response.id", "e: assert e.code == 400 assert e.msg == \"No access_token detected.\" dummy_url +=", "= await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session() assert isinstance(response, Session)", "must be defined, both can't be None.\" try: await client.sign_up(password=password) assert False except", "@pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\":", "@pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email,", "as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response =", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response =", "response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) )", "or provider must be defined, \" \"all can't be None.\" ) try: await", ") async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await", "e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False", "\"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception", "as e: assert e.code == 400 assert e.msg == \"No expires_in detected.\" dummy_url", "client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e: assert str(e) ==", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try:", "False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must", "response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e:", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response", "await client.init_recover() response = client.user() assert not response except Exception as e: assert", "+ f\"?error_description={error_description}\" ) assert False except APIError as e: assert e.code == 400", "assert True except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client:", "client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response,", "isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response =", "async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client fake =", "def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email, password=password, )", "new_client.current_session.access_token == access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__]", "password=password, ) assert isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token )", "as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient(", "await client.init_recover() response = client.user() assert isinstance(response, User) assert response.id assert response.email ==", "assert provider == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__])", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover()", "assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be", "detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e:", "response.user assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at", "e: assert e.code == 400 assert e.msg == \"Invalid expires_in.\" except Exception as", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response", "= await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id assert response.email", "def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client:", "e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or", "= await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert", "client.sign_up(password=password) assert False except ValueError as e: assert str(e) == expected_error_message except Exception", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try:", "store_session=True) assert isinstance(response, Session) except Exception as e: assert False, str(e) @pytest.mark.asyncio async", "== \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except", "assert e.code == 400 assert e.msg == \"Invalid expires_in.\" except Exception as e:", "pytest from faker import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError", "str(e) == expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async", "assert e.msg == \"Invalid expires_in.\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", "\"world\"})) assert False except ValueError as e: assert str(e) == expected_error_message except Exception", "assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token", "async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't be None.\"", "async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await client.init_recover() await", "assert response.user assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert", "AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User) assert response.id assert", "APIError as e: assert e.code == 400 assert e.msg == \"No access_token detected.\"", "\"world\"}) ) assert isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at", "async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await", "False except APIError: assert True except Exception as e: assert False, str(e) @pytest.mark.asyncio", "expected_error_message = \"Password must be defined, can't be None.\" try: await client.sign_up(email=email) assert", "try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User)", "isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session)", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert", "response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception as", "assert isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at", "dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await", "email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token", "APIError as e: assert e.code == 400 assert e.msg == \"No expires_in detected.\"", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await", "as e: assert e.code == 400 assert e.msg == \"No token_type detected.\" dummy_url", "test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert isinstance(response, Session) assert response.access_token", "def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User) assert", "def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't be None.\" try:", "response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as", "False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description =", "as e: assert expected_error_message in e.msg except Exception as e: assert False, str(e)", "assert isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2,", "@pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response,", "password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert", "e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must", "@pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email() try:", "global access_token access_token = response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at", "= await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert False", "assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url", "def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\":", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await", "client.refresh_session() assert False except ValueError as e: assert str(e) == \"Not logged in.\"", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already", "be None.\" try: await client.sign_up(email=email) assert False except ValueError as e: assert str(e)", "email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\")", "= f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str]", "assert str(e) == \"Not logged in.\" except Exception as e: assert False, str(e)", "response.id assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at", "\"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert", "assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") ==", "def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client:", ") as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with", "assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response =", "isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email,", "= client.session() assert response is None except Exception as e: assert False, str(e)", "async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session", "assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone", "@pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, )", "client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at", "def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert not response except", "Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except Exception as e:", "client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert", "await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session() assert isinstance(response, Session) await", "assert isinstance(response, Session) except Exception as e: assert False, str(e) @pytest.mark.asyncio async def", "== \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def", "test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token", "dummy_url = \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" )", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try:", "Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id", "from gotrue.exceptions import APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\"", "\"Password must be defined, can't be None.\" try: await client.sign_up(email=email) assert False except", "dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert", "isinstance(response, Session) global access_token access_token = response.access_token assert response.access_token assert response.refresh_token assert response.expires_in", "await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert", "e.code == 400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False except", "assert isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response", "dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert", "AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url +", "async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\"", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response", "auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]:", "response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except", "must be defined, \" \"all can't be None.\" ) try: await client.sign_in() assert", "APIError as e: assert e.code == 400 assert e.msg == error_description try: await", "Session) response = await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session()", "assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except", "response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False,", "await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError as e: assert", "== 400 assert e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert", "\"Invalid expires_in.\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def", "== email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider", "assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert", "assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response", "set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None", "response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\"", "response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async", "client.init_recover() response = client.user() assert isinstance(response, User) assert response.id assert response.email == email", "e: assert e.code == 400 assert e.msg == \"No expires_in detected.\" dummy_url +=", "client.sign_out() try: await client.refresh_session() assert False except ValueError as e: assert str(e) ==", "assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async", "def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert isinstance(response, Session) assert", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ):", "Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import Session,", "client.init_recover() response = client.user() assert not response except Exception as e: assert False,", "access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as", "response = client.user() assert isinstance(response, User) assert response.id assert response.email == email assert", "e.code == 400 assert e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try:", "GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message =", "response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session() assert", "e.code == 400 assert e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try:", "-> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client", "create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield", "new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e:", "or phone must be defined, both can't be None.\" try: await client.sign_up(password=password) assert", "e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response", "isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await", "except APIError as e: assert e.code == 400 assert e.msg == error_description try:", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email,", "assert e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert", "response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception", "response = await client.sign_in(email=email) assert response is None except Exception as e: assert", "Session) await client.sign_out() try: await client.refresh_session() assert False except ValueError as e: assert", "AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token", "try: await client.sign_up(email=email) assert False except ValueError as e: assert str(e) == expected_error_message", "import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def", "client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\"", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message =", "client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception as e: assert False,", "test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert", "response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient):", "@pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, )", "def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response = client.session() assert response", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url", "response = client.user() assert not response except Exception as e: assert False, str(e)", "create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client:", "@pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert False", "e: assert str(e) == \"Not logged in.\" except Exception as e: assert False,", "= await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in", "email=email, password=password, ) assert False except APIError as e: assert expected_error_message in e.msg", "assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as", "\"Email, phone, refresh_token, or provider must be defined, \" \"all can't be None.\"", "except ValueError as e: assert str(e) == \"Not logged in.\" except Exception as", "AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL =", "isinstance(response, Session) response = await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await", "= client.user() assert isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at", "token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as", "email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token:", "access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response = await", "new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e: assert False,", "def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\"", "password=password, ) assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"}", "be None.\" ) try: await client.sign_in() assert False except ValueError as e: assert", "400 assert e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url)", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token", "response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", ") assert isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert", "import AsyncIterable, Optional import pytest from faker import Faker from gotrue import AsyncGoTrueClient", "AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client fake = Faker() email", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient):", "e.code == 400 assert e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try:", "client.user() assert not response except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__])", "= \"Password must be defined, can't be None.\" try: await client.sign_up(email=email) assert False", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user()", "assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__])", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client:", "@pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response = client.session()", "try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e: assert", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient,", "phone must be defined, both can't be None.\" try: await client.sign_up(password=password) assert False", "e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\"", "e: assert e.code == 400 assert e.msg == \"No refresh_token detected.\" dummy_url +=", "refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at", "try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError as e:", "dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert", "{\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except", "@pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must be defined,", "access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response =", "Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id", "response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id assert response.user.email == email", "assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert", "@pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def", "True except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient):", "assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except", "response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\"", "\"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code ==", "assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except Exception", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover()", "try: await client.refresh_session() assert False except ValueError as e: assert str(e) == \"Not", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password", "assert isinstance(response, Session) response = await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try:", "expires_in.\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client:", "== expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client:", "gotrue.exceptions import APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover()", "== 400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError", "await client.sign_in() assert False except ValueError as e: assert str(e) == expected_error_message except", "persist_session=False, ) as client: yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email", "def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert", "str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response", "response.expires_at assert response.user assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at", "response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password)", "access_token = response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user", "AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ):", "( \"Email, phone, refresh_token, or provider must be defined, \" \"all can't be", "await client.sign_up(password=password) assert False except ValueError as e: assert str(e) == expected_error_message except", "= None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email,", "async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User)", "await client.sign_out() response = client.session() assert response is None except Exception as e:", "isinstance(response, Session) except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client:", "def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response,", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url =", "def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response is None except", "be defined, both can't be None.\" try: await client.sign_up(password=password) assert False except ValueError", "assert not response except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async", "== access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def", "AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session)", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response =", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password)", "async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert not response", "None.\" try: await client.sign_up(email=email) assert False except ValueError as e: assert str(e) ==", "as e: assert e.code == 400 assert e.msg == \"Invalid expires_in.\" except Exception", "= await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token response2 =", "provider must be defined, \" \"all can't be None.\" ) try: await client.sign_in()", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await", "def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or provider must be", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user()", "response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e:", "assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except Exception as e: assert", "@pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't be", "access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async", "== \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def", "typing import AsyncIterable, Optional import pytest from faker import Faker from gotrue import", "str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't", "== \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover()", "assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as", "e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session()", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\")", "url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() ->", "\"alpha\"}, ) assert isinstance(response, Session) global access_token access_token = response.access_token assert response.access_token assert", "== 400 assert e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await", "client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data =", "access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client:", "e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert", "try: response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover(", "in e.msg except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def", "assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as e:", "e.code == 400 assert e.msg == \"Invalid expires_in.\" except Exception as e: assert", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response =", "response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at", "def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, )", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token)", "): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token ==", "client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id", "async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try: await", "def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert", "): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except", "response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id assert response.user.email", "registered\" try: await client.sign_up( email=email, password=password, ) assert False except APIError as e:", "Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up(", "assert response.user_metadata == data except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__])", "client.sign_in(email=email, password=password + \"2\") assert False except APIError: assert True except Exception as", "client.sign_out() response = client.session() assert response is None except Exception as e: assert", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient,", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response", "test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or provider must be defined,", "response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception", "response.expires_at except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client:", "access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception", "str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert", "test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert not response except Exception", "assert str(e) == expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async", "data = {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata ==", "f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response,", "url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client fake = Faker() email =", "ValueError as e: assert str(e) == expected_error_message except Exception as e: assert False,", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\"", "= <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response", "defined, \" \"all can't be None.\" ) try: await client.sign_in() assert False except", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User", "\"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError", "\"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError", "AsyncGoTrueClient): expected_error_message = \"Email or phone must be defined, both can't be None.\"", "try: await client.sign_in(email=email, password=password + \"2\") assert False except APIError: assert True except", "\"User already registered\" try: await client.sign_up( email=email, password=password, ) assert False except APIError", "try: await client.init_recover() await client.sign_out() response = client.session() assert response is None except", "access_token access_token = response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert", "False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert", "fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password", "e.code == 400 assert e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try:", "assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except", "response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert", "await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response =", "@pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response is", "assert response.refresh_token assert response.expires_in assert response.expires_at except Exception as e: assert False, str(e)", "assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert", "try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code == 400", ") as client: yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email =", "phone, refresh_token, or provider must be defined, \" \"all can't be None.\" )", "== \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert", "400 assert e.msg == \"Invalid expires_in.\" except Exception as e: assert False, str(e)", "with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async def", "e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False", "async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"})", "async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert False except", "response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at", "400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError as", "response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async", "): expected_error_message = \"User already registered\" try: await client.sign_up( email=email, password=password, ) assert", "str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up(", "async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as", "= await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token)", "try: response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session)", "def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) )", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response = await", "AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response", "@pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, )", "assert response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\"", "\" \"all can't be None.\" ) try: await client.sign_in() assert False except ValueError", "expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient):", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await", "response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email", "response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\"", "defined, can't be None.\" try: await client.sign_up(email=email) assert False except ValueError as e:", "dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert", "assert isinstance(response, Session) global access_token access_token = response.access_token assert response.access_token assert response.refresh_token assert", "response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id assert", "client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata", "= Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password =", "data except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error(", "@pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response,", "+= \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code", "\"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient):", "assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e)", "response = await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert", "try: await client.sign_in() assert False except ValueError as e: assert str(e) == expected_error_message", ") assert response.user_metadata == data except Exception as e: assert False, str(e) @pytest.mark.asyncio", "assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert", "assert e.code == 400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False", "response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token response2", "def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try: await client.sign_up(", "= f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio", "f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient):", "assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except", "client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL,", "response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at", "def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must be defined, both can't", "expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient):", ") assert isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at assert", "as e: assert str(e) == expected_error_message except Exception as e: assert False, str(e)", "assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__])", "\"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session)", "password=password + \"2\") assert False except APIError: assert True except Exception as e:", "can't be None.\" try: await client.sign_up(password=password) assert False except ValueError as e: assert", "new_client.current_session.access_token == access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async", "assert expected_error_message in e.msg except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__])", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient,", "assert e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert", "client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token response2 = await client_with_session.sign_in(", "be None.\" try: await client.sign_up(password=password) assert False except ValueError as e: assert str(e)", "assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user", "assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert", "False except APIError as e: assert expected_error_message in e.msg except Exception as e:", "assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\")", "False except APIError as e: assert e.code == 400 assert e.msg == \"Invalid", "attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception as e: assert False, str(e)", "async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ):", "e.msg except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client(", "fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError as", "response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async", "\"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError", "response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response = await", "str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email()", "assert response.expires_in assert response.expires_at except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__])", "def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert False except APIError:", "assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e)", "assert e.code == 400 assert e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\"", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await", "\"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code ==", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try: await client.init_recover() response = await client.update(", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover()", "as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient(", "AsyncGoTrueClient): try: await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response,", "e: assert expected_error_message in e.msg except Exception as e: assert False, str(e) @pytest.mark.asyncio", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response = await", "response = client.session() assert response is None except Exception as e: assert False,", "access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e:", "str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must be", "test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\"", "= fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError", "-> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client", "def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client:", "e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await", "both can't be None.\" try: await client.sign_up(password=password) assert False except ValueError as e:", "+= \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code", "response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata", "== expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client:", "<filename>tests/_async/test_client_with_auto_confirm_enabled.py from typing import AsyncIterable, Optional import pytest from faker import Faker from", "@pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response,", "assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") ==", "e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email,", "expected_error_message = ( \"Email, phone, refresh_token, or provider must be defined, \" \"all", "def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert", "refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try:", "assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except", "AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try: await client.sign_up( email=email, password=password, )", "isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert False except ValueError as e:", "await client.sign_up(email=email) assert False except ValueError as e: assert str(e) == expected_error_message except", "assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e:", "assert response.expires_at assert response.user assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert", "response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata", "await client.init_recover() response = await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert", "AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert False except APIError: assert True", "email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider =", "email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\")", "persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async", "): try: response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert", "False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token,", "async def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"},", "None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client:", "ValueError as e: assert str(e) == \"Not logged in.\" except Exception as e:", "AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\"", "= ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url,", "response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", "== expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client:", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await", "assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert", "= \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert", "client.init_recover() response = client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in", "response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async", "assert e.code == 400 assert e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\"", "response.expires_in assert response.expires_at except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async", "AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or provider must be defined, \"", "assert False except APIError as e: assert e.code == 400 assert e.msg ==", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient):", "expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as", "e.msg == \"Invalid expires_in.\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__])", "is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def", "assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description", "test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response = client.session() assert response is", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover()", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try:", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert", "url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError as e: assert e.code ==", "except APIError: assert True except Exception as e: assert False, str(e) @pytest.mark.asyncio async", "async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or provider must", "@pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await", "response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id", "await client.init_recover() response = client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert", "response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\"", "= \"User already registered\" try: await client.sign_up( email=email, password=password, ) assert False except", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message =", "\"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception", "== error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code", "assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert False except ValueError as", "\"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code ==", "except APIError as e: assert e.code == 400 assert e.msg == \"Invalid expires_in.\"", "as e: assert str(e) == \"Not logged in.\" except Exception as e: assert", "auto_refresh_token=False, persist_session=False, ) as client: yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\"", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message", "import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL", "assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try:", "assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone,", "client.sign_up(email=email) assert False except ValueError as e: assert str(e) == expected_error_message except Exception", "import APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO =", "defined, both can't be None.\" try: await client.sign_up(password=password) assert False except ValueError as", "async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email, password=password,", "AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client()", "yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False,", "password=password, ) assert False except APIError as e: assert expected_error_message in e.msg except", "as e: assert e.code == 400 assert e.msg == \"No refresh_token detected.\" dummy_url", "AsyncIterable, Optional import pytest from faker import Faker from gotrue import AsyncGoTrueClient from", "password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token access_token = response.access_token assert", "response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at", "Session) global access_token access_token = response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert", "def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User) assert", "str(e) == expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def", "data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token access_token = response.access_token assert response.access_token", "url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() ->", "\"alpha\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session:", "AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client fake", "AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response is None except Exception as", "= \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with", "try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response =", "client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient):", "\"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client:", "assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert", "as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email", "password=password) assert isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session)", "response.user_metadata == data except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async", "response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e:", "client: yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email", "test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session)", "async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must be defined, both", "faker import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types", "= \"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except", "== \"Invalid expires_in.\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async", "already registered\" try: await client.sign_up( email=email, password=password, ) assert False except APIError as", "client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session() assert isinstance(response, Session) await client.sign_out()", "@pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, )", "f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async", "assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider", "except APIError as e: assert e.code == 400 assert e.msg == \"No access_token", "= \"Email or phone must be defined, both can't be None.\" try: await", ") try: await client.sign_in() assert False except ValueError as e: assert str(e) ==", "await client.sign_up( email=email, password=password, ) assert False except APIError as e: assert expected_error_message", "await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in", "assert e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert", "assert response.created_at assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as", "assert response.id assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert", "Session) except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient):", "e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False", "assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert", "\"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as", "False except ValueError as e: assert str(e) == \"Not logged in.\" except Exception", "@pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\"", "test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session", "persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async", "assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") == \"email\" except Exception as", "e: assert str(e) == expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio", "isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert", "try: await client.init_recover() response = client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token", "== data except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response =", "except APIError as e: assert expected_error_message in e.msg except Exception as e: assert", "not response except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def", "try: await client.init_recover() response = client.user() assert isinstance(response, User) assert response.id assert response.email", "+= \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code", "= f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client:", "= await client.sign_in(email=email) assert response is None except Exception as e: assert False,", "e: assert e.code == 400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url) assert", "as e: assert e.code == 400 assert e.msg == \"No access_token detected.\" dummy_url", "False except ValueError as e: assert str(e) == expected_error_message except Exception as e:", "assert new_client.current_session.access_token == access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__])", "try: response = await client.sign_in(email=email) assert response is None except Exception as e:", ") response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as e:", "new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token ==", "== 400 assert e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response", "400 assert e.msg == \"No token_type detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url)", "try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token", "await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e: assert", "yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email =", "as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password", "expected_error_message = \"Email or phone must be defined, both can't be None.\" try:", "400 assert e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url)", "AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\")", "response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider ==", "\"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code ==", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try:", "test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try: await client.sign_up( email=email,", "\"2\") assert False except APIError: assert True except Exception as e: assert False,", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert", "assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data)", "assert response.expires_at except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def", "assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__])", "as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response =", "None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password,", "response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email", "e: assert e.code == 400 assert e.msg == \"No token_type detected.\" dummy_url +=", "\"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient(", "client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False,", ") assert isinstance(response2, Session) assert response2.access_token assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try:", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient):", "async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient):", "can't be None.\" try: await client.sign_up(email=email) assert False except ValueError as e: assert", "test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't be None.\" try: await", "assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email)", "False except APIError as e: assert e.code == 400 assert e.msg == \"No", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient):", "await client.sign_out() try: await client.refresh_session() assert False except ValueError as e: assert str(e)", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try:", "== access_token except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] )", "expected_error_message = \"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False", "User) assert response.id assert response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at", "@pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response,", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password +", "False except APIError as e: assert e.code == 400 assert e.msg == error_description", "e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False", "refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as", "str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password,", "response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", "== \"alpha\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error(", "assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as e: assert False, str(e)", "APIError as e: assert expected_error_message in e.msg except Exception as e: assert False,", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client:", "response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata provider = response.app_metadata.get(\"provider\") assert", "await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token access_token", "== expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def", "async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response is None", "assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert", "= await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response =", "refresh_token, or provider must be defined, \" \"all can't be None.\" ) try:", "response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False,", "response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e:", "logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as", "= response.access_token assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert", "assert response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__])", "response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception", "response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient,", "async def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session)", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert", "assert e.code == 400 assert e.msg == \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\"", "@pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try:", "from typing import AsyncIterable, Optional import pytest from faker import Faker from gotrue", "assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") ==", "test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token", "= ( \"Email, phone, refresh_token, or provider must be defined, \" \"all can't", "== \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def", "= client.user() assert not response except Exception as e: assert False, str(e) @pytest.mark.asyncio", "= await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as e: assert False,", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message =", "Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await", "await client.refresh_session() assert False except ValueError as e: assert str(e) == \"Not logged", "assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id assert response.user.email ==", "expected_error_message in e.msg except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async", "except APIError as e: assert e.code == 400 assert e.msg == \"No token_type", "\"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert False,", "False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True,", "== email assert response.user.email_confirmed_at assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert", "client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response,", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message", "as e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url =", "\"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client:", "be defined, can't be None.\" try: await client.sign_up(email=email) assert False except ValueError as", "TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL,", "<PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response =", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\"", "async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as", "assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\") ==", "expected_error_message = \"User already registered\" try: await client.sign_up( email=email, password=password, ) assert False", "client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False,", "await client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id assert response.email ==", "assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await", "client.session() assert response is None except Exception as e: assert False, str(e) @pytest.mark.asyncio", "await client.sign_in(email=email, password=password + \"2\") assert False except APIError: assert True except Exception", "\"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert", "response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session() assert isinstance(response,", "expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__]) async def test_sign_in_with_the_wrong_password(client:", "await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception as", "on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover()", "from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import Session, User,", "isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except Exception as", "@pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert", "assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up(", "attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id assert response.email == email assert", "= False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False,", "in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e:", "+ \"2\") assert False except APIError: assert True except Exception as e: assert", "import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import", "== refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert", "== email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata assert", "assert response2.refresh_token assert response2.expires_in assert response2.expires_at assert response2.user assert response2.user.id assert response2.user.email ==", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token", "None.\" try: await client.sign_up(password=password) assert False except ValueError as e: assert str(e) ==", "async def test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session)", "APIError from gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False", "expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient):", "is None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def", "AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response = client.session() assert response is None", "== \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session:", "AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token", "must be defined, can't be None.\" try: await client.sign_up(email=email) assert False except ValueError", "except ValueError as e: assert str(e) == expected_error_message except Exception as e: assert", "== 400 assert e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await", "== \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except", "detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e:", "assert e.code == 400 assert e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\"", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_up_the_same_user_twice_should_throw_an_error( client: AsyncGoTrueClient, ):", "except APIError as e: assert e.code == 400 assert e.msg == \"No refresh_token", "error_description = fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except", "str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or", "( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" ) response = await client.get_session_from_url(url=dummy_url, store_session=True)", "\"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client:", "assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception as e: assert False, str(e)", "assert False except APIError: assert True except Exception as e: assert False, str(e)", "assert response.user.last_sign_in_at assert response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert", "as e: assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try:", "@pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = ( \"Email, phone, refresh_token, or provider", "async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email() try: await", "yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False,", "refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata assert response2.user.app_metadata.get(\"provider\")", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_get_session_from_url_errors(client: AsyncGoTrueClient): try:", "= await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception as e:", "async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User)", "AsyncGoTrueClient): expected_error_message = \"Password must be defined, can't be None.\" try: await client.sign_up(email=email)", "async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out() response = client.session() assert", "error_description try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code ==", "gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import Session, User, UserAttributes", "client.sign_up( email=email, password=password, ) assert False except APIError as e: assert expected_error_message in", "response.user.created_at assert response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\")", "response.app_metadata provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as e: assert", "AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert not response except Exception as", "provider == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async", "await client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert False except", "client: AsyncGoTrueClient, ): expected_error_message = \"User already registered\" try: await client.sign_up( email=email, password=password,", "response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", "assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user", "AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert", "async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async", "await client_with_session.sign_up( email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email,", "await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e: assert str(e)", "client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e: assert str(e) == expected_error_message except", "try: assert access_token dummy_url = ( \"https://localhost\" f\"?access_token={access_token}\" \"&refresh_token=refresh_token\" \"&token_type=bearer\" \"&expires_in=3600\" \"&type=recovery\" )", "detected.\" dummy_url += \"&token_type=bearer\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e:", "response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at except Exception as e: assert False,", "await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token response2 = await", "AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session()", "try: await client.sign_up( email=email, password=password, ) assert False except APIError as e: assert", "test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert", "None except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client:", "assert response.expires_in assert response.expires_at assert response.user assert response.user.id assert response.user.email == email assert", "await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response", "test_sign_in_with_the_wrong_password(client: AsyncGoTrueClient): try: await client.sign_in(email=email, password=password + \"2\") assert False except APIError: assert", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient):", "response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient):", "False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message = \"Password must be defined,", "400 assert e.msg == \"No access_token detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url)", "assert str(e) == expected_error_message except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_sign_out.__name__])", "@pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password, data={\"status\":", "test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url", "assert False except APIError as e: assert expected_error_message in e.msg except Exception as", "gotrue.types import Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async", "= response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as e: assert False, str(e)", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try:", "async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token)", "response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async def", ") assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response", "await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data except Exception as e: assert", "Session) assert response.refresh_token response2 = await client_with_session.sign_in( refresh_token=response.refresh_token ) assert isinstance(response2, Session) assert", "response except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client:", "AsyncGoTrueClient): try: response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response,", "test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email) assert response is None except Exception", "can't be None.\" ) try: await client.sign_in() assert False except ValueError as e:", "assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e) @pytest.mark.asyncio async", "User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() ->", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_magic_link(client: AsyncGoTrueClient): try: response", "False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await", "\"Email or phone must be defined, both can't be None.\" try: await client.sign_up(password=password)", "response.refresh_token assert response.expires_in assert response.expires_at except Exception as e: assert False, str(e) @pytest.mark.asyncio", "+= \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code", "def test_get_session_from_url_errors(client: AsyncGoTrueClient): try: dummy_url = \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url(", "response = await client.sign_up( email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global", "from faker import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import APIError from", "as client: yield client fake = Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\"", "@pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert isinstance(response,", "assert e.msg == \"No expires_in detected.\" dummy_url += \"&expires_in=str\" try: await client.get_session_from_url(url=dummy_url) assert", "client.sign_in() assert False except ValueError as e: assert str(e) == expected_error_message except Exception", ") assert False except APIError as e: assert expected_error_message in e.msg except Exception", "client.init_recover() await client.sign_out() response = client.session() assert response is None except Exception as", "try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token", "Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message =", ") assert False except APIError as e: assert e.code == 400 assert e.msg", "except APIError as e: assert e.code == 400 assert e.msg == \"No expires_in", "auto_refresh_token=False, persist_session=False, ) as client: yield client @pytest.fixture(name=\"new_client\") async def create_new_client() -> AsyncIterable[AsyncGoTrueClient]:", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_get_session_from_url(client: AsyncGoTrueClient): try: assert", "try: await client.init_recover() response = client.user() assert not response except Exception as e:", "assert False except ValueError as e: assert str(e) == expected_error_message except Exception as", "assert False except ValueError as e: assert str(e) == \"Not logged in.\" except", "str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user()", "AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\")", "response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert response2.user.updated_at assert response2.user.app_metadata", "create_new_client() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield", "email=email, password=password, data={\"status\": \"alpha\"}, ) assert isinstance(response, Session) global access_token access_token = response.access_token", "assert False, str(e) @pytest.mark.asyncio async def test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response =", "UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client() -> AsyncIterable[AsyncGoTrueClient]:", "try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token", "assert response.updated_at assert response.user_metadata assert response.user_metadata.get(\"hello\") == \"world\" except Exception as e: assert", "\"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_update_user(client: AsyncGoTrueClient): try:", "except Exception as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_up_with_password_none(client: AsyncGoTrueClient): expected_error_message", "response.user.updated_at assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False,", "async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert isinstance(response, Session)", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try:", "@pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert not", "f\"?error_description={error_description}\" ) assert False except APIError as e: assert e.code == 400 assert", "as e: assert e.code == 400 assert e.msg == error_description try: await client.get_session_from_url(url=dummy_url)", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_update_user.__name__]) async def test_get_user_after_update(client: AsyncGoTrueClient): try:", ") assert isinstance(response, Session) global access_token access_token = response.access_token assert response.access_token assert response.refresh_token", "new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.init_recover() await new_client.set_auth(access_token=access_token) assert new_client.current_session assert", "response = client.session() assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert response.expires_in assert", "Faker() email = f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>()", "client: yield client @pytest.fixture(name=\"client_with_session\") async def create_client_with_session() -> AsyncIterable[AsyncGoTrueClient]: async with AsyncGoTrueClient( url=GOTRUE_URL,", "Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\": \"world\"} response = await client_with_session.update(", "await client.update(attributes=UserAttributes(data={\"hello\": \"world\"})) assert False except ValueError as e: assert str(e) == expected_error_message", "== \"No refresh_token detected.\" dummy_url += \"&refresh_token=refresh_token\" try: await client.get_session_from_url(url=dummy_url) assert False except", "client.update( attributes=UserAttributes(data={\"hello\": \"world\"}) ) assert isinstance(response, User) assert response.id assert response.email == email", "AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email, password=password, ) assert isinstance(response, Session) assert", "try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert new_client.current_session.access_token == access_token except Exception", "Optional import pytest from faker import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions", "test_refresh_session(client: AsyncGoTrueClient): try: response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_update_user_after_sign_out.__name__]) async def test_refresh_session(client: AsyncGoTrueClient): try: response =", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends( on=[test_set_auth_should_set_the_auth_headers_on_a_new_client.__name__] ) async def test_set_auth_should_set_the_auth_headers_on_a_new_client_and_recover( new_client: AsyncGoTrueClient, ): try:", "assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response", "Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_user_after_sign_out(client: AsyncGoTrueClient): try:", "APIError as e: assert e.code == 400 assert e.msg == \"No token_type detected.\"", "APIError as e: assert e.code == 400 assert e.msg == \"Invalid expires_in.\" except", "assert response.access_token assert response.refresh_token assert response.expires_in assert response.expires_at assert response.user assert response.user.id assert", "client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as e: assert False, str(e) @pytest.mark.asyncio", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client: AsyncGoTrueClient): try: await client.init_recover() await client.sign_out()", "@pytest.mark.depends(on=[test_sign_up.__name__]) async def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert", "await client.init_recover() await client.sign_out() response = client.session() assert response is None except Exception", "with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=False, ) as client: yield client fake = Faker()", "assert response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" except Exception as e: assert False, str(e)", "response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.app_metadata", "f\"client_ac_enabled_{fake.email().lower()}\" set_session_email = f\"client_ac_session_{fake.email().lower()}\" refresh_token_email = f\"client_refresh_token_signin_{fake.email().lower()}\" password = <PASSWORD>() access_token: Optional[str] =", "response = await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.access_token assert response.refresh_token assert", "test_get_user(client: AsyncGoTrueClient): try: await client.init_recover() response = client.user() assert isinstance(response, User) assert response.id", "client.user() assert isinstance(response, User) assert response.id assert response.email == email assert response.email_confirmed_at assert", "APIError: assert True except Exception as e: assert False, str(e) @pytest.mark.asyncio async def", "as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_user(client: AsyncGoTrueClient): try: await", "response = await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as e: assert", "detected.\" dummy_url += \"?access_token=access_token\" try: await client.get_session_from_url(url=dummy_url) assert False except APIError as e:", "AsyncGoTrueClient): try: await client.init_recover() response = client.session() assert isinstance(response, Session) assert response.access_token assert", "client.get_session_from_url(url=dummy_url) assert False except APIError as e: assert e.code == 400 assert e.msg", "assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token) assert isinstance(response, Session) response = await client.refresh_session()", "as e: assert False, str(e) @pytest.mark.asyncio async def test_sign_in_with_all_nones(client: AsyncGoTrueClient): expected_error_message = (", "response.expires_in assert response.expires_at assert response.user assert response.user.id assert response.user.email == email assert response.user.email_confirmed_at", "try: dummy_url = \"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\"", "response2.expires_at assert response2.user assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at", "e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_out.__name__]) async def test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not", "test_get_update_user_after_sign_out(client: AsyncGoTrueClient): expected_error_message = \"Not logged in.\" try: await client.init_recover() await client.update(attributes=UserAttributes(data={\"hello\": \"world\"}))", "response.email == email assert response.email_confirmed_at assert response.last_sign_in_at assert response.created_at assert response.updated_at assert response.user_metadata", "await client.get_session_from_url(url=dummy_url, store_session=True) assert isinstance(response, Session) except Exception as e: assert False, str(e)", "\"world\" except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_get_user_after_update.__name__]) async def test_sign_out(client:", "Session, User, UserAttributes GOTRUE_URL = \"http://localhost:9998\" TEST_TWILIO = False @pytest.fixture(name=\"client\") async def create_client()", "client.refresh_session() assert isinstance(response, Session) await client.sign_out() try: await client.refresh_session() assert False except ValueError", "email=set_session_email, password=password, ) assert isinstance(response, Session) assert response.refresh_token await client_with_session.set_session(refresh_token=response.refresh_token) data = {\"hello\":", "None.\" ) try: await client.sign_in() assert False except ValueError as e: assert str(e)", "import pytest from faker import Faker from gotrue import AsyncGoTrueClient from gotrue.exceptions import", "== 400 assert e.msg == \"Invalid expires_in.\" except Exception as e: assert False,", "= await client.sign_in(email=email, password=password) assert isinstance(response, Session) assert response.refresh_token response = await client.set_session(refresh_token=response.refresh_token)", "= {\"hello\": \"world\"} response = await client_with_session.update( attributes=UserAttributes(data=data) ) assert response.user_metadata == data", "provider = response.app_metadata.get(\"provider\") assert provider == \"email\" except Exception as e: assert False,", "response.user.app_metadata assert response.user.app_metadata.get(\"provider\") == \"email\" assert response.user.user_metadata assert response.user.user_metadata.get(\"status\") == \"alpha\" except Exception", "be defined, \" \"all can't be None.\" ) try: await client.sign_in() assert False", "except Exception as e: assert False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_up.__name__]) async def test_sign_in(client: AsyncGoTrueClient):", "test_sign_up_with_email_and_phone_none(client: AsyncGoTrueClient): expected_error_message = \"Email or phone must be defined, both can't be", "password = <PASSWORD>() access_token: Optional[str] = None @pytest.mark.asyncio async def test_sign_up(client: AsyncGoTrueClient): try:", "assert response2.user.id assert response2.user.email == refresh_token_email assert response2.user.email_confirmed_at assert response2.user.last_sign_in_at assert response2.user.created_at assert", "\"https://localhost\" error_description = fake.email() try: await client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False", "client.get_session_from_url( url=dummy_url + f\"?error_description={error_description}\" ) assert False except APIError as e: assert e.code", "def test_set_auth_should_set_the_auth_headers_on_a_new_client( new_client: AsyncGoTrueClient, ): try: assert access_token await new_client.set_auth(access_token=access_token) assert new_client.current_session assert", "APIError as e: assert e.code == 400 assert e.msg == \"No refresh_token detected.\"", "test_set_session_should_return_no_error( client_with_session: AsyncGoTrueClient, ): try: response = await client_with_session.sign_up( email=set_session_email, password=password, ) assert", "False, str(e) @pytest.mark.asyncio async def test_sign_in_with_refresh_token(client_with_session: AsyncGoTrueClient): try: response = await client_with_session.sign_up( email=refresh_token_email,", "await client.sign_in(email=email) assert response is None except Exception as e: assert False, str(e)", "False, str(e) @pytest.mark.asyncio @pytest.mark.depends(on=[test_sign_in.__name__]) async def test_get_session(client: AsyncGoTrueClient): try: await client.init_recover() response =", "with AsyncGoTrueClient( url=GOTRUE_URL, auto_refresh_token=False, persist_session=True, ) as client: yield client @pytest.fixture(name=\"client_with_session\") async def", "try: await client.sign_up(password=password) assert False except ValueError as e: assert str(e) == expected_error_message" ]
[ "stdin.readline n = int(rl()) a = [[int(x) for x in rl().split()] for _", "a = [[int(x) for x in rl().split()] for _ in range(n)] a.sort() i", "_ in range(n)] a.sort() i = s = 0 while i < n:", "= 0 while i < n: end = a[i][1] while i < n", "range(n)] a.sort() i = s = 0 while i < n: end =", "import stdin, stdout rl = stdin.readline n = int(rl()) a = [[int(x) for", "sys import stdin, stdout rl = stdin.readline n = int(rl()) a = [[int(x)", "= int(rl()) a = [[int(x) for x in rl().split()] for _ in range(n)]", "in range(n)] a.sort() i = s = 0 while i < n: end", "for x in rl().split()] for _ in range(n)] a.sort() i = s =", "= s = 0 while i < n: end = a[i][1] while i", "= stdin.readline n = int(rl()) a = [[int(x) for x in rl().split()] for", "< n: end = a[i][1] while i < n and end >= a[i][0]:", "+= 1 end = min(end, a[i][1]) if i < n else end s", "stdin, stdout rl = stdin.readline n = int(rl()) a = [[int(x) for x", "i < n: end = a[i][1] while i < n and end >=", "n and end >= a[i][0]: i += 1 end = min(end, a[i][1]) if", "rl = stdin.readline n = int(rl()) a = [[int(x) for x in rl().split()]", "0 while i < n: end = a[i][1] while i < n and", "main(): from sys import stdin, stdout rl = stdin.readline n = int(rl()) a", "end >= a[i][0]: i += 1 end = min(end, a[i][1]) if i <", ">= a[i][0]: i += 1 end = min(end, a[i][1]) if i < n", "end = a[i][1] while i < n and end >= a[i][0]: i +=", "s = 0 while i < n: end = a[i][1] while i <", "a.sort() i = s = 0 while i < n: end = a[i][1]", "i += 1 end = min(end, a[i][1]) if i < n else end", "[[int(x) for x in rl().split()] for _ in range(n)] a.sort() i = s", "end = min(end, a[i][1]) if i < n else end s += 1", "<gh_stars>1-10 # https://www.codechef.com/ZCOPRAC/problems/ZCO15003 def main(): from sys import stdin, stdout rl = stdin.readline", "for _ in range(n)] a.sort() i = s = 0 while i <", "in rl().split()] for _ in range(n)] a.sort() i = s = 0 while", "i = s = 0 while i < n: end = a[i][1] while", "n: end = a[i][1] while i < n and end >= a[i][0]: i", "= a[i][1] while i < n and end >= a[i][0]: i += 1", "a[i][1] while i < n and end >= a[i][0]: i += 1 end", "< n and end >= a[i][0]: i += 1 end = min(end, a[i][1])", "i < n and end >= a[i][0]: i += 1 end = min(end,", "and end >= a[i][0]: i += 1 end = min(end, a[i][1]) if i", "1 end = min(end, a[i][1]) if i < n else end s +=", "while i < n: end = a[i][1] while i < n and end", "min(end, a[i][1]) if i < n else end s += 1 stdout.write(str(s)) main()", "= min(end, a[i][1]) if i < n else end s += 1 stdout.write(str(s))", "x in rl().split()] for _ in range(n)] a.sort() i = s = 0", "stdout rl = stdin.readline n = int(rl()) a = [[int(x) for x in", "https://www.codechef.com/ZCOPRAC/problems/ZCO15003 def main(): from sys import stdin, stdout rl = stdin.readline n =", "while i < n and end >= a[i][0]: i += 1 end =", "a[i][0]: i += 1 end = min(end, a[i][1]) if i < n else", "int(rl()) a = [[int(x) for x in rl().split()] for _ in range(n)] a.sort()", "from sys import stdin, stdout rl = stdin.readline n = int(rl()) a =", "# https://www.codechef.com/ZCOPRAC/problems/ZCO15003 def main(): from sys import stdin, stdout rl = stdin.readline n", "= [[int(x) for x in rl().split()] for _ in range(n)] a.sort() i =", "def main(): from sys import stdin, stdout rl = stdin.readline n = int(rl())", "rl().split()] for _ in range(n)] a.sort() i = s = 0 while i", "n = int(rl()) a = [[int(x) for x in rl().split()] for _ in" ]
[ "payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False", "payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return", "payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter']", "new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc", "delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment) db.session.commit() return True return False", "payment['payment_type']: existing = True break if not existing: new_payment = ChapterPayments() new_payment.received_from =", "existing = True break if not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from']", "ChapterPayments from baseapp import db class ChapterPaymentsController: def __init__(self): pass def add(self, payment):", "payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def edit(self, payment):", "def __init__(self): pass def add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for", "payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing = True break if not existing:", "models import ChapterPayments from baseapp import db class ChapterPaymentsController: def __init__(self): pass def", "payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first()", "= payment['chapter'] db.session.commit() return True return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first()", "= ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type =", "ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount ==", "False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\", "payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount", "if not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount", "= True break if not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date", "existing_payment.payment_type == payment['payment_type']: existing = True break if not existing: new_payment = ChapterPayments()", "existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\", "db.session.commit() return True return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment:", "new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment)", "add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if", "if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type ==", "db.session.commit() return True return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment:", "payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\ and", "def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date =", "payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing =", "\\ and existing_payment.payment_type == payment['payment_type']: existing = True break if not existing: new_payment", "from baseapp import db class ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing", "True return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from =", "existing_payment.chapter = payment['chapter'] db.session.commit() return True return False def delete(self, payment): existing_payment =", "db class ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing = False payments", "= payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc =", "and existing_payment.payment_type == payment['payment_type']: existing = True break if not existing: new_payment =", "return True return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from", "payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from", "= payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter =", "in payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and", "import db class ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing = False", "new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def", "pass def add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in", "payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter']", "return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from']", "payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True", "import ChapterPayments from baseapp import db class ChapterPaymentsController: def __init__(self): pass def add(self,", "== payment['payment_type']: existing = True break if not existing: new_payment = ChapterPayments() new_payment.received_from", "True return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment) db.session.commit()", "db.session.add(new_payment) db.session.commit() return True return False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if", "== payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing", "ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all()", "False def edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date", "new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter", "existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return", "ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type']", "= ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount']", "= False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from == payment['received_from']", "payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc']", "payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc']", "__init__(self): pass def add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment", "= ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount", "= payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return False def delete(self, payment):", "payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return False def delete(self, payment): existing_payment", "break if not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date']", "== payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing = True break if not", "= payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc =", "new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True", "existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit()", "def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment) db.session.commit() return True return", "existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing = True break if", "for existing_payment in payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount']", "= payment['received_amount'] new_payment.payment_type = payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit()", "= payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def edit(self, payment): existing_payment =", "payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return False def", "def add(self, payment): existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments:", "existing = False payments = ChapterPayments.query.filter_by(received_date=payment['received_date']).all() for existing_payment in payments: if existing_payment.received_from ==", "payment['chapter'] db.session.commit() return True return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if", "ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type", "existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount']", "and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing = True break", "edit(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date']", "existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type']", "payments: if existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type", "existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount =", "class ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing = False payments =", "= payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def edit(self,", "new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return False def edit(self, payment): existing_payment", "= payment['payment_type'] new_payment.cpc = payment['cpc'] new_payment.chapter = payment['chapter'] db.session.add(new_payment) db.session.commit() return True return", "if existing_payment: existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type =", "\\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']: existing = True", "not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount =", "new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date = payment['received_date'] new_payment.received_amount = payment['received_amount'] new_payment.payment_type", "existing_payment.received_from == payment['received_from'] \\ and existing_payment.received_amount == payment['received_amount'] \\ and existing_payment.payment_type == payment['payment_type']:", "from models import ChapterPayments from baseapp import db class ChapterPaymentsController: def __init__(self): pass", "= payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return", "= payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return False", "= payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter =", "existing_payment.cpc = payment['cpc'] existing_payment.chapter = payment['chapter'] db.session.commit() return True return False def delete(self,", "baseapp import db class ChapterPaymentsController: def __init__(self): pass def add(self, payment): existing =", "return True return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment)", "return False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment) db.session.commit() return", "True break if not existing: new_payment = ChapterPayments() new_payment.received_from = payment['received_from'] new_payment.received_date =", "False def delete(self, payment): existing_payment = ChapterPayments.query.filter_by(id=payment['id']).first() if existing_payment: db.session.delete(existing_payment) db.session.commit() return True", "existing_payment.received_from = payment['received_from'] existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc", "existing_payment.received_date = payment['received_date'] existing_payment.received_amount = payment['received_amount'] existing_payment.payment_type = payment['payment_type'] existing_payment.cpc = payment['cpc'] existing_payment.chapter" ]
[ "the consuming system must understand the element and be able to provide values", "\"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on the data in terms", "an effective evaluation. This does not mean that a value is required for", "specify additional constraints on the data in terms of the applicable date range", "data, i.e. date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a", "value that does not contain spaces. \"id\": FHIR_string, # May be used to", "or date-based filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique", "module and must be supported by the consumer in order to obtain an", "the applicable date range for specific elements. Each date filter specifies an additional", "FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id for the element within a", "SHALL be met as part of the definition of the extension. \"extension\": List[Any],", "the data, i.e. date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies", "resource of the profile. \"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element, #", "# Unique id for the element within a resource (for internal references). This", "date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number", "type of the DataRequirement. The path SHALL consist only of identifiers, constant indexers,", "there is a set of requirements that SHALL be met as part of", "in order to obtain an effective evaluation. This does not mean that a", "of the profile definition. \"profile\": List[FHIR_canonical], # The intended subjects of the data", "full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters", "The type of the required data, specified as the type name of a", "data, specified as the type name of a resource. For profiles, this value", "constraint on the data, i.e. code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter],", "interest for a particular element of the data. Each code filter defines an", "Describes a required data item for evaluation in terms of the type of", "# Describes a required data item for evaluation in terms of the type", "# The type of the required data, specified as the type name of", "of extensions safe and manageable, there is a strict set of governance applied", "search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, # Specifies the", "must be supported by the consumer in order to obtain an effective evaluation.", "of identifiers, constant indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full", "evaluation in terms of the type of data, and optional code or date-based", "of the data requirement. If this element is not provided, a Patient subject", "of the basic definition of the element. To make the use of extensions", "mean that a value is required for this element, only that the consuming", "the base resource of the profile. \"type\": FHIR_code, # Extensions for type \"_type\":", "a set of requirements that SHALL be met as part of the definition", "FHIR_Element, # Specifies the order of the results to be returned. \"sort\": List[FHIR_DataRequirement_Sort],", "set of governance applied to the definition and use of extensions. Though any", "define an extension, there is a set of requirements that SHALL be met", "List[FHIR_Element], # Code filters specify additional constraints on the data, specifying the value", "the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, #", "the data, specifying the value set of interest for a particular element of", "the required data, specified as the uri of the profile definition. \"profile\": List[FHIR_canonical],", "a value is required for this element, only that the consuming system must", "Though any implementer can define an extension, there is a set of requirements", "provide values for it if they are available. The value of mustSupport SHALL", "element of the data. Each code filter defines an additional constraint on the", "applied to the definition and use of extensions. Though any implementer can define", "The value of mustSupport SHALL be a FHIRPath resolveable on the type of", "the basic definition of the element. To make the use of extensions safe", "be supported by the consumer in order to obtain an effective evaluation. This", ".FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt", "# May be used to represent additional information that is not part of", "data, i.e. code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters", "additional constraint on the data, i.e. date filters are AND'ed, not OR'ed. \"dateFilter\":", "consumer in order to obtain an effective evaluation. This does not mean that", "from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from", "import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import", "the data in terms of the applicable date range for specific elements. Each", "extension. \"extension\": List[Any], # The type of the required data, specified as the", "for it if they are available. The value of mustSupport SHALL be a", "\"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the data requirement. If this element", "import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import", "# Extensions for type \"_type\": FHIR_Element, # The profile of the required data,", "that a value is required for this element, only that the consuming system", "maximum number of results that are required (uses the _count search parameter). \"limit\":", "profiles, this value is set to the type of the base resource of", "# Code filters specify additional constraints on the data, specifying the value set", "value set of interest for a particular element of the data. Each code", "is a set of requirements that SHALL be met as part of the", "set of requirements that SHALL be met as part of the definition of", "that specific elements of the type are referenced by the knowledge module and", "code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional", "provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of", "is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the data requirement. If", "If this element is not provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept,", "name of a resource. For profiles, this value is set to the type", "is not provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended", "the profile definition. \"profile\": List[FHIR_canonical], # The intended subjects of the data requirement.", "of data, and optional code or date-based filters of the data. FHIR_DataRequirement =", "are referenced by the knowledge module and must be supported by the consumer", "are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on", "values for it if they are available. The value of mustSupport SHALL be", "(see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions for", "specify additional constraints on the data, specifying the value set of interest for", "TypedDict( \"FHIR_DataRequirement\", { # Unique id for the element within a resource (for", "an extension, there is a set of requirements that SHALL be met as", "make the use of extensions safe and manageable, there is a strict set", "range for specific elements. Each date filter specifies an additional constraint on the", "knowledge module and must be supported by the consumer in order to obtain", "be any string value that does not contain spaces. \"id\": FHIR_string, # May", "limit \"_limit\": FHIR_Element, # Specifies the order of the results to be returned.", "of the definition of the extension. \"extension\": List[Any], # The type of the", "filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints", "specific elements. Each date filter specifies an additional constraint on the data, i.e.", "in terms of the type of data, and optional code or date-based filters", "and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], #", "the order of the results to be returned. \"sort\": List[FHIR_DataRequirement_Sort], }, total=False, )", "data, and optional code or date-based filters of the data. FHIR_DataRequirement = TypedDict(", "specified as the type name of a resource. For profiles, this value is", "requirement. If this element is not provided, a Patient subject is assumed. \"subjectReference\":", "that are required (uses the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions for", "available. The value of mustSupport SHALL be a FHIRPath resolveable on the type", "FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Describes a required", "(uses the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element,", "value of mustSupport SHALL be a FHIRPath resolveable on the type of the", "element. To make the use of extensions safe and manageable, there is a", "the use of extensions safe and manageable, there is a strict set of", "on the data, i.e. code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], #", "requirement. If this element is not provided, a Patient subject is assumed. \"subjectCodeableConcept\":", "from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from", "of the type are referenced by the knowledge module and must be supported", "set of interest for a particular element of the data. Each code filter", "data, specifying the value set of interest for a particular element of the", "of extensions. Though any implementer can define an extension, there is a set", "not provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects", "of interest for a particular element of the data. Each code filter defines", "obtain an effective evaluation. This does not mean that a value is required", "i.e. code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify", "Extensions for limit \"_limit\": FHIR_Element, # Specifies the order of the results to", "is a strict set of governance applied to the definition and use of", "the extension. \"extension\": List[Any], # The type of the required data, specified as", "of the DataRequirement. The path SHALL consist only of identifiers, constant indexers, and", ".resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions", "within a resource (for internal references). This may be any string value that", "import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import", "Code filters specify additional constraints on the data, specifying the value set of", "Indicates that specific elements of the type are referenced by the knowledge module", "element within a resource (for internal references). This may be any string value", "are available. The value of mustSupport SHALL be a FHIRPath resolveable on the", "of the applicable date range for specific elements. Each date filter specifies an", "a required data item for evaluation in terms of the type of data,", "the type name of a resource. For profiles, this value is set to", "type of the base resource of the profile. \"type\": FHIR_code, # Extensions for", "Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the data", "does not contain spaces. \"id\": FHIR_string, # May be used to represent additional", "FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, # Specifies the order of the", "a Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements of", "# Specifies a maximum number of results that are required (uses the _count", "use of extensions. Though any implementer can define an extension, there is a", "indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string],", "May be used to represent additional information that is not part of the", "The profile of the required data, specified as the uri of the profile", "of the extension. \"extension\": List[Any], # The type of the required data, specified", "_count search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, # Specifies", "the element and be able to provide values for it if they are", "that does not contain spaces. \"id\": FHIR_string, # May be used to represent", "required (uses the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\":", "AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on the", ".FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter", "import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import", "FHIR_CodeableConcept, # The intended subjects of the data requirement. If this element is", "this element is not provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference, #", "and optional code or date-based filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\",", "for this element, only that the consuming system must understand the element and", "i.e. date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum", "data, specified as the uri of the profile definition. \"profile\": List[FHIR_canonical], # The", "FHIR_Reference, # Indicates that specific elements of the type are referenced by the", "internal references). This may be any string value that does not contain spaces.", "mustSupport SHALL be a FHIRPath resolveable on the type of the DataRequirement. The", "specific elements of the type are referenced by the knowledge module and must", "If this element is not provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference,", "extensions. Though any implementer can define an extension, there is a set of", "FHIRPath resolveable on the type of the DataRequirement. The path SHALL consist only", "resource (for internal references). This may be any string value that does not", "FHIR_string # Describes a required data item for evaluation in terms of the", "defines an additional constraint on the data, i.e. code filters are AND'ed, not", "not provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific", "referenced by the knowledge module and must be supported by the consumer in", "for type \"_type\": FHIR_Element, # The profile of the required data, specified as", "the knowledge module and must be supported by the consumer in order to", "FHIR_string, # May be used to represent additional information that is not part", "filters specify additional constraints on the data in terms of the applicable date", "from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from", "elements of the type are referenced by the knowledge module and must be", "a maximum number of results that are required (uses the _count search parameter).", "by the consumer in order to obtain an effective evaluation. This does not", "import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import", "is not provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that", "assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements of the type are referenced", "the profile. \"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element, # The profile", ".FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Describes a required data item", "use of extensions safe and manageable, there is a strict set of governance", "of results that are required (uses the _count search parameter). \"limit\": FHIR_positiveInt, #", "additional constraints on the data, specifying the value set of interest for a", "element is not provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates", "List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on the data in terms of", "for a particular element of the data. Each code filter defines an additional", "\"subjectReference\": FHIR_Reference, # Indicates that specific elements of the type are referenced by", "represent additional information that is not part of the basic definition of the", "import FHIR_string # Describes a required data item for evaluation in terms of", "an additional constraint on the data, i.e. code filters are AND'ed, not OR'ed.", "List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints", "subjects of the data requirement. If this element is not provided, a Patient", "of the required data, specified as the type name of a resource. For", "basic definition of the element. To make the use of extensions safe and", "a resource. For profiles, this value is set to the type of the", "Specifies the order of the results to be returned. \"sort\": List[FHIR_DataRequirement_Sort], }, total=False,", "references). This may be any string value that does not contain spaces. \"id\":", "profile. \"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element, # The profile of", "not part of the basic definition of the element. To make the use", "[Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\":", "able to provide values for it if they are available. The value of", "consuming system must understand the element and be able to provide values for", "FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string", "of the profile. \"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element, # The", "the required data, specified as the type name of a resource. For profiles,", "and be able to provide values for it if they are available. The", "constraints on the data in terms of the applicable date range for specific", "resolveable on the type of the DataRequirement. The path SHALL consist only of", "FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element", "may be any string value that does not contain spaces. \"id\": FHIR_string, #", "order to obtain an effective evaluation. This does not mean that a value", "FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter", "from .FHIR_string import FHIR_string # Describes a required data item for evaluation in", "List[FHIR_canonical], # The intended subjects of the data requirement. If this element is", "the uri of the profile definition. \"profile\": List[FHIR_canonical], # The intended subjects of", "on the type of the DataRequirement. The path SHALL consist only of identifiers,", "date range for specific elements. Each date filter specifies an additional constraint on", "intended subjects of the data requirement. If this element is not provided, a", "effective evaluation. This does not mean that a value is required for this", "FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt", "this element, only that the consuming system must understand the element and be", "to the type of the base resource of the profile. \"type\": FHIR_code, #", "as part of the definition of the extension. \"extension\": List[Any], # The type", "safe and manageable, there is a strict set of governance applied to the", "are required (uses the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions for limit", "a particular element of the data. Each code filter defines an additional constraint", "of mustSupport SHALL be a FHIRPath resolveable on the type of the DataRequirement.", "by the knowledge module and must be supported by the consumer in order", "type of data, and optional code or date-based filters of the data. FHIR_DataRequirement", "be met as part of the definition of the extension. \"extension\": List[Any], #", "part of the definition of the extension. \"extension\": List[Any], # The type of", "the element. To make the use of extensions safe and manageable, there is", "OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on the data in", "path SHALL consist only of identifiers, constant indexers, and .resolve() (see the [Simple", "data requirement. If this element is not provided, a Patient subject is assumed.", "List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results that are required (uses the", "the value set of interest for a particular element of the data. Each", "# Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints on", "requirements that SHALL be met as part of the definition of the extension.", "profile definition. \"profile\": List[FHIR_canonical], # The intended subjects of the data requirement. If", "that SHALL be met as part of the definition of the extension. \"extension\":", "any implementer can define an extension, there is a set of requirements that", "and must be supported by the consumer in order to obtain an effective", "string value that does not contain spaces. \"id\": FHIR_string, # May be used", "to provide values for it if they are available. The value of mustSupport", "\"id\": FHIR_string, # May be used to represent additional information that is not", "required data item for evaluation in terms of the type of data, and", "import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import", "\"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, # Specifies the order of", "for specific elements. Each date filter specifies an additional constraint on the data,", "of a resource. For profiles, this value is set to the type of", "not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results that are", "information that is not part of the basic definition of the element. To", "the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport", "from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from", "not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date filters specify additional constraints on the data", "a resource (for internal references). This may be any string value that does", "Specifies a maximum number of results that are required (uses the _count search", "of requirements that SHALL be met as part of the definition of the", "system must understand the element and be able to provide values for it", "are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results", "This may be any string value that does not contain spaces. \"id\": FHIR_string,", "element and be able to provide values for it if they are available.", "this element is not provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, #", "typing import Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import", "to obtain an effective evaluation. This does not mean that a value is", "FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter", "value is set to the type of the base resource of the profile.", "implementer can define an extension, there is a set of requirements that SHALL", "FHIR_code, # Extensions for type \"_type\": FHIR_Element, # The profile of the required", "data. Each code filter defines an additional constraint on the data, i.e. code", "SHALL consist only of identifiers, constant indexers, and .resolve() (see the [Simple FHIRPath", "extension, there is a set of requirements that SHALL be met as part", "number of results that are required (uses the _count search parameter). \"limit\": FHIR_positiveInt,", "is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements of the type are", "mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints on the data, specifying", "# Specifies the order of the results to be returned. \"sort\": List[FHIR_DataRequirement_Sort], },", "required data, specified as the type name of a resource. For profiles, this", "from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Describes a required data", "filter specifies an additional constraint on the data, i.e. date filters are AND'ed,", "is not part of the basic definition of the element. To make the", "the DataRequirement. The path SHALL consist only of identifiers, constant indexers, and .resolve()", "# Indicates that specific elements of the type are referenced by the knowledge", "definition and use of extensions. Though any implementer can define an extension, there", "The intended subjects of the data requirement. If this element is not provided,", "from typing import Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code", "\"_type\": FHIR_Element, # The profile of the required data, specified as the uri", "particular element of the data. Each code filter defines an additional constraint on", "provided, a Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements", "type of the required data, specified as the type name of a resource.", "any string value that does not contain spaces. \"id\": FHIR_string, # May be", "date filter specifies an additional constraint on the data, i.e. date filters are", "on the data, specifying the value set of interest for a particular element", "the definition and use of extensions. Though any implementer can define an extension,", "an additional constraint on the data, i.e. date filters are AND'ed, not OR'ed.", "\"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results that are required (uses", "from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from", "{ # Unique id for the element within a resource (for internal references).", "definition of the element. To make the use of extensions safe and manageable,", "of the data. Each code filter defines an additional constraint on the data,", "be used to represent additional information that is not part of the basic", "value is required for this element, only that the consuming system must understand", "the type of the DataRequirement. The path SHALL consist only of identifiers, constant", "specifying the value set of interest for a particular element of the data.", "filter defines an additional constraint on the data, i.e. code filters are AND'ed,", "does not mean that a value is required for this element, only that", "# The intended subjects of the data requirement. If this element is not", ".FHIR_string import FHIR_string # Describes a required data item for evaluation in terms", "subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements of the type", "filters specify additional constraints on the data, specifying the value set of interest", "filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id for", "of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id for the", "they are available. The value of mustSupport SHALL be a FHIRPath resolveable on", "the data, i.e. code filters are AND'ed, not OR'ed. \"codeFilter\": List[FHIR_DataRequirement_CodeFilter], # Date", "For profiles, this value is set to the type of the base resource", "terms of the type of data, and optional code or date-based filters of", "only of identifiers, constant indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for", "the type of data, and optional code or date-based filters of the data.", "set to the type of the base resource of the profile. \"type\": FHIR_code,", "that is not part of the basic definition of the element. To make", "be a FHIRPath resolveable on the type of the DataRequirement. The path SHALL", "details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify", "a FHIRPath resolveable on the type of the DataRequirement. The path SHALL consist", "part of the basic definition of the element. To make the use of", "as the uri of the profile definition. \"profile\": List[FHIR_canonical], # The intended subjects", "import Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code", "additional information that is not part of the basic definition of the element.", ".FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter", "strict set of governance applied to the definition and use of extensions. Though", "resource. For profiles, this value is set to the type of the base", "DataRequirement. The path SHALL consist only of identifiers, constant indexers, and .resolve() (see", ".FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort", "and manageable, there is a strict set of governance applied to the definition", "\"FHIR_DataRequirement\", { # Unique id for the element within a resource (for internal", "element, only that the consuming system must understand the element and be able", "to the definition and use of extensions. Though any implementer can define an", "the data. Each code filter defines an additional constraint on the data, i.e.", "# The profile of the required data, specified as the uri of the", "constraint on the data, i.e. date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter],", "a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the", "for evaluation in terms of the type of data, and optional code or", "required data, specified as the uri of the profile definition. \"profile\": List[FHIR_canonical], #", "AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results that", "manageable, there is a strict set of governance applied to the definition and", "(for internal references). This may be any string value that does not contain", "FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference", "To make the use of extensions safe and manageable, there is a strict", "evaluation. This does not mean that a value is required for this element,", "FHIR_Reference from .FHIR_string import FHIR_string # Describes a required data item for evaluation", "contain spaces. \"id\": FHIR_string, # May be used to represent additional information that", "Extensions for type \"_type\": FHIR_Element, # The profile of the required data, specified", "constant indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\":", "of the required data, specified as the uri of the profile definition. \"profile\":", "This does not mean that a value is required for this element, only", "the consumer in order to obtain an effective evaluation. This does not mean", "extensions safe and manageable, there is a strict set of governance applied to", "\"profile\": List[FHIR_canonical], # The intended subjects of the data requirement. If this element", "constraints on the data, specifying the value set of interest for a particular", "= TypedDict( \"FHIR_DataRequirement\", { # Unique id for the element within a resource", ".FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element", "uri of the profile definition. \"profile\": List[FHIR_canonical], # The intended subjects of the", "for limit \"_limit\": FHIR_Element, # Specifies the order of the results to be", "of the type of data, and optional code or date-based filters of the", "governance applied to the definition and use of extensions. Though any implementer can", "type are referenced by the knowledge module and must be supported by the", "\"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element, # The profile of the", "on the data, i.e. date filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], #", "subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the data requirement.", "for full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code", "from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string #", "SHALL be a FHIRPath resolveable on the type of the DataRequirement. The path", "optional code or date-based filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", {", "type name of a resource. For profiles, this value is set to the", "import FHIR_Reference from .FHIR_string import FHIR_string # Describes a required data item for", "parameter). \"limit\": FHIR_positiveInt, # Extensions for limit \"_limit\": FHIR_Element, # Specifies the order", "code or date-based filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { #", "FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort", "for the element within a resource (for internal references). This may be any", "a strict set of governance applied to the definition and use of extensions.", "specifies an additional constraint on the data, i.e. date filters are AND'ed, not", "the data requirement. If this element is not provided, a Patient subject is", "definition of the extension. \"extension\": List[Any], # The type of the required data,", "data item for evaluation in terms of the type of data, and optional", "additional constraints on the data in terms of the applicable date range for", "additional constraint on the data, i.e. code filters are AND'ed, not OR'ed. \"codeFilter\":", "met as part of the definition of the extension. \"extension\": List[Any], # The", "# Extensions for limit \"_limit\": FHIR_Element, # Specifies the order of the results", "import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Describes a", "Unique id for the element within a resource (for internal references). This may", "terms of the applicable date range for specific elements. Each date filter specifies", "item for evaluation in terms of the type of data, and optional code", "of governance applied to the definition and use of extensions. Though any implementer", "identifiers, constant indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple) for full details).", "that the consuming system must understand the element and be able to provide", ".FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string", "not mean that a value is required for this element, only that the", "must understand the element and be able to provide values for it if", "the type of the base resource of the profile. \"type\": FHIR_code, # Extensions", "is required for this element, only that the consuming system must understand the", "The path SHALL consist only of identifiers, constant indexers, and .resolve() (see the", "required for this element, only that the consuming system must understand the element", "FHIR_Element, # The profile of the required data, specified as the uri of", "\"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints on the data, specifying the", "Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import", "Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from", "not contain spaces. \"id\": FHIR_string, # May be used to represent additional information", "List[Any], # The type of the required data, specified as the type name", "the definition of the extension. \"extension\": List[Any], # The type of the required", "the type are referenced by the knowledge module and must be supported by", "only that the consuming system must understand the element and be able to", "data in terms of the applicable date range for specific elements. Each date", "supported by the consumer in order to obtain an effective evaluation. This does", "date-based filters of the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id", "and use of extensions. Though any implementer can define an extension, there is", "the data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id for the element", "\"extension\": List[Any], # The type of the required data, specified as the type", "as the type name of a resource. For profiles, this value is set", "results that are required (uses the _count search parameter). \"limit\": FHIR_positiveInt, # Extensions", "from .FHIR_DataRequirement_CodeFilter import FHIR_DataRequirement_CodeFilter from .FHIR_DataRequirement_DateFilter import FHIR_DataRequirement_DateFilter from .FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from", ".FHIR_DataRequirement_Sort import FHIR_DataRequirement_Sort from .FHIR_Element import FHIR_Element from .FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference", "this value is set to the type of the base resource of the", "base resource of the profile. \"type\": FHIR_code, # Extensions for type \"_type\": FHIR_Element,", "if they are available. The value of mustSupport SHALL be a FHIRPath resolveable", "it if they are available. The value of mustSupport SHALL be a FHIRPath", "Patient subject is assumed. \"subjectReference\": FHIR_Reference, # Indicates that specific elements of the", "elements. Each date filter specifies an additional constraint on the data, i.e. date", "spaces. \"id\": FHIR_string, # May be used to represent additional information that is", "from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from", "id for the element within a resource (for internal references). This may be", "the element within a resource (for internal references). This may be any string", "import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_DataRequirement_CodeFilter import", "is set to the type of the base resource of the profile. \"type\":", "data. FHIR_DataRequirement = TypedDict( \"FHIR_DataRequirement\", { # Unique id for the element within", "of the element. To make the use of extensions safe and manageable, there", "OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of results that are required", "can define an extension, there is a set of requirements that SHALL be", ".FHIR_positiveInt import FHIR_positiveInt from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Describes", "Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints on the", "# Date filters specify additional constraints on the data in terms of the", "used to represent additional information that is not part of the basic definition", "for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional constraints on the data,", "element is not provided, a Patient subject is assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The", "filters are AND'ed, not OR'ed. \"dateFilter\": List[FHIR_DataRequirement_DateFilter], # Specifies a maximum number of", "definition. \"profile\": List[FHIR_canonical], # The intended subjects of the data requirement. If this", "there is a strict set of governance applied to the definition and use", "FHIRPath Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element],", "Profile](fhirpath.html#simple) for full details). \"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], #", "\"_limit\": FHIR_Element, # Specifies the order of the results to be returned. \"sort\":", "\"mustSupport\": List[FHIR_string], # Extensions for mustSupport \"_mustSupport\": List[FHIR_Element], # Code filters specify additional", "List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept", "Each code filter defines an additional constraint on the data, i.e. code filters", "profile of the required data, specified as the uri of the profile definition.", "in terms of the applicable date range for specific elements. Each date filter", "code filter defines an additional constraint on the data, i.e. code filters are", "consist only of identifiers, constant indexers, and .resolve() (see the [Simple FHIRPath Profile](fhirpath.html#simple)", "applicable date range for specific elements. Each date filter specifies an additional constraint", "Each date filter specifies an additional constraint on the data, i.e. date filters", "specified as the uri of the profile definition. \"profile\": List[FHIR_canonical], # The intended", "type \"_type\": FHIR_Element, # The profile of the required data, specified as the", "TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_code import FHIR_code from .FHIR_CodeableConcept import FHIR_CodeableConcept", "of the base resource of the profile. \"type\": FHIR_code, # Extensions for type", "understand the element and be able to provide values for it if they", "be able to provide values for it if they are available. The value", "assumed. \"subjectCodeableConcept\": FHIR_CodeableConcept, # The intended subjects of the data requirement. If this", "to represent additional information that is not part of the basic definition of", "Date filters specify additional constraints on the data in terms of the applicable", "on the data in terms of the applicable date range for specific elements." ]
[ "requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS", "while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response): break", "Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS = 100", "LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS", "'game_modes' in question and len(question['game_modes']) > 0 \\ and 'options' in question def", "= [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not", "valid_question(question): return 'id' in question \\ and 'title' in question \\ and 'game_type'", "import json from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}'", "all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if", "HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503,", "> 0 def valid_question(question): return 'id' in question \\ and 'title' in question", "import requests import json from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL", "\\ and 'game_type' in question and question['game_type'] is not None \\ and 'game_modes'", "in question \\ and 'game_type' in question and question['game_type'] is not None \\", "outer_questions in all_questions for question in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content))", "\\ and 'title' in question \\ and 'game_type' in question and question['game_type'] is", "url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset", "has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for", "503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session()", "has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in question \\ and", "def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset", "in all_questions for question in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) >", "= 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET =", "question in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question):", "all_questions for question in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0", "in question \\ and 'title' in question \\ and 'game_type' in question and", "TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for question in outer_questions if valid_question(question)]", "= LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset +=", "from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504]", "in question and len(question['game_modes']) > 0 \\ and 'options' in question def set_question(question):", "= [408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL):", "def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type': question['game_type'], 'options': question['options'], 'game_modes': question['game_modes']}", "response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question)", "[set_question(question) for outer_questions in all_questions for question in outer_questions if valid_question(question)] def has_content(response):", "0 def valid_question(question): return 'id' in question \\ and 'title' in question \\", "len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in question \\ and 'title' in", "import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS =", "502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s =", "504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries", "= requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions", "valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in question", "outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return 'id'", "= INIT_OFFSET all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response =", "0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries))", "and 'game_type' in question and question['game_type'] is not None \\ and 'game_modes' in", "is not None \\ and 'game_modes' in question and len(question['game_modes']) > 0 \\", "and 'game_modes' in question and len(question['game_modes']) > 0 \\ and 'options' in question", "= Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while", "question and len(question['game_modes']) > 0 \\ and 'options' in question def set_question(question): return", "return [set_question(question) for outer_questions in all_questions for question in outer_questions if valid_question(question)] def", "s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions", "'id' in question \\ and 'title' in question \\ and 'game_type' in question", "in question and question['game_type'] is not None \\ and 'game_modes' in question and", "json from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES", "\\ and 'options' in question def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type':", "None \\ and 'game_modes' in question and len(question['game_modes']) > 0 \\ and 'options'", "get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset =", "offset = INIT_OFFSET all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response", "offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for question in outer_questions", "TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries =", "question \\ and 'game_type' in question and question['game_type'] is not None \\ and", "s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET", "> 0 \\ and 'options' in question def set_question(question): return {'id': question['id'], 'title':", "0 \\ and 'options' in question def set_question(question): return {'id': question['id'], 'title': question['title'],", "return 'id' in question \\ and 'title' in question \\ and 'game_type' in", "[] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response):", "INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES)", "break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for question", "requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408,", "= 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://',", "from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES =", "and 'options' in question def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type': question['game_type'],", "question def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type': question['game_type'], 'options': question['options'], 'game_modes':", "100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5, backoff_factor=1,", "and 'title' in question \\ and 'game_type' in question and question['game_type'] is not", "status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while True: url =", "True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content))", "and question['game_type'] is not None \\ and 'game_modes' in question and len(question['game_modes']) >", "+= TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for question in outer_questions if", "return len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in question \\ and 'title'", "question['game_type'] is not None \\ and 'game_modes' in question and len(question['game_modes']) > 0", "def valid_question(question): return 'id' in question \\ and 'title' in question \\ and", "requests import json from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL =", "'options' in question def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type': question['game_type'], 'options':", "offset) response = s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return", "for question in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def", "and len(question['game_modes']) > 0 \\ and 'options' in question def set_question(question): return {'id':", "'title' in question \\ and 'game_type' in question and question['game_type'] is not None", "s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS,", "= 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s = requests.Session() retries = Retry(total=5,", "question \\ and 'title' in question \\ and 'game_type' in question and question['game_type']", "if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in", "all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions for question in", "= s.get(url) if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for", "'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0", "import HTTPAdapter from requests.packages.urllib3.util.retry import Retry LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502,", "backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while True: url", "HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset)", "def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return 'id' in question \\", "not None \\ and 'game_modes' in question and len(question['game_modes']) > 0 \\ and", "requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions =", "if not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in", "\\ and 'game_modes' in question and len(question['game_modes']) > 0 \\ and 'options' in", "len(question['game_modes']) > 0 \\ and 'options' in question def set_question(question): return {'id': question['id'],", "LOLQUIZ_CMS_URL = 'https://lolquiz-cms.herokuapp.com/questions?_sort=id&_limit={}&_start={}' HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET", "in question def set_question(question): return {'id': question['id'], 'title': question['title'], 'game_type': question['game_type'], 'options': question['options'],", "'game_type' in question and question['game_type'] is not None \\ and 'game_modes' in question", "INIT_OFFSET all_questions = [] while True: url = LOLQUIZ_CMS_URL.format(TOTAL_QUESTIONS, offset) response = s.get(url)", "Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = [] while True:", "for outer_questions in all_questions for question in outer_questions if valid_question(question)] def has_content(response): return", "retries = Retry(total=5, backoff_factor=1, status_forcelist=HTTP_STATUS_ERROR_CODES) s.mount('https://', HTTPAdapter(max_retries=retries)) offset = INIT_OFFSET all_questions = []", "HTTP_STATUS_ERROR_CODES = [408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def", "[408, 502, 503, 504] TOTAL_QUESTIONS = 100 INIT_OFFSET = 0 def get_questions(url=LOLQUIZ_CMS_URL): s", "not has_content(response): break all_questions.append(json.loads(response.content)) offset += TOTAL_QUESTIONS return [set_question(question) for outer_questions in all_questions", "question and question['game_type'] is not None \\ and 'game_modes' in question and len(question['game_modes'])", "in outer_questions if valid_question(question)] def has_content(response): return len(json.loads(response.content)) > 0 def valid_question(question): return" ]
[ "音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype :", "= -1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count))", "Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit ==", "def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str :", "st.session_state: st.session_state.game_count = 1 if 'exp' not in st.session_state: st.session_state.exp = 0 if", "self.hit = 0 self.blow = 0 for i in range(self.digits): if num[i] ==", ": なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not", "round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200): if i**3/3 <= st.session_state.exp and", "='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3)", "int digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans :", ": なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype :", "place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None", "col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num", "import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() ->", ": return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 :", "手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return : なし \"\"\" #self._music_stop()", "{} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\"", "title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return : なし \"\"\" pygame.mixer.init() #", "if num[i] in ans: self.blow += 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム", "st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i", "Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\"", "進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num", "= get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not", "hit : 数字のhit数 :param int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def", ": なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回)", ": 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int hit : 数字のhit数 :param", "経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return : なし \"\"\"", "{} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode()", "self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3)", "st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20:", "= round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200): if i**3/3 <= st.session_state.exp", "-> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return :", "_voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return : なし \"\"\" pygame.mixer.init()", "sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype :", "\"\"\" # st.session_state.win_in_a_row += 1 level_up = False evolution = False new_exp =", "else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img)", "args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None: runner =", "self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume = 0.3 if", "num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str : return :", "0 self.blow = 0 for i in range(self.digits): if num[i] == ans[i]: self.hit", "if num[i] == ans[i]: self.hit += 1 else: if num[i] in ans: self.blow", "col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count = 1 if 'exp'", "= \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image)", ": rtype : None : return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history)", "0 if 'history' not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name =", ": rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title)", "parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans=", "\"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state:", ": return : なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み", ": ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def", "new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num = 1,", "str: \"\"\"自分が当てる答えをつくる : rtype : str : return : ans \"\"\" ans_list =", "ans[i]: self.hit += 1 else: if num[i] in ans: self.blow += 1 def", "!!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype :", "return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype", "数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str", "= (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume = 0.3 if ans", "in st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history= {} name =", "rtype : None : return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\")", "on october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import random import argparse", "= random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param", ": rtype : None : return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def", "= round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level != st.session_state.level: level_up =", "title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") #", "rtype : None : return : なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\")", "-> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return :", "self.hit += 1 else: if num[i] in ans: self.blow += 1 def _play_game_manual(self)", "対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return : なし \"\"\" #self._music_stop() place", "st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype :", "+= 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype :", ": None : return : なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title)", "= None self.volume = 0.3 if ans is not None: self.ans = ans", "なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None", "= Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title", "rtype : None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num", "== ans[i]: self.hit += 1 else: if num[i] in ans: self.blow += 1", "args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count", "random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int", "None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1,", "0 st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype", "<= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level =", "+= 1 level_up = False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp +=", "1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: #", "'game_count' not in st.session_state: st.session_state.game_count = 1 if 'exp' not in st.session_state: st.session_state.exp", "title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None :", ": UTF-8 \"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created", "なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self)", "正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype", "= \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img =", "st.session_state: st.session_state.exp = 0 if 'level' not in st.session_state: st.session_state.level = 1 if", "1 level_up = False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp", "col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値,", "+= new_exp for i in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp <", "st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える,", "time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1)", "st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace:", "rtype : None : return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ.", "'exp' not in st.session_state: st.session_state.exp = 0 if 'level' not in st.session_state: st.session_state.level", ": なし \"\"\" self.hit = 0 self.blow = 0 for i in range(self.digits):", "= 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume =", "import Image import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4])", "not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0", "= 1 if 'exp' not in st.session_state: st.session_state.exp = 0 if 'level' not", "st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"])", "\"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else:", ": 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param", "= col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else:", ":rtype : argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args", "def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype", "st.session_state.exp = 0 if 'level' not in st.session_state: st.session_state.level = 1 if 'win_in_a_row'", "\"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param", "\"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num", "= 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num]", "# if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if", "def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\" parser", "def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str : return : ans", "col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits", "None self.blow = None self.volume = 0.3 if ans is not None: self.ans", "None: \"\"\"再生中の音楽停止 : rtype : None : return : なし \"\"\" pygame.mixer.music.stop() #", ": 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5", "経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row", "int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return : なし", "return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) :", "is not None: self.ans = ans else: self.ans = self._define_answer() if 'ans' not", "random import argparse import time from PIL import Image import streamlit as st", "col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0", "int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits", "st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history'", ":param str num : こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int blow", "title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row))", "'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual() if __name__ == \"__main__\":", ": return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if", "self.blow += 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype", "streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0", "自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int", "ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int,", "print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if", "self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None:", "= parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser()", "Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title =", "= name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image", "= Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num", "Image import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num", "= \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int", "argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\")", "args = parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args =", "time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif')", "\"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if", "self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans)", "= [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{}", "= None self.blow = None self.volume = 0.3 if ans is not None:", "st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history' not", "# 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None:", "for i in range(self.digits): if num[i] == ans[i]: self.hit += 1 else: if", "if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3)", "st.session_state.level = 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count'", "2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name))", "st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level", "20: image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level))", "if 'exp' not in st.session_state: st.session_state.exp = 0 if 'level' not in st.session_state:", "+= 1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser()", ": {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param set", "st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル", "Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\")", "= {} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace", "args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num", "print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {}", "'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state: st.session_state.turn_count=", "= col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level", ": rtype : str : return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits)", "= \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img", "音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None : return :", "None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return : なし \"\"\" print(\"------------------------\")", "col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img)", "None : return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用", "comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int", "if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image)", "st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return :", "col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level <", "in ans: self.blow += 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示", "(i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level != st.session_state.level:", "なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num", "import argparse import time from PIL import Image import streamlit as st import", "= 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not", ":param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 =", "Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count = 1 if", "\"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit =", "print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算", "= Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3)", "if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history=", "in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1", "playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定", "2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return : なし \"\"\" self.hit", "== 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if", "st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name", "print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う :", ":param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict] my_history", "= True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後,", "self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav')", ": argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args =", "\"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数", "pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None :", "-> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return : なし \"\"\"", "0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) :", "new_level = i if new_level != st.session_state.level: level_up = True if new_level ==", "= self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title", "return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト :", "pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納", "self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\"", "self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count +=", "1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title =", "return : なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0:", "< 20: image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル :", ": return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count))", "runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num", "\"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img =", "st.session_state.game_count = 1 if 'exp' not in st.session_state: st.session_state.exp = 0 if 'level'", "== 20: evolution = True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self)", "List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int hit :", "None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return : なし", "1 else: if num[i] in ans: self.blow += 1 def _play_game_manual(self) -> None:", "Created on october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import random import", "if 'game_count' not in st.session_state: st.session_state.game_count = 1 if 'exp' not in st.session_state:", "st.session_state.exp += new_exp for i in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp", "Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else:", "1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img", "# 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None : return", "if 'level' not in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in st.session_state:", "= Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード", "= \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level))", ": {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history", ": {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans", "not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 =", "self.blowに格納 : rtype : None : return : なし \"\"\" self.hit = 0", "coding : UTF-8 \"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021", "else: self.ans = self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num =", "初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止", "= num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str : return", "evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200):", "col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13)", "st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if", "なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3)", "Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count = 1", "\"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif')", "= pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit,", "+= 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count))", "return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title =", "col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\")", "num : こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int blow : 数字のblow数", "ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param", ":param int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None:", "parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main() ->", ": なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop()", "_define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str : return : ans \"\"\"", "None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None", "-> None: \"\"\"再生中の音楽停止 : rtype : None : return : なし \"\"\" pygame.mixer.music.stop()", "def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype :", "試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return : なし", "= 0.3 if ans is not None: self.ans = ans else: self.ans =", "進化とレベルアップの時は追加エフェクト : rtype : None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information()", "_show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None", "初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用", "col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count =", "self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp))", "\"\"\" args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans", "\"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title =", "not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0:", "new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示", "col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def", "\"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return : なし \"\"\"", "_check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return", "ans else: self.ans = self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num", "i in range(self.digits): if num[i] == ans[i]: self.hit += 1 else: if num[i]", ": 数字のhit数 :param int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None)", "int hit : 数字のhit数 :param int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\"", "if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self) ->", "-> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return :", "return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up = False evolution =", "None : return : なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) #", "place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num", "獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up = False evolution = False new_exp", "st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans = self._define_answer() def", "level_up = False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for", "-> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None", "col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count", "sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し,", ": return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num)", "time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num", "= \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title", "if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) ->", "not in st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history= {} name", "= 1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history' not in", "1 if 'exp' not in st.session_state: st.session_state.exp = 0 if 'level' not in", "pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) ->", "Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1))", "if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp)", "in st.session_state: st.session_state.exp = 0 if 'level' not in st.session_state: st.session_state.level = 1", "\"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None :", "remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level != st.session_state.level: level_up", "Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合", "= col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title =", "new_level != st.session_state.level: level_up = True if new_level == 20: evolution = True", "import random import argparse import time from PIL import Image import streamlit as", "st.session_state.ans= self.ans self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype :", "image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2", "rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up", "in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\"", "return : なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume)", "col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\")", "\"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2)", "main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\")", "get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None:", "not in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row =", "# 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return :", "col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image", "\"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title):", "history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め,", "if st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title", "else: if num[i] in ans: self.blow += 1 def _play_game_manual(self) -> None: \"\"\"", "Created by <NAME>, <NAME>, <NAME> \"\"\" import random import argparse import time from", ":param int digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans", ": rtype : None : return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\")", "\"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num =", "place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title", "pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) ->", "13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import random import argparse import time", "False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in", "not None: self.ans = ans else: self.ans = self._define_answer() if 'ans' not in", "'ans' not in st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self) -> str:", "おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype", "0 for i in range(self.digits): if num[i] == ans[i]: self.hit += 1 else:", "終わったら対戦終了と結果の表示 : rtype : None : return : なし \"\"\" #self._music_stop() place =", ": None : return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です.", "\"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None)", "if new_level != st.session_state.level: level_up = True if new_level == 20: evolution =", "col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\")", "int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return : なし \"\"\" pygame.mixer.init() #", "pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return", "再生の終了 def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return : なし", "True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分)", "col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans = self._define_answer()", "str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up = False", "not in st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる", "対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution =", "col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title", "'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state: st.session_state.history= {}", "if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title =", "def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None :", "レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return : なし \"\"\" col1.title(\"Welcome", "= new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル,", "st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1,", "Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num =", "col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int", ": None : return : なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if", "self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >=", ": なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play()", "20: evolution = True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) ->", "self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow", "= 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2)", "col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num =", "self.blow = None self.volume = 0.3 if ans is not None: self.ans =", "数字のhit数 :param int blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) ->", "rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定 sound =", "None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return : なし", "0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"):", "by <NAME>, <NAME>, <NAME> \"\"\" import random import argparse import time from PIL", "{} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits:", "なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def", "print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) :", "num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return : なし \"\"\"", "0 if 'level' not in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in", "Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\")", ": こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int blow : 数字のblow数 :param", "range(self.digits): if num[i] == ans[i]: self.hit += 1 else: if num[i] in ans:", "in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3", "1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in", "args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is", "new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype", "-1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\")", "= 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual() if __name__ ==", "set Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict] my_history :", "ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype", ": None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num =", "my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int hit : 数字のhit数", "time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count", "< (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level !=", "def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num =", "def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None :", "# coding : UTF-8 \"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october", "_play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None", "st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow))", ": return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return", "お互いの結果を表示(vscode上に表示する分) : rtype : None : return : なし \"\"\" print(\"------------------------\") print(\"show history\")", "\"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return :", "self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None :", "Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import random", ": return : なし \"\"\" self.hit = 0 self.blow = 0 for i", "'level' not in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row", "\"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return : なし \"\"\"", "image = Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数", "None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num", "お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return : なし", ": なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\")", "col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\")", "False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200): if i**3/3", "st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light)", "None : return : なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count", "PIL import Image import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6", "True if new_level == 20: evolution = True st.session_state.level = new_level break return", "<reponame>HayatoNatural/NEDO-Hit-Blow-teamF # coding : UTF-8 \"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on", "pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None:", "argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン", "Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1,", "round((i+1)**3/3 - st.session_state.exp) new_level = i if new_level != st.session_state.level: level_up = True", "{}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数", "print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める", "st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype", ": rtype : None : return : なし \"\"\" self.hit = 0 self.blow", "= \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\")", "勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return : なし \"\"\"", "# 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype", "初期化しておく(マジックコマンド的な) : rtype : None : return : なし \"\"\" col1.title(\"Welcome to Hit&Blow", "return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count'", "なし \"\"\" self.hit = 0 self.blow = 0 for i in range(self.digits): if", "= self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値", ">= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution:", "コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def", "import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num =", ":return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return", "=st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数,", "self.ans self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str", "new_level == 20: evolution = True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def", "print(button_num) initialize_streamlit() if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner =", "from PIL import Image import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1])", "ans: self.blow += 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 :", "st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav')", "進化やレベルアップの判定も行う : rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row +=", "(\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume = 0.3 if ans is", "def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None", "def _voice_play(self,num:int, title): \"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return : なし \"\"\"", "# 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 :", ":param int hit : 数字のhit数 :param int blow : 数字のblow数 :param int volume:音量(0~1で変更)", "= Image.open(pic_url1) col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 :", "print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う", "st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2", "数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\"", "None : return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます!", "self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image =", "\"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>,", "argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args()", "<NAME>, <NAME>, <NAME> \"\"\" import random import argparse import time from PIL import", ": 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param", "音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype", "if 'history' not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name", "= Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 =", "print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str:", "= \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else: image =", "def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return :", "level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\")", "pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1) col4.image(image) else: image", "col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light =", "if 'win_in_a_row' not in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state:", "self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume", "col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner", "File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>, <NAME>,", "{} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return", "img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop()", "= 0 st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ", "rtype : None : return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int,", "self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num =", "= Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count))", "!!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です", "0.3 if ans is not None: self.ans = ans else: self.ans = self._define_answer()", ": comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param", "0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav')", "自動一人対戦の数当てモード :param int digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str", "\"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) ->", "# col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light", "level_up = True if new_level == 20: evolution = True st.session_state.level = new_level", "経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution", "='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"]", "= -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1", "hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\"", "if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up:", "col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self)", "else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav')", "\"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return", "to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count =", "runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num =", ": str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up =", ": None : return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み", "{} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit", "= 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な)", "pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image = Image.open(pic_url1)", "self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと)", "== self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後,", "\"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return : なし \"\"\" print(\"------------------------\") print(\"show", "経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count = 1 if 'exp' not", "数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict]", "col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1", "\"\"\" self.hit = 0 self.blow = 0 for i in range(self.digits): if num[i]", "self.blow = 0 for i in range(self.digits): if num[i] == ans[i]: self.hit +=", "str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {}", "in st.session_state: st.session_state.win_in_a_row = 1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if", "なし \"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def", "5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow = None self.volume = 0.3", "1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル :", "if ans is not None: self.ans = ans else: self.ans = self._define_answer() if", "col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count", "image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\")", "st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if", "in st.session_state: st.session_state.game_count = 1 if 'exp' not in st.session_state: st.session_state.exp = 0", "\"\"\"自分が当てる答えをつくる : rtype : str : return : ans \"\"\" ans_list = random.sample(self.Tuple_16,", ": None : return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\")", "数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16", "in st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる :", "for i in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp", "-1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual() if __name__", "ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字", ":param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return : なし \"\"\" pygame.mixer.init()", "= \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if", ": None : return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了 def _voice_play(self,num:int, title):", "= 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2:", ":param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num : こちらが予想した相手の数字 :param int hit", "title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\",", "1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね, 進化した!\") pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image)", "\"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row", "self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\")", "-1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!!", "UTF-8 \"\"\" File Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by", "if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if", "状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return :", "not in st.session_state: st.session_state.game_count = 1 if 'exp' not in st.session_state: st.session_state.exp =", "ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生", "-> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow,", "range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 -", "{}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans =", "parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args", "pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None", "col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons()", "name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if st.session_state.level < 20: image =", "num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num)", "Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit()", ": return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop() self._play_song(num = -1, title", "int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\")", "その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None : return : なし \"\"\" self.hit =", "import time from PIL import Image import streamlit as st import pygame st.set_page_config(layout=\"wide\")", "return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list) return ans", "_play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None : return", "self.hit = None self.blow = None self.volume = 0.3 if ans is not", "break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト", "__init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow", "なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in", "None: self.ans = ans else: self.ans = self._define_answer() if 'ans' not in st.session_state:", "こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int blow : 数字のblow数 :param int", "col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count +=", "\"\"\"再生中の音楽停止 : rtype : None : return : なし \"\"\" pygame.mixer.music.stop() # 再生の終了", "i in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp =", "{}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history =", "rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) #", "1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始, 終わったら対戦終了と結果の表示 : rtype : None", "str num : こちらが予想した相手の数字 :param int hit : 数字のhit数 :param int blow :", "= i if new_level != st.session_state.level: level_up = True if new_level == 20:", "if new_level == 20: evolution = True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution", "連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return : なし \"\"\" col1.title(\"Welcome to", "return : なし \"\"\" self.hit = 0 self.blow = 0 for i in", "\"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit,", "october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import random import argparse import", "button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し,", "1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] =", "col6.subheader(\"勝利だ,おめでとう!\") col6.subheader(\"正解は‥【{}】{}回で正解できた!\".format(self.num,st.session_state.turn_count)) col6.subheader(\"\") # if st.session_state.win_in_a_row >= 2: # col6.subheader(\"すごいぞ,{}連勝だ!その調子!\".format(st.session_state.win_in_a_row)) time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp))", "return args def main() -> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans", "def _music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None : return : なし", "self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title =", "# st.session_state.win_in_a_row += 1 level_up = False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count)", "is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num) if st.session_state.turn_count ==", "self._music_stop() self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\")", "return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) #", "= -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual() if", "st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 =", "None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None :", "<NAME> \"\"\" import random import argparse import time from PIL import Image import", "+= 1 else: if num[i] in ans: self.blow += 1 def _play_game_manual(self) ->", "self._play_song(num = -1, title = \"bgm/winner.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/winner.wav') col6.subheader(\"\") col6.subheader(\"勝利だ,おめでとう!\")", "time from PIL import Image import streamlit as st import pygame st.set_page_config(layout=\"wide\") col1,col2", "st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく", "= 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル", "= argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main() -> None:", "勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" #", "=st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル,", "= 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\")", "== 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title", "col4.image(image) else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class", "else: image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual:", "_get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return", "'history' not in st.session_state: st.session_state.history= {} name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1", "self.volume = 0.3 if ans is not None: self.ans = ans else: self.ans", ": return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up = False evolution", "argparse import time from PIL import Image import streamlit as st import pygame", "= True if new_level == 20: evolution = True st.session_state.level = new_level break", "\"\"\" pygame.mixer.init() # 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans)", "initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype :", "\"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args def main()", "ans is not None: self.ans = ans else: self.ans = self._define_answer() if 'ans'", "evolution = True st.session_state.level = new_level break return new_exp,remaining_exp,level_up,evolution def _show_result_streamlit(self) -> None:", "- st.session_state.exp) new_level = i if new_level != st.session_state.level: level_up = True if", "num[i] == ans[i]: self.hit += 1 else: if num[i] in ans: self.blow +=", "image = Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow", "return : なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\")", "col6.subheader(\"レベルアップだ!\") self._music_stop() self._play_song(num = 1,title = \"bgm/level_up.wav\") img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp))", "num[i] in ans: self.blow += 1 def _play_game_manual(self) -> None: \"\"\" 手動一人対戦の数当てゲーム 対戦中の表示を出してから部屋を作成して答えをポストして対戦開始,", "1 st.session_state.turn_count = 0 st.session_state.history = {} st.session_state.ans = self._define_answer() def get_parser() ->", "None : return : なし \"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume)", "Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴", ": str : return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans =", "col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num = 1,title = \"bgm/evolution.mp3\") time.sleep(3) else: col6.subheader(\"レベルアップだ!\")", "new_exp for i in range(200): if i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3:", "digits : 数の桁数 :param set Tuple_16 : 数に使う16進数の数字の集合 :param str ans : comの答え(自分が当てる数字)", "rtype : None : return : なし \"\"\" self.hit = 0 self.blow =", "\"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title = \"bgm/Battle.wav\") print(\"aaaaa\")", "ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit() if args.ans is not None: runner", ": rtype : None : return : なし \"\"\" #self._music_stop() place = col6.empty()", "_show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return : なし", "st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit()", "class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param set Tuple_16 :", "= False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i", ": コマンド値 \"\"\" parser = argparse.ArgumentParser(description=\"Hit&Blow, 数当てゲーム\") parser.add_argument(\"--ans\",default=None) args = parser.parse_args() return args", "_music_stop(self) -> None: \"\"\"再生中の音楽停止 : rtype : None : return : なし \"\"\"", "-> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit = None self.blow =", "= ans else: self.ans = self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans", ": rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定 sound", "self.digits: print(\"!! 正解です !!\") place.write(\"対戦終了!\") self._show_result_vscode() self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分)", "get_parser() -> argparse.Namespace: \"\"\"コマンドライン引数を解析したものを持つ :rtype : argparse.Namespace :return : コマンド値 \"\"\" parser =", "<NAME>, <NAME> \"\"\" import random import argparse import time from PIL import Image", "self.ans = ans else: self.ans = self._define_answer() if 'ans' not in st.session_state: st.session_state.ans=", "None : return : なし \"\"\" self.hit = 0 self.blow = 0 for", ": return : なし \"\"\" #self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count ==", "\"\"\" import random import argparse import time from PIL import Image import streamlit", "\"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\"", "str ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num :", "-> None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None :", "None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num) initialize_streamlit()", "1 if 'turn_count' not in st.session_state: st.session_state.turn_count= 0 if 'history' not in st.session_state:", "Image.open(pic_url2) col4.image(image) col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param", "str : return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans = \"\".join(ans_list)", "= Playgame_solo_manual(num=num) if st.session_state.turn_count == 0: runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num =", "= \"bgm/Battle.wav\") print(\"aaaaa\") self._check_hit_blow(self.num,st.session_state.ans) st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {}", "= self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num = num def", "{}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype :", "time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title", "self.num = num def _define_answer(self) -> str: \"\"\"自分が当てる答えをつくる : rtype : str :", "\"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として, 試合数, 経験値, レベル, 連勝数を定義し, 初期化しておく(マジックコマンド的な) : rtype : None : return", "as st import pygame st.set_page_config(layout=\"wide\") col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def", "# 初期設定 sound = pygame.mixer.Sound(title) # 音楽ファイルの読み込み sound.set_volume(self.volume) sound.play() def _check_hit_blow(self,num,ans) -> None:", "in range(self.digits): if num[i] == ans[i]: self.hit += 1 else: if num[i] in", "Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history)) if self.hit == self.digits: print(\"!!", "img = Image.open('picture/level-up.gif') time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 :", "volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits = 5 self.Tuple_16 = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\") self.hit", "\"\".join(ans_list) return ans def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い)", "print(\"------------------------\") def _get_information(self) -> str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str", "pic_url2 = \"picture/\"+st.session_state.chara_name+\"-2.jpg\" image = Image.open(pic_url2) col4.image(image) img = Image.open('picture/evolution.gif') col6.image(img) self._play_song(num =", ": {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits :", "#self._music_stop() place = col6.empty() place.write(\"対戦中・・・\") if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num =", "i**3/3 <= st.session_state.exp and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level", "\"\"\" pygame.mixer.init() # 初期設定 pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self)", "= 0 self.blow = 0 for i in range(self.digits): if num[i] == ans[i]:", "pygame.mixer.music.load(title) # 音楽ファイルの読み込み pygame.mixer.music.set_volume(self.volume) pygame.mixer.music.play(num) # 音楽の再生回数(1回) def _music_stop(self) -> None: \"\"\"再生中の音楽停止 :", "self.ans = self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num = num", "time.sleep(3) st.balloons() col6.write(\"{}は{}経験値を得た!\".format(st.session_state.chara_name,new_exp)) col6.write(\"\") time.sleep(13) if level_up: if evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png')", "def _play_song(self,num:int, title): \"\"\"待機時間中音楽再生 :param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype :", "new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200): if i**3/3 <=", "1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit, {} Blowだ!\".format(self.hit,self.blow)) col6.write(\"現在のターン数,{}\".format(st.session_state.turn_count)) col6.write(\"今までの入力履歴,{}\".format(st.session_state.history))", "col6.write(\"対戦回数 : {}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param", ": None : return : なし \"\"\" self.hit = 0 self.blow = 0", "col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\") if 'game_count' not in st.session_state: st.session_state.game_count = 1 if 'exp' not in", "if st.session_state.turn_count == 0: self._music_stop() time.sleep(3) self._play_song(num = 1,title = \"bgm/game_start.wav\") self._voice_play(num =", "str: \"\"\"対戦終了後,web画面に表示する内容を計算 勝敗,連勝に応じて獲得経験値を求め, 経験値に加える.レベルや次のレベルまでの必要経験値も求める 進化やレベルアップの判定も行う : rtype : str : return : 獲得経験値と次のレベルまでの必要経験値", "and st.session_state.exp < (i+1)**3/3: remaining_exp = round((i+1)**3/3 - st.session_state.exp) new_level = i if", "sound.play() def _check_hit_blow(self,num,ans) -> None: \"\"\"メインで使用 2つの引数を入力し, その2数のhit,blowを計算してself.hit, self.blowに格納 : rtype : None", "st.session_state.exp) new_level = i if new_level != st.session_state.level: level_up = True if new_level", "not in st.session_state: st.session_state.exp = 0 if 'level' not in st.session_state: st.session_state.level =", "st.session_state.level: level_up = True if new_level == 20: evolution = True st.session_state.level =", "i if new_level != st.session_state.level: level_up = True if new_level == 20: evolution", "evolution: col4.subheader(\"おや?{}の様子が...\".format(st.session_state.chara_name)) image_light = Image.open('picture/evolution_light.png') col4.image(image_light) self._play_song(num = 1,title = \"bgm/evolution_light.mp3\") time.sleep(3) col4.subheader(\"やったね,", "None self.volume = 0.3 if ans is not None: self.ans = ans else:", "name = col4.selectbox(\"キャラクターを選んでね\",[\"ジャック\",\"クリス\",\"フローラ\",\"ドロシー\"]) st.session_state.chara_name = name pic_url1 = \"picture/\"+name+\"-1.jpg\" pic_url2 = \"picture/\"+name+\"-2.jpg\" if", "-> None: \"\"\"Hit&Blowのメイン \"\"\" args = get_parser() ans= args.ans num = col6.text_input(\"予想する数字を入力してね\") print(button_num)", "Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>, <NAME>, <NAME> \"\"\" import", "st.session_state.win_in_a_row += 1 level_up = False evolution = False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp", "None: \"\"\"対戦終了後, お互いの結果を表示(web画面上に表示する分) 勝敗、連勝数に応じて表示を変える, 経験値やレベル, 対戦回数も表示 進化とレベルアップの時は追加エフェクト : rtype : None : return", ": rtype : None : return : なし \"\"\" new_exp,remaining_exp,level_up,evolution = self._get_information() self._music_stop()", "= False new_exp = round(3000*(1+(st.session_state.win_in_a_row-1)/4)/st.session_state.turn_count) st.session_state.exp += new_exp for i in range(200): if", "self._show_result_streamlit() def _show_result_vscode(self) -> None: \"\"\"対戦終了後, お互いの結果を表示(vscode上に表示する分) : rtype : None : return", "\"\"\"音楽再生中のキャラボイス再生用 : rtype : None : return : なし \"\"\" pygame.mixer.init() # 初期設定", ": なし \"\"\" print(\"------------------------\") print(\"show history\") print(st.session_state.history) print(\"------------------------\") print(\"正解は{}です. おめでとうございます! {}回で正解しました.\".format(st.session_state.ans,st.session_state.turn_count)) print(\"------------------------\") def", "= 0 if 'level' not in st.session_state: st.session_state.level = 1 if 'win_in_a_row' not", "time.sleep(1) col6.image(img) col6.write(\"次のレベルまでの経験値:{}\".format(remaining_exp)) col6.write(\"今まで得た合計経験値:{}\".format(st.session_state.exp)) col6.subheader(\"\") col6.subheader(\"{}の現在のレベル : {}\".format(st.session_state.chara_name,st.session_state.level)) col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count", "= 0 for i in range(self.digits): if num[i] == ans[i]: self.hit += 1", "= 1,title = \"bgm/game_start.wav\") self._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/game_start.wav') time.sleep(3) self._play_song(num = -1,title", "col6.write(\"対戦回数 : {}\".format(st.session_state.game_count)) col6.subheader(\"また新たな秘密の数字が現れた!当てに行こう!\") st.session_state.game_count += 1 st.session_state.turn_count = 0 st.session_state.history = {}", ": rtype : str : return : 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1", "runner._play_song(num = -1,title = 'bgm/waiting.wav') runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual()", "[str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow)) col6.subheader(\"{} Hit,", "blow : 数字のblow数 :param int volume:音量(0~1で変更) \"\"\" def __init__(self,ans=None,num=None) -> None: self.digits =", "None : return : なし \"\"\" col1.title(\"Welcome to Hit&Blow Game!16進数5桁の秘密の数字を当てよう!\") col1.subheader(\"対戦すると経験値がもらえるよ. 経験値は当てた回数や連勝数に応じて増えるぞ!\") col1.subheader(\"経験値が貯まるとレベルアップだ!いずれはキャラが進化するかも‥?\")", "!= st.session_state.level: level_up = True if new_level == 20: evolution = True st.session_state.level", ": 獲得経験値と次のレベルまでの必要経験値 \"\"\" # st.session_state.win_in_a_row += 1 level_up = False evolution = False", "initialize_streamlit() if args.ans is not None: runner = Playgame_solo_manual(ans=ans,num=num) else: runner = Playgame_solo_manual(num=num)", "Name: hitblow_solo_manual.py Description: Hit&Blowの手動一人対戦モード Created on october 13,2021 Created by <NAME>, <NAME>, <NAME>", "self._define_answer() if 'ans' not in st.session_state: st.session_state.ans= self.ans self.num = num def _define_answer(self)", ":param str ans : comの答え(自分が当てる数字) :param List[dict] my_history : 自分が相手の数当をした時の履歴 :param str num", "-> str: \"\"\"自分が当てる答えをつくる : rtype : str : return : ans \"\"\" ans_list", "rtype : str : return : ans \"\"\" ans_list = random.sample(self.Tuple_16, self.digits) ans", "col1,col2 =st.columns([4,1]) col4,space,col6 =st.columns([7,1,4]) button_num = 0 def initialize_streamlit() -> None: \"\"\"クラスを定義する前にweb上で画面を出しておく 状態量として,", "st.session_state.history[self.num] = [str(self.hit)+\"hit\", str(self.blow)+\"blow\"] st.session_state.turn_count += 1 print(\"!! {} Hit, {} Blow !!\".format(self.hit,self.blow))", ":param int num:再生回数(-1で無限ループ,これを使って止めたいときにstopするのが良いかと) :param int playtime:再生時間(基本-1で無限ループしてるので、使わない.デフォルト値Noneで良い) : rtype : None : return :", "{}\".format(st.session_state.game_count-1)) class Playgame_solo_manual: \"\"\"16進数5桁のHit&Blow 自動一人対戦の数当てモード :param int digits : 数の桁数 :param set Tuple_16", "runner._voice_play(num = 1, title ='voice/'+st.session_state.chara_name+'/waiting.wav') if col6.button(\"クリックすると数字をチェックするよ!\"): runner._play_game_manual() if __name__ == \"__main__\": main()" ]