content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_specs2_specs2_fp_2_12",
artifact = "org.specs2:specs2-fp_2.12:4.8.3",
artifact_sha256 = "777962ca58054a9ea86e294e025453ecf394c60084c28bd61956a00d16be31a7",
srcjar_sha256 = "6b8bd1e7210754b768b68610709271c0dac29447936a976a2a9881389e6404ca",
deps = [
"@org_scala_lang_scala_library"
],
)
import_external(
name = "org_specs2_specs2_common_2_12",
artifact = "org.specs2:specs2-common_2.12:4.8.3",
artifact_sha256 = "3b08fecb9e21d3903e48b62cd95c19ea9253d466e03fd4cf9dc9227e7c368708",
srcjar_sha256 = "b2f148c75d3939b3cd0d58afddd74a8ce03077bb3ccdc93dae55bd9c3993e9c3",
deps = [
"@org_scala_lang_modules_scala_parser_combinators_2_12",
"@org_scala_lang_modules_scala_xml_2_12",
"@org_scala_lang_scala_library",
"@org_scala_lang_scala_reflect",
"@org_specs2_specs2_fp_2_12"
],
)
import_external(
name = "org_specs2_specs2_matcher_2_12",
artifact = "org.specs2:specs2-matcher_2.12:4.8.3",
artifact_sha256 = "aadf27b6d015572b2e3842627c09bf0797153dbb329262ea3bcbbce129d51ad8",
srcjar_sha256 = "01251acc28219aa17aabcb9a26a84e1871aa64980d335cd8f83c2bcea6f4f1be",
deps = [
"@org_scala_lang_scala_library",
"@org_specs2_specs2_common_2_12"
],
)
import_external(
name = "org_specs2_specs2_core_2_12",
artifact = "org.specs2:specs2-core_2.12:4.8.3",
artifact_sha256 = "f73f32156a711a4e83e696dc83e269c5a165d62cc3dd7c652617cb03d140d063",
srcjar_sha256 = "0e3cebfc7410051b70e627e35f13978add3d061b8f1233741f9b397638f193e9",
deps = [
"@org_scala_lang_scala_library",
"@org_scala_sbt_test_interface",
"@org_specs2_specs2_common_2_12",
"@org_specs2_specs2_matcher_2_12"
],
)
import_external(
name = "org_specs2_specs2_junit_2_12",
artifact = "org.specs2:specs2-junit_2.12:4.8.3",
artifact_sha256 = "5d7ad2c0b0bc142ea064edb7a1ea75ab7b17ad37e1a621ac7e578823845098e8",
srcjar_sha256 = "84edd1cd6291f6686638225fcbaff970ae36da006efabf2228255c2127b2290c",
deps = [
"@junit_junit",
"@org_scala_lang_scala_library",
"@org_scala_sbt_test_interface",
"@org_specs2_specs2_core_2_12"
],
)
| load('@wix_oss_infra//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='org_specs2_specs2_fp_2_12', artifact='org.specs2:specs2-fp_2.12:4.8.3', artifact_sha256='777962ca58054a9ea86e294e025453ecf394c60084c28bd61956a00d16be31a7', srcjar_sha256='6b8bd1e7210754b768b68610709271c0dac29447936a976a2a9881389e6404ca', deps=['@org_scala_lang_scala_library'])
import_external(name='org_specs2_specs2_common_2_12', artifact='org.specs2:specs2-common_2.12:4.8.3', artifact_sha256='3b08fecb9e21d3903e48b62cd95c19ea9253d466e03fd4cf9dc9227e7c368708', srcjar_sha256='b2f148c75d3939b3cd0d58afddd74a8ce03077bb3ccdc93dae55bd9c3993e9c3', deps=['@org_scala_lang_modules_scala_parser_combinators_2_12', '@org_scala_lang_modules_scala_xml_2_12', '@org_scala_lang_scala_library', '@org_scala_lang_scala_reflect', '@org_specs2_specs2_fp_2_12'])
import_external(name='org_specs2_specs2_matcher_2_12', artifact='org.specs2:specs2-matcher_2.12:4.8.3', artifact_sha256='aadf27b6d015572b2e3842627c09bf0797153dbb329262ea3bcbbce129d51ad8', srcjar_sha256='01251acc28219aa17aabcb9a26a84e1871aa64980d335cd8f83c2bcea6f4f1be', deps=['@org_scala_lang_scala_library', '@org_specs2_specs2_common_2_12'])
import_external(name='org_specs2_specs2_core_2_12', artifact='org.specs2:specs2-core_2.12:4.8.3', artifact_sha256='f73f32156a711a4e83e696dc83e269c5a165d62cc3dd7c652617cb03d140d063', srcjar_sha256='0e3cebfc7410051b70e627e35f13978add3d061b8f1233741f9b397638f193e9', deps=['@org_scala_lang_scala_library', '@org_scala_sbt_test_interface', '@org_specs2_specs2_common_2_12', '@org_specs2_specs2_matcher_2_12'])
import_external(name='org_specs2_specs2_junit_2_12', artifact='org.specs2:specs2-junit_2.12:4.8.3', artifact_sha256='5d7ad2c0b0bc142ea064edb7a1ea75ab7b17ad37e1a621ac7e578823845098e8', srcjar_sha256='84edd1cd6291f6686638225fcbaff970ae36da006efabf2228255c2127b2290c', deps=['@junit_junit', '@org_scala_lang_scala_library', '@org_scala_sbt_test_interface', '@org_specs2_specs2_core_2_12']) |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == 0 and b == 0:
print("INF")
else:
if (d - b * c / a) != 0 and (- b / a) == (- b // a):
print(- b // a)
else:
print("NO")
| a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == 0 and b == 0:
print('INF')
elif d - b * c / a != 0 and -b / a == -b // a:
print(-b // a)
else:
print('NO') |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 19:46:40 2020
@author: Intel
"""
def displayPathtoPrincess(n,grid):
me_i=n//2
me_j=n//2
for i in range(n):
if 'p' in grid[i]:
pe_i=i
for j in range(n):
if 'p'==grid[i][j]:
pe_j=j
break
break
while((me_i!=pe_i) | (me_j!=pe_j)):
if(me_i-pe_i<0):
print('DOWN')
me_i=me_i+1
elif(me_i-pe_i>0):
print('UP')
me_i=me_i-1
else:
if(me_j-pe_j>0):
print('LEFT')
me_j=me_j-1
elif(me_j-pe_j<0):
print('RIGHT')
me_j=me_j+1
else:
break
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
displayPathtoPrincess(m,grid) | """
Created on Mon Dec 7 19:46:40 2020
@author: Intel
"""
def display_pathto_princess(n, grid):
me_i = n // 2
me_j = n // 2
for i in range(n):
if 'p' in grid[i]:
pe_i = i
for j in range(n):
if 'p' == grid[i][j]:
pe_j = j
break
break
while (me_i != pe_i) | (me_j != pe_j):
if me_i - pe_i < 0:
print('DOWN')
me_i = me_i + 1
elif me_i - pe_i > 0:
print('UP')
me_i = me_i - 1
elif me_j - pe_j > 0:
print('LEFT')
me_j = me_j - 1
elif me_j - pe_j < 0:
print('RIGHT')
me_j = me_j + 1
else:
break
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
display_pathto_princess(m, grid) |
# Copyright (C) 2020 Google Inc.
#
# This file has been licensed under Apache 2.0 license. Please see the LICENSE
# file at the root of the repository.
# Build rules for building ebooks.
# This is the container
CONTAINER = "filipfilmar/ebook-buildenv:1.1"
# Use this for quick local runs.
#CONTAINER = "ebook-buildenv:local"
EbookInfo = provider(fields=["figures", "markdowns"])
# Returns the docker_run script invocation command based on the
# script path and its reference directory.
#
# Params:
# script_path: (string) The full path to the script to invoke
# dir_reference: (string) The path to a file used for figuring out
# the reference directories (build root and repo root).
def _script_cmd(script_path, dir_reference):
return """\
{script} \
--container={container} \
--dir-reference={dir_reference}""".format(
script=script_path,
container=CONTAINER,
dir_reference=dir_reference,
)
def _drawtiming_png_impl(ctx):
cmd = "drawtiming"
docker_run = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + ".png")
figures += [out_file]
script_cmd = _script_cmd(docker_run.path, in_file.path)
ctx.actions.run_shell(
progress_message = "timing diagram to PNG with {1}: {0}".format(in_file.short_path, cmd),
inputs = [in_file],
outputs = [out_file],
tools = [docker_run],
command = """\
{script} \
{cmd} --output "{out_file}" "{in_file}"
""".format(
cmd=cmd,
out_file=out_file.path,
in_file=in_file.path,
script=script_cmd),
)
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files = figures)
return [
EbookInfo(figures=figures+deps, markdowns=[]),
DefaultInfo(files=depset(figures+deps), runfiles=runfiles),
]
drawtiming_png = rule(implementation = _drawtiming_png_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".t"],
doc = "The file to compile",
),
"deps": attr.label_list(
doc = "The dependencies, any targets should be allowed",
),
"output": attr.output(doc="The generated file"),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Transform a timing diagram file into png using drawtiming",
)
def _generalized_graphviz_rule_impl(ctx, cmd):
docker_run = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + ".png")
figures += [out_file]
script_cmd = _script_cmd(docker_run.path, in_file.path)
ctx.actions.run_shell(
progress_message = "graphviz to PNG with {1}: {0}".format(in_file.short_path, cmd),
inputs = [in_file],
outputs = [out_file],
tools = [docker_run],
command = """\
{script} \
{cmd} -Tpng -o "{out_file}" "{in_file}"
""".format(
cmd=cmd,
out_file=out_file.path,
in_file=in_file.path,
script=script_cmd),
)
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files = figures)
return [
EbookInfo(figures=figures+deps, markdowns=[]),
DefaultInfo(files=depset(figures+deps), runfiles=runfiles),
]
def _neato_png_impl(ctx):
return _generalized_graphviz_rule_impl(ctx, "neato")
neato_png = rule(implementation = _neato_png_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".dot"],
doc = "The file to compile",
),
"deps": attr.label_list(
doc = "The dependencies, any targets should be allowed",
),
"output": attr.output(doc="The generated file"),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Transform a graphviz dot file into png using neato",
)
def _dot_png_impl(ctx):
return _generalized_graphviz_rule_impl(ctx, "dot")
dot_png = rule(implementation = _dot_png_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".dot"],
doc = "The file to compile",
),
"deps": attr.label_list(
doc = "The dependencies, any targets should be allowed",
),
"output": attr.output(doc="The generated file"),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Transform a graphviz dot file into png using dot",
)
def _asymptote_impl(ctx):
asycc = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + ".png")
figures += [out_file]
script_cmd = _script_cmd(asycc.path, in_file.path)
ctx.actions.run_shell(
progress_message = "ASY to PNG: {0}".format(in_file.short_path),
inputs = [in_file],
outputs = [out_file],
tools = [asycc],
command = """\
{script} \
asy -render 5 -f png -o "{out_file}" "{in_file}"
""".format(
out_file=out_file.path, in_file=in_file.path, script=script_cmd),
)
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files=figures+deps)
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [
EbookInfo(figures=figures+deps, markdowns=[]),
DefaultInfo(files=depset(figures+deps), runfiles=runfiles),
]
asymptote = rule(implementation = _asymptote_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".asy"],
doc = "The file to compile",
),
"deps": attr.label_list(
doc = "The dependencies, any targets should be allowed",
),
"output": attr.output(doc="The generated file"),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Transform an asymptote file into png",
)
def _copy_file_to_workdir_renamed(ctx, src):
src_copy = ctx.actions.declare_file("{}_{}".format(ctx.label.name, src.short_path))
ctx.actions.run_shell(
progress_message = "Copying {} to {}".format(src.short_path, src_copy.short_path),
outputs = [src_copy],
inputs = [src],
command="cp {} {}".format(src.path, src_copy.path),
)
return src_copy
def _copy_file_to_workdir(ctx, src):
src_copy = ctx.actions.declare_file(src.basename)
ctx.actions.run_shell(
progress_message = "Copying {}".format(src.short_path),
outputs = [src_copy],
inputs = [src],
command="cp {} {}".format(src.path, src_copy.path),
)
return src_copy
def _markdown_lib_impl(ctx):
markdowns = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
markdowns += [_copy_file_to_workdir(ctx, src)]
figures = []
for target in ctx.attr.deps:
provider = target[EbookInfo]
figures += (provider.figures or [])
markdowns += (provider.markdowns or [])
runfiles = ctx.runfiles(files=figures+markdowns)
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [
EbookInfo(figures=figures, markdowns=markdowns),
DefaultInfo(
files=depset(figures+markdowns),
runfiles=runfiles,
),
]
markdown_lib = rule(
implementation = _markdown_lib_impl,
doc = "Declares a set of markdown files",
attrs = {
"srcs": attr.label_list(
allow_files = [".md"],
doc = "The markdown source files",
),
"deps": attr.label_list(
doc = "The file to compile",
providers = [EbookInfo],
),
},
)
def _ebook_epub_impl(ctx):
name = ctx.label.name
# This is duplicated in _ebook_pdf_impl.
# steps
# run htex on all *md, gives book.htex
markdowns = []
figures = []
for dep in ctx.attr.deps:
provider = dep[EbookInfo]
markdowns += provider.markdowns
figures += provider.figures
dir_reference = markdowns[0]
htex_file = ctx.actions.declare_file("{}.htex".format(name))
markdowns_paths = [file.path for file in markdowns]
markdowns_paths_stripped = _strip_reference_dir_from_files(dir_reference, markdowns)
script = ctx.executable._script
script_cmd = _script_cmd(script.path, markdowns_paths[0])
ctx.actions.run_shell(
progress_message = "Building equation environments for: {}".format(name),
inputs = markdowns,
outputs = [htex_file],
tools = [script],
command = """\
{script} \
pandoc -s --gladtex -o {target} {sources} \
""".format(
script=script_cmd,
target=htex_file.path,
sources=" ".join(markdowns_paths))
)
# run gladtex on the resulting htex to obtain html and output directory with figures.
outdir = ctx.actions.declare_directory("{}.eqn".format(name))
html_file = ctx.actions.declare_file("{}.html".format(name))
ctx.actions.run_shell(
progress_message = "Extracting equations for: {}".format(name),
inputs = [htex_file],
outputs = [outdir, html_file],
tools = [script],
command = """\
{script} --cd-to-dir-reference \
gladtex -r 200 -d {outdir} {htex_file} \
""".format(
script=script_cmd,
outdir=_strip_reference_dir(dir_reference, outdir.path),
htex_file=_strip_reference_dir(dir_reference, htex_file.path),
)
)
outdir_tar = ctx.actions.declare_file("{}.tar".format(outdir.basename))
tar_command = "(cd {base} ; tar cf {archive} {dir})".format(
base=outdir_tar.dirname,
archive=outdir_tar.basename,
dir=outdir.basename)
ctx.actions.run_shell(
progress_message = "Archiving equations: {}".format(outdir_tar.short_path),
inputs = [outdir],
outputs = [outdir_tar],
command = tar_command,
)
# run htexepub to obtain book.epub.
# This is gonna be fun!
epub_metadata = ctx.attr.metadata_xml.files.to_list()[0]
epub_metadata = _copy_file_to_workdir_renamed(ctx, epub_metadata)
title_yaml = ctx.attr.title_yaml.files.to_list()[0]
title_yaml = _copy_file_to_workdir_renamed(ctx, epub_metadata)
ebook_epub = ctx.actions.declare_file("{}.epub".format(name))
inputs = [epub_metadata, title_yaml, html_file, outdir, outdir_tar] + markdowns + figures
ctx.actions.run_shell(
progress_message = "Building EPUB for: {}".format(name),
inputs = inputs,
tools = [script],
outputs = [ebook_epub],
command = """\
{script} --cd-to-dir-reference \
pandoc --epub-metadata={epub_metadata} \
-f html -t epub3 -o {ebook_epub} {html_file} \
""".format(
script=script_cmd,
epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path),
ebook_epub=_strip_reference_dir(dir_reference, ebook_epub.path),
html_file=_strip_reference_dir(dir_reference, html_file.path),
))
runfiles = ctx.runfiles(files=[ebook_epub])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [
dep[EbookInfo],
DefaultInfo(
files=depset([ebook_epub, outdir, outdir_tar]),
runfiles=runfiles,
)
]
ebook_epub = rule(
implementation = _ebook_epub_impl,
attrs = {
"deps": attr.label_list(
doc = "All the targets you need to make this book work.",
providers = [EbookInfo],
),
"title_yaml": attr.label(
allow_files = True,
doc = "The title.yaml file to use for this book",
),
"metadata_xml": attr.label(
allow_files = True,
doc = "The epub-metadata.xml file to use for this book",
),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Generate an ebook in EPUB format"
)
def _strip_reference_dir(reference_dir, path):
return path.replace(reference_dir.dirname+"/", "")
def _strip_reference_dir_from_files(reference_dir, files):
return [ _strip_reference_dir(reference_dir, file.path) for file in files]
def _ebook_pdf_impl(ctx):
name = ctx.label.name
# steps
# run htex on all *md, gives book.htex
markdowns = []
figures = []
for dep in ctx.attr.deps:
provider = dep[EbookInfo]
markdowns += provider.markdowns
figures += provider.figures
dir_reference = markdowns[0]
# Fixed up paths -- relative to the directory dir_reference, not the
# directory where the build happens! This is needed because we can not control
# figure inclusion.
markdowns_paths = _strip_reference_dir_from_files(dir_reference, markdowns)
script = ctx.executable._script
script_cmd = _script_cmd(script.path, dir_reference.path)
# run htexepub to obtain book.epub.
# This is gonna be fun!
epub_metadata = ctx.attr.metadata_xml.files.to_list()[0]
epub_metadata = _copy_file_to_workdir(ctx, epub_metadata)
title_yaml = ctx.attr.title_yaml.files.to_list()[0]
title_yaml = _copy_file_to_workdir(ctx, title_yaml)
ebook_pdf = ctx.actions.declare_file("{}.pdf".format(name))
inputs = [epub_metadata, title_yaml] + markdowns + figures
ctx.actions.run_shell(
progress_message = "Building PDF for: {}".format(name),
inputs = inputs,
tools = [script],
outputs = [ebook_pdf],
command = """\
{script} --cd-to-dir-reference \
pandoc --epub-metadata={epub_metadata} \
--mathml -o {ebook_pdf} {markdowns} \
""".format(
script=script_cmd,
epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path),
ebook_pdf=_strip_reference_dir(dir_reference, ebook_pdf.path),
markdowns=" ".join(markdowns_paths),
))
runfiles = ctx.runfiles(files=[ebook_pdf])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [
DefaultInfo(
files=depset([ebook_pdf]),
runfiles=runfiles,
)
]
ebook_pdf = rule(
implementation = _ebook_pdf_impl,
attrs = {
"deps": attr.label_list(
doc = "All the targets you need to make this book work.",
providers = [EbookInfo],
),
"title_yaml": attr.label(
allow_files = True,
doc = "The title.yaml file to use for this book",
),
"metadata_xml": attr.label(
allow_files = True,
doc = "The epub-metadata.xml file to use for this book",
),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Generate an ebook in PDF format"
)
def _ebook_kindle_impl(ctx):
mobi_file = ctx.actions.declare_file("{}.mobi".format(ctx.label.name))
# First provider is EbookInfo, second is DefaultInfo.
(ebook_info, default_info) = _ebook_epub_impl(ctx)
# There can be only one such file
outputs = default_info.files.to_list()
epub_file = outputs[0]
equation_outdir = outputs[1]
equation_outdir_tar = outputs[2]
captured_output = ctx.actions.declare_file(
"{}.untar-out".format(ctx.label.name))
# untar the equation dir
# Maybe this is not needed.
tar_command = "(cd {base} ; tar xvf {archive}) > {output}".format(
base=equation_outdir_tar.dirname,
archive=equation_outdir_tar.basename,
output=captured_output.path)
ctx.actions.run_shell(
progress_message = "Unarchiving equations: {}".format(equation_outdir_tar.short_path),
inputs = [equation_outdir_tar],
outputs = [captured_output],
command = tar_command,
)
dir_reference = epub_file
script = ctx.executable._script
name = ctx.label.name
script_cmd = _script_cmd(script.path, epub_file.path)
ctx.actions.run_shell(
progress_message = "Building MOBI for: {}".format(name),
inputs = [epub_file, equation_outdir],
tools = [script],
outputs = [mobi_file],
command = """\
{script} --cd-to-dir-reference \
ebook-convert {epub_file} {mobi_file} \
""".format(
script=script_cmd,
epub_file=_strip_reference_dir(dir_reference, epub_file.path),
mobi_file=_strip_reference_dir(dir_reference, mobi_file.path),
))
runfiles = ctx.runfiles(files=[mobi_file])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [
DefaultInfo(
files=depset([mobi_file, captured_output]),
runfiles=runfiles,
)
]
ebook_kindle = rule(
implementation = _ebook_kindle_impl,
attrs = {
"deps": attr.label_list(
doc = "All the targets you need to make this book work.",
providers = [EbookInfo],
),
"title_yaml": attr.label(
allow_files = True,
doc = "The title.yaml file to use for this book",
),
"metadata_xml": attr.label(
allow_files = True,
doc = "The epub-metadata.xml file to use for this book",
),
"_script": attr.label(
default="//build:docker_run",
executable=True,
cfg="host"),
},
doc = "Generate an ebook in the Kindle's MOBI format"
)
| container = 'filipfilmar/ebook-buildenv:1.1'
ebook_info = provider(fields=['figures', 'markdowns'])
def _script_cmd(script_path, dir_reference):
return ' {script} --container={container} --dir-reference={dir_reference}'.format(script=script_path, container=CONTAINER, dir_reference=dir_reference)
def _drawtiming_png_impl(ctx):
cmd = 'drawtiming'
docker_run = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + '.png')
figures += [out_file]
script_cmd = _script_cmd(docker_run.path, in_file.path)
ctx.actions.run_shell(progress_message='timing diagram to PNG with {1}: {0}'.format(in_file.short_path, cmd), inputs=[in_file], outputs=[out_file], tools=[docker_run], command=' {script} {cmd} --output "{out_file}" "{in_file}"\n '.format(cmd=cmd, out_file=out_file.path, in_file=in_file.path, script=script_cmd))
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files=figures)
return [ebook_info(figures=figures + deps, markdowns=[]), default_info(files=depset(figures + deps), runfiles=runfiles)]
drawtiming_png = rule(implementation=_drawtiming_png_impl, attrs={'srcs': attr.label_list(allow_files=['.t'], doc='The file to compile'), 'deps': attr.label_list(doc='The dependencies, any targets should be allowed'), 'output': attr.output(doc='The generated file'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Transform a timing diagram file into png using drawtiming')
def _generalized_graphviz_rule_impl(ctx, cmd):
docker_run = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + '.png')
figures += [out_file]
script_cmd = _script_cmd(docker_run.path, in_file.path)
ctx.actions.run_shell(progress_message='graphviz to PNG with {1}: {0}'.format(in_file.short_path, cmd), inputs=[in_file], outputs=[out_file], tools=[docker_run], command=' {script} {cmd} -Tpng -o "{out_file}" "{in_file}"\n '.format(cmd=cmd, out_file=out_file.path, in_file=in_file.path, script=script_cmd))
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files=figures)
return [ebook_info(figures=figures + deps, markdowns=[]), default_info(files=depset(figures + deps), runfiles=runfiles)]
def _neato_png_impl(ctx):
return _generalized_graphviz_rule_impl(ctx, 'neato')
neato_png = rule(implementation=_neato_png_impl, attrs={'srcs': attr.label_list(allow_files=['.dot'], doc='The file to compile'), 'deps': attr.label_list(doc='The dependencies, any targets should be allowed'), 'output': attr.output(doc='The generated file'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Transform a graphviz dot file into png using neato')
def _dot_png_impl(ctx):
return _generalized_graphviz_rule_impl(ctx, 'dot')
dot_png = rule(implementation=_dot_png_impl, attrs={'srcs': attr.label_list(allow_files=['.dot'], doc='The file to compile'), 'deps': attr.label_list(doc='The dependencies, any targets should be allowed'), 'output': attr.output(doc='The generated file'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Transform a graphviz dot file into png using dot')
def _asymptote_impl(ctx):
asycc = ctx.executable._script
figures = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
in_file = src
out_file = ctx.actions.declare_file(in_file.basename + '.png')
figures += [out_file]
script_cmd = _script_cmd(asycc.path, in_file.path)
ctx.actions.run_shell(progress_message='ASY to PNG: {0}'.format(in_file.short_path), inputs=[in_file], outputs=[out_file], tools=[asycc], command=' {script} asy -render 5 -f png -o "{out_file}" "{in_file}"\n '.format(out_file=out_file.path, in_file=in_file.path, script=script_cmd))
deps = []
for target in ctx.attr.deps:
ebook_provider = target[EbookInfo]
if not ebook_provider:
continue
deps += ebook_provider.figures
runfiles = ctx.runfiles(files=figures + deps)
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [ebook_info(figures=figures + deps, markdowns=[]), default_info(files=depset(figures + deps), runfiles=runfiles)]
asymptote = rule(implementation=_asymptote_impl, attrs={'srcs': attr.label_list(allow_files=['.asy'], doc='The file to compile'), 'deps': attr.label_list(doc='The dependencies, any targets should be allowed'), 'output': attr.output(doc='The generated file'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Transform an asymptote file into png')
def _copy_file_to_workdir_renamed(ctx, src):
src_copy = ctx.actions.declare_file('{}_{}'.format(ctx.label.name, src.short_path))
ctx.actions.run_shell(progress_message='Copying {} to {}'.format(src.short_path, src_copy.short_path), outputs=[src_copy], inputs=[src], command='cp {} {}'.format(src.path, src_copy.path))
return src_copy
def _copy_file_to_workdir(ctx, src):
src_copy = ctx.actions.declare_file(src.basename)
ctx.actions.run_shell(progress_message='Copying {}'.format(src.short_path), outputs=[src_copy], inputs=[src], command='cp {} {}'.format(src.path, src_copy.path))
return src_copy
def _markdown_lib_impl(ctx):
markdowns = []
for target in ctx.attr.srcs:
for src in target.files.to_list():
markdowns += [_copy_file_to_workdir(ctx, src)]
figures = []
for target in ctx.attr.deps:
provider = target[EbookInfo]
figures += provider.figures or []
markdowns += provider.markdowns or []
runfiles = ctx.runfiles(files=figures + markdowns)
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [ebook_info(figures=figures, markdowns=markdowns), default_info(files=depset(figures + markdowns), runfiles=runfiles)]
markdown_lib = rule(implementation=_markdown_lib_impl, doc='Declares a set of markdown files', attrs={'srcs': attr.label_list(allow_files=['.md'], doc='The markdown source files'), 'deps': attr.label_list(doc='The file to compile', providers=[EbookInfo])})
def _ebook_epub_impl(ctx):
name = ctx.label.name
markdowns = []
figures = []
for dep in ctx.attr.deps:
provider = dep[EbookInfo]
markdowns += provider.markdowns
figures += provider.figures
dir_reference = markdowns[0]
htex_file = ctx.actions.declare_file('{}.htex'.format(name))
markdowns_paths = [file.path for file in markdowns]
markdowns_paths_stripped = _strip_reference_dir_from_files(dir_reference, markdowns)
script = ctx.executable._script
script_cmd = _script_cmd(script.path, markdowns_paths[0])
ctx.actions.run_shell(progress_message='Building equation environments for: {}'.format(name), inputs=markdowns, outputs=[htex_file], tools=[script], command=' {script} pandoc -s --gladtex -o {target} {sources} '.format(script=script_cmd, target=htex_file.path, sources=' '.join(markdowns_paths)))
outdir = ctx.actions.declare_directory('{}.eqn'.format(name))
html_file = ctx.actions.declare_file('{}.html'.format(name))
ctx.actions.run_shell(progress_message='Extracting equations for: {}'.format(name), inputs=[htex_file], outputs=[outdir, html_file], tools=[script], command=' {script} --cd-to-dir-reference gladtex -r 200 -d {outdir} {htex_file} '.format(script=script_cmd, outdir=_strip_reference_dir(dir_reference, outdir.path), htex_file=_strip_reference_dir(dir_reference, htex_file.path)))
outdir_tar = ctx.actions.declare_file('{}.tar'.format(outdir.basename))
tar_command = '(cd {base} ; tar cf {archive} {dir})'.format(base=outdir_tar.dirname, archive=outdir_tar.basename, dir=outdir.basename)
ctx.actions.run_shell(progress_message='Archiving equations: {}'.format(outdir_tar.short_path), inputs=[outdir], outputs=[outdir_tar], command=tar_command)
epub_metadata = ctx.attr.metadata_xml.files.to_list()[0]
epub_metadata = _copy_file_to_workdir_renamed(ctx, epub_metadata)
title_yaml = ctx.attr.title_yaml.files.to_list()[0]
title_yaml = _copy_file_to_workdir_renamed(ctx, epub_metadata)
ebook_epub = ctx.actions.declare_file('{}.epub'.format(name))
inputs = [epub_metadata, title_yaml, html_file, outdir, outdir_tar] + markdowns + figures
ctx.actions.run_shell(progress_message='Building EPUB for: {}'.format(name), inputs=inputs, tools=[script], outputs=[ebook_epub], command=' {script} --cd-to-dir-reference pandoc --epub-metadata={epub_metadata} -f html -t epub3 -o {ebook_epub} {html_file} '.format(script=script_cmd, epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path), ebook_epub=_strip_reference_dir(dir_reference, ebook_epub.path), html_file=_strip_reference_dir(dir_reference, html_file.path)))
runfiles = ctx.runfiles(files=[ebook_epub])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [dep[EbookInfo], default_info(files=depset([ebook_epub, outdir, outdir_tar]), runfiles=runfiles)]
ebook_epub = rule(implementation=_ebook_epub_impl, attrs={'deps': attr.label_list(doc='All the targets you need to make this book work.', providers=[EbookInfo]), 'title_yaml': attr.label(allow_files=True, doc='The title.yaml file to use for this book'), 'metadata_xml': attr.label(allow_files=True, doc='The epub-metadata.xml file to use for this book'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Generate an ebook in EPUB format')
def _strip_reference_dir(reference_dir, path):
return path.replace(reference_dir.dirname + '/', '')
def _strip_reference_dir_from_files(reference_dir, files):
return [_strip_reference_dir(reference_dir, file.path) for file in files]
def _ebook_pdf_impl(ctx):
name = ctx.label.name
markdowns = []
figures = []
for dep in ctx.attr.deps:
provider = dep[EbookInfo]
markdowns += provider.markdowns
figures += provider.figures
dir_reference = markdowns[0]
markdowns_paths = _strip_reference_dir_from_files(dir_reference, markdowns)
script = ctx.executable._script
script_cmd = _script_cmd(script.path, dir_reference.path)
epub_metadata = ctx.attr.metadata_xml.files.to_list()[0]
epub_metadata = _copy_file_to_workdir(ctx, epub_metadata)
title_yaml = ctx.attr.title_yaml.files.to_list()[0]
title_yaml = _copy_file_to_workdir(ctx, title_yaml)
ebook_pdf = ctx.actions.declare_file('{}.pdf'.format(name))
inputs = [epub_metadata, title_yaml] + markdowns + figures
ctx.actions.run_shell(progress_message='Building PDF for: {}'.format(name), inputs=inputs, tools=[script], outputs=[ebook_pdf], command=' {script} --cd-to-dir-reference pandoc --epub-metadata={epub_metadata} --mathml -o {ebook_pdf} {markdowns} '.format(script=script_cmd, epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path), ebook_pdf=_strip_reference_dir(dir_reference, ebook_pdf.path), markdowns=' '.join(markdowns_paths)))
runfiles = ctx.runfiles(files=[ebook_pdf])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [default_info(files=depset([ebook_pdf]), runfiles=runfiles)]
ebook_pdf = rule(implementation=_ebook_pdf_impl, attrs={'deps': attr.label_list(doc='All the targets you need to make this book work.', providers=[EbookInfo]), 'title_yaml': attr.label(allow_files=True, doc='The title.yaml file to use for this book'), 'metadata_xml': attr.label(allow_files=True, doc='The epub-metadata.xml file to use for this book'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc='Generate an ebook in PDF format')
def _ebook_kindle_impl(ctx):
mobi_file = ctx.actions.declare_file('{}.mobi'.format(ctx.label.name))
(ebook_info, default_info) = _ebook_epub_impl(ctx)
outputs = default_info.files.to_list()
epub_file = outputs[0]
equation_outdir = outputs[1]
equation_outdir_tar = outputs[2]
captured_output = ctx.actions.declare_file('{}.untar-out'.format(ctx.label.name))
tar_command = '(cd {base} ; tar xvf {archive}) > {output}'.format(base=equation_outdir_tar.dirname, archive=equation_outdir_tar.basename, output=captured_output.path)
ctx.actions.run_shell(progress_message='Unarchiving equations: {}'.format(equation_outdir_tar.short_path), inputs=[equation_outdir_tar], outputs=[captured_output], command=tar_command)
dir_reference = epub_file
script = ctx.executable._script
name = ctx.label.name
script_cmd = _script_cmd(script.path, epub_file.path)
ctx.actions.run_shell(progress_message='Building MOBI for: {}'.format(name), inputs=[epub_file, equation_outdir], tools=[script], outputs=[mobi_file], command=' {script} --cd-to-dir-reference ebook-convert {epub_file} {mobi_file} '.format(script=script_cmd, epub_file=_strip_reference_dir(dir_reference, epub_file.path), mobi_file=_strip_reference_dir(dir_reference, mobi_file.path)))
runfiles = ctx.runfiles(files=[mobi_file])
for dep in ctx.attr.deps:
runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles)
return [default_info(files=depset([mobi_file, captured_output]), runfiles=runfiles)]
ebook_kindle = rule(implementation=_ebook_kindle_impl, attrs={'deps': attr.label_list(doc='All the targets you need to make this book work.', providers=[EbookInfo]), 'title_yaml': attr.label(allow_files=True, doc='The title.yaml file to use for this book'), 'metadata_xml': attr.label(allow_files=True, doc='The epub-metadata.xml file to use for this book'), '_script': attr.label(default='//build:docker_run', executable=True, cfg='host')}, doc="Generate an ebook in the Kindle's MOBI format") |
n = int(input())
coelho = rato = sapo = contador = 0
for i in range(0, n):
q, t = input().split(' ')
t = t.upper()
q = int(q)
if 1 <= q <= 15:
contador += q
if t == 'C':
coelho += q
elif t == 'R':
rato += q
elif t == 'S':
sapo += q
porccoelho = (coelho * 100) / contador
porcrato = (rato * 100) / contador
porcsapo = (sapo * 100) / contador
print(f'Total: {contador} cobaias')
print(f'Total de coelhos: {coelho}')
print(f'Total de ratos: {rato}')
print(f'Total de sapos: {sapo}')
print(f'Percentual de coelhos: {porccoelho:.2f} %')
print(f'Percentual de ratos: {porcrato:.2f} %')
print(f'Percentual de sapos: {porcsapo:.2f} %')
| n = int(input())
coelho = rato = sapo = contador = 0
for i in range(0, n):
(q, t) = input().split(' ')
t = t.upper()
q = int(q)
if 1 <= q <= 15:
contador += q
if t == 'C':
coelho += q
elif t == 'R':
rato += q
elif t == 'S':
sapo += q
porccoelho = coelho * 100 / contador
porcrato = rato * 100 / contador
porcsapo = sapo * 100 / contador
print(f'Total: {contador} cobaias')
print(f'Total de coelhos: {coelho}')
print(f'Total de ratos: {rato}')
print(f'Total de sapos: {sapo}')
print(f'Percentual de coelhos: {porccoelho:.2f} %')
print(f'Percentual de ratos: {porcrato:.2f} %')
print(f'Percentual de sapos: {porcsapo:.2f} %') |
class APIError(Exception):
"""
raise APIError if receiving json message indicating failure.
"""
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
Exception.__init__(self, error)
def __str__(self):
return "APIError: %s: %s, request: %s" % (
self.error_code,
self.error,
self.request,
)
| class Apierror(Exception):
"""
raise APIError if receiving json message indicating failure.
"""
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
Exception.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request) |
def base_conv(n, input_base=10, output_base=10):
"""
Converts a number n from base input_base to base output_base.
The following symbols are used to represent numbers:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
n can be an int if input_base <= 10, and a string otherwise.
The result will be a string.
"""
numbers = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
## base 10 conversion
n = str(n)
size = len(n)
baseten = 0
for i in range(size):
baseten += numbers.index(n[i]) * input_base ** (size - 1 - i)
## base output_base conversion
# we search the biggest number m such that n^m < x
max_power = 0
while output_base ** (max_power + 1) <= baseten:
max_power += 1
result = ""
for i in range(max_power + 1):
coeff = baseten / (output_base ** (max_power - i))
baseten -= coeff * (output_base ** (max_power - i))
result += numbers[coeff]
return result
if __name__ == "__main__":
assert(base_conv(10) == "10")
assert(base_conv(42) == "42")
assert(base_conv(5673576) == "5673576")
assert(base_conv(10, input_base=2) == "2")
assert(base_conv(101010, input_base=2) == "42")
assert(base_conv(43, input_base=10, output_base=2) == "101011")
assert(base_conv(256**3 - 1, input_base=10, output_base=16) == "ffffff")
assert(base_conv("d9bbb9d0ceabf", input_base=16, output_base=8) ==
"154673563503165277")
assert(base_conv("154673563503165277", input_base=8, output_base=10) ==
"3830404793297599")
assert(base_conv(0, input_base=3, output_base=50) == "0")
| def base_conv(n, input_base=10, output_base=10):
"""
Converts a number n from base input_base to base output_base.
The following symbols are used to represent numbers:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
n can be an int if input_base <= 10, and a string otherwise.
The result will be a string.
"""
numbers = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = str(n)
size = len(n)
baseten = 0
for i in range(size):
baseten += numbers.index(n[i]) * input_base ** (size - 1 - i)
max_power = 0
while output_base ** (max_power + 1) <= baseten:
max_power += 1
result = ''
for i in range(max_power + 1):
coeff = baseten / output_base ** (max_power - i)
baseten -= coeff * output_base ** (max_power - i)
result += numbers[coeff]
return result
if __name__ == '__main__':
assert base_conv(10) == '10'
assert base_conv(42) == '42'
assert base_conv(5673576) == '5673576'
assert base_conv(10, input_base=2) == '2'
assert base_conv(101010, input_base=2) == '42'
assert base_conv(43, input_base=10, output_base=2) == '101011'
assert base_conv(256 ** 3 - 1, input_base=10, output_base=16) == 'ffffff'
assert base_conv('d9bbb9d0ceabf', input_base=16, output_base=8) == '154673563503165277'
assert base_conv('154673563503165277', input_base=8, output_base=10) == '3830404793297599'
assert base_conv(0, input_base=3, output_base=50) == '0' |
#a2_t1b.py
#This program is to convert Celsius to Kelvin
def c_to_k(c):
k = c + 273.15 #Formula to convert Celsius to Kelvin
return k
def f_to_c(f):
fa = (f-32) * 5/9 #Formula to convert Fareheit to Celsius
return fa
c = 25.0
f = 100.0
k = c_to_k(c)
fa = f_to_c(f)
print("Celsius of " + str(c) + " is " + str(k) + " in Kelvin")
print("Farenheit of " + str(f) + " is " + str(fa) + " in Celsius")
| def c_to_k(c):
k = c + 273.15
return k
def f_to_c(f):
fa = (f - 32) * 5 / 9
return fa
c = 25.0
f = 100.0
k = c_to_k(c)
fa = f_to_c(f)
print('Celsius of ' + str(c) + ' is ' + str(k) + ' in Kelvin')
print('Farenheit of ' + str(f) + ' is ' + str(fa) + ' in Celsius') |
"""This module contains the GeneFlow LocalWorkflow class."""
class LocalWorkflow:
"""
A class that represents the Local Workflow objects.
"""
def __init__(
self,
job,
config,
parsed_job_work_uri
):
"""
Instantiate LocalWorkflow class.
"""
self._job = job
self._config = config
self._parsed_job_work_uri = parsed_job_work_uri
def initialize(self):
"""
Initialize the LocalWorkflow class.
This workflow class has no additional functionality.
Args:
None.
Returns:
True.
"""
return True
def init_data(self):
"""
Initialize any data specific to this context.
"""
return True
def get_context_options(self):
"""
Return dict of options specific for this context.
Args:
None.
Returns:
{} - no options specific for this context.
"""
return {}
| """This module contains the GeneFlow LocalWorkflow class."""
class Localworkflow:
"""
A class that represents the Local Workflow objects.
"""
def __init__(self, job, config, parsed_job_work_uri):
"""
Instantiate LocalWorkflow class.
"""
self._job = job
self._config = config
self._parsed_job_work_uri = parsed_job_work_uri
def initialize(self):
"""
Initialize the LocalWorkflow class.
This workflow class has no additional functionality.
Args:
None.
Returns:
True.
"""
return True
def init_data(self):
"""
Initialize any data specific to this context.
"""
return True
def get_context_options(self):
"""
Return dict of options specific for this context.
Args:
None.
Returns:
{} - no options specific for this context.
"""
return {} |
# -*- coding: utf-8 -*-
def main():
s, t, u = map(str, input().split())
if len(s) == 5 and len(t) == 7 and len(u) == 5:
print('valid')
else:
print('invalid')
if __name__ == '__main__':
main()
| def main():
(s, t, u) = map(str, input().split())
if len(s) == 5 and len(t) == 7 and (len(u) == 5):
print('valid')
else:
print('invalid')
if __name__ == '__main__':
main() |
def buttonClick(button):
JS("""
var doc = button.ownerDocument;
if (doc != null) {
var evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, null, 0, 0,
0, 0, 0, false, false, false, false, 0, null);
button.dispatchEvent(evt);
}
""")
def compare(elem1, elem2):
JS("""
if (!elem1 && !elem2) {
return true;
} else if (!elem1 || !elem2) {
return false;
}
if (!elem1.isSameNode) {
return (elem1 == elem2);
}
return (elem1.isSameNode(elem2));
""")
def eventGetButton(evt):
JS("""
var button = evt.which;
if(button == 2) {
return 4;
} else if (button == 3) {
return 2;
} else {
return button || 0;
}
""")
# This is what is in GWT 1.5 for getAbsoluteLeft. err...
#"""
# // We cannot use DOMImpl here because offsetLeft/Top return erroneous
# // values when overflow is not visible. We have to difference screenX
# // here due to a change in getBoxObjectFor which causes inconsistencies
# // on whether the calculations are inside or outside of the element's
# // border.
# try {
# return $doc.getBoxObjectFor(elem).screenX
# - $doc.getBoxObjectFor($doc.documentElement).screenX;
# } catch (e) {
# // This works around a bug in the FF3 betas. The bug
# // should be fixed before they release, so this can
# // be removed at a later date.
# // https://bugzilla.mozilla.org/show_bug.cgi?id=409111
# // DOMException.WRONG_DOCUMENT_ERR == 4
# if (e.code == 4) {
# return 0;
# }
# throw e;
# }
#"""
def getAbsoluteLeft(elem):
JS("""
// Firefox 3 expects getBoundingClientRect
// getBoundingClientRect can be float: 73.1 instead of 74, see
// gwt's workaround at user/src/com/google/gwt/dom/client/DOMImplMozilla.java:47
// Please note, their implementation has 1px offset.
if ( typeof elem.getBoundingClientRect == 'function' ) {
var left = Math.ceil(elem.getBoundingClientRect().left);
return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft;
}
// Older Firefox can use getBoxObjectFor
else {
var left = $doc.getBoxObjectFor(elem).x;
var parent = elem.parentNode;
while (parent) {
if (parent.scrollLeft > 0) {
left = left - parent.scrollLeft;
}
parent = parent.parentNode;
}
return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft;
}
""")
# This is what is in GWT 1.5 for getAbsoluteTop. err...
#"""
# // We cannot use DOMImpl here because offsetLeft/Top return erroneous
# // values when overflow is not visible. We have to difference screenY
# // here due to a change in getBoxObjectFor which causes inconsistencies
# // on whether the calculations are inside or outside of the element's
# // border.
# try {
# return $doc.getBoxObjectFor(elem).screenY
# - $doc.getBoxObjectFor($doc.documentElement).screenY;
# } catch (e) {
# // This works around a bug in the FF3 betas. The bug
# // should be fixed before they release, so this can
# // be removed at a later date.
# // https://bugzilla.mozilla.org/show_bug.cgi?id=409111
# // DOMException.WRONG_DOCUMENT_ERR == 4
# if (e.code == 4) {
# return 0;
# }
# throw e;
# }
#"""
def getAbsoluteTop(elem):
JS("""
// Firefox 3 expects getBoundingClientRect
if ( typeof elem.getBoundingClientRect == 'function' ) {
var top = Math.ceil(elem.getBoundingClientRect().top);
return top + $doc.body.scrollTop + $doc.documentElement.scrollTop;
}
// Older Firefox can use getBoxObjectFor
else {
var top = $doc.getBoxObjectFor(elem).y;
var parent = elem.parentNode;
while (parent) {
if (parent.scrollTop > 0) {
top -= parent.scrollTop;
}
parent = parent.parentNode;
}
return top + $doc.body.scrollTop + $doc.documentElement.scrollTop;
}
""")
def getChildIndex(parent, child):
JS("""
var count = 0, current = parent.firstChild;
while (current) {
if (! current.isSameNode) {
if (current == child) {
return count;
}
}
else if (current.isSameNode(child)) {
return count;
}
if (current.nodeType == 1) {
++count;
}
current = current.nextSibling;
}
return -1;
""")
def isOrHasChild(parent, child):
JS("""
while (child) {
if ((!parent.isSameNode)) {
if (parent == child) {
return true;
}
}
else if (parent.isSameNode(child)) {
return true;
}
try {
child = child.parentNode;
} catch(e) {
// Give up on 'Permission denied to get property
// HTMLDivElement.parentNode'
// See https://bugzilla.mozilla.org/show_bug.cgi?id=208427
return false;
}
if (child && (child.nodeType != 1)) {
child = null;
}
}
return false;
""")
def releaseCapture(elem):
JS("""
if ((DOM.sCaptureElem != null) && DOM.compare(elem, DOM.sCaptureElem))
DOM.sCaptureElem = null;
if (!elem.isSameNode) {
if (elem == $wnd.__captureElem) {
$wnd.__captureElem = null;
}
}
else if (elem.isSameNode($wnd.__captureElem)) {
$wnd.__captureElem = null;
}
""")
| def button_click(button):
js("\n var doc = button.ownerDocument;\n if (doc != null) {\n var evt = doc.createEvent('MouseEvents');\n evt.initMouseEvent('click', true, true, null, 0, 0,\n 0, 0, 0, false, false, false, false, 0, null);\n button.dispatchEvent(evt);\n }\n ")
def compare(elem1, elem2):
js('\n if (!elem1 && !elem2) {\n return true;\n } else if (!elem1 || !elem2) {\n return false;\n }\n\tif (!elem1.isSameNode) {\n\t\treturn (elem1 == elem2);\n\t}\n return (elem1.isSameNode(elem2));\n ')
def event_get_button(evt):
js('\n var button = evt.which;\n if(button == 2) {\n return 4;\n } else if (button == 3) {\n return 2;\n } else {\n return button || 0;\n }\n ')
def get_absolute_left(elem):
js("\n // Firefox 3 expects getBoundingClientRect\n // getBoundingClientRect can be float: 73.1 instead of 74, see\n // gwt's workaround at user/src/com/google/gwt/dom/client/DOMImplMozilla.java:47\n // Please note, their implementation has 1px offset.\n if ( typeof elem.getBoundingClientRect == 'function' ) {\n var left = Math.ceil(elem.getBoundingClientRect().left);\n \n return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft;\n }\n // Older Firefox can use getBoxObjectFor\n else {\n var left = $doc.getBoxObjectFor(elem).x;\n var parent = elem.parentNode;\n while (parent) {\n if (parent.scrollLeft > 0) {\n left = left - parent.scrollLeft;\n }\n parent = parent.parentNode;\n }\n \n return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft;\n }\n ")
def get_absolute_top(elem):
js("\n // Firefox 3 expects getBoundingClientRect\n if ( typeof elem.getBoundingClientRect == 'function' ) {\n var top = Math.ceil(elem.getBoundingClientRect().top);\n return top + $doc.body.scrollTop + $doc.documentElement.scrollTop;\n }\n // Older Firefox can use getBoxObjectFor\n else {\n var top = $doc.getBoxObjectFor(elem).y;\n var parent = elem.parentNode;\n while (parent) {\n if (parent.scrollTop > 0) {\n top -= parent.scrollTop;\n }\n parent = parent.parentNode;\n }\n \n return top + $doc.body.scrollTop + $doc.documentElement.scrollTop;\n }\n ")
def get_child_index(parent, child):
js('\n var count = 0, current = parent.firstChild;\n while (current) {\n\t\tif (! current.isSameNode) {\n\t\t\tif (current == child) {\n\t\t\treturn count;\n\t\t\t}\n\t\t}\n\t\telse if (current.isSameNode(child)) {\n return count;\n }\n if (current.nodeType == 1) {\n ++count;\n }\n current = current.nextSibling;\n }\n return -1;\n ')
def is_or_has_child(parent, child):
js("\n while (child) {\n if ((!parent.isSameNode)) {\n\t\t\tif (parent == child) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (parent.isSameNode(child)) {\n return true;\n }\n try {\n child = child.parentNode;\n } catch(e) {\n // Give up on 'Permission denied to get property\n // HTMLDivElement.parentNode'\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=208427\n return false;\n }\n if (child && (child.nodeType != 1)) {\n child = null;\n }\n }\n return false;\n ")
def release_capture(elem):
js('\n if ((DOM.sCaptureElem != null) && DOM.compare(elem, DOM.sCaptureElem))\n DOM.sCaptureElem = null;\n \n\tif (!elem.isSameNode) {\n\t\tif (elem == $wnd.__captureElem) {\n\t\t\t$wnd.__captureElem = null;\n\t\t}\n\t}\n\telse if (elem.isSameNode($wnd.__captureElem)) {\n $wnd.__captureElem = null;\n }\n ') |
"""
Demonstration of numbers in Python
"""
# Python has an integer type called int
print("int")
print("---")
print(0)
print(1)
print(-3)
print(70383028364830)
print("")
# Python has a real number type called float
print("float")
print("-----")
print(0.0)
print(7.35)
print(-43.2)
print("")
# Limited precision
print("Precision")
print("---------")
print(4.56372883832331773)
print(1.23456789012345678)
print("")
# Scientific/exponential notation
print("Scientific notation")
print("-------------------")
print(5e32)
print(999999999999999999999999999999999999999.9)
print("")
# Infinity
print("Infinity")
print("--------")
print(1e500)
print(-1e500)
print("")
# Conversions
print("Conversions between numeric types")
print("---------------------------------")
print(float(3))
print(float(99999999999999999999999999999999999999))
print(int(3.0))
print(int(3.7))
print(int(-3.7))
"""
Demonstration of simple arithmetic expressions in Python
"""
# Unary + and -
print("Unary operators")
print(+3)
print(-5)
print(+7.86)
print(-3348.63)
print("")
# Simple arithmetic
print("Addition and Subtraction")
print(1 + 2)
print(48 - 89)
print(3.45 + 2.7)
print(87.3384 - 12.35)
print(3 + 6.7)
print(9.8 - 4)
print("")
print("Multiplication")
print(3 * 2)
print(7.8 * 27.54)
print(7 * 8.2)
print("")
print("Division")
print(8 / 2)
print(3 / 2)
print(7.538 / 14.3)
print(8 // 2)
print(3 // 2)
print(7.538 // 14.3)
print("")
print("Exponentiation")
print(3 ** 2)
print(5 ** 4)
print(32.6 ** 7)
print(9 ** 0.5)
"""
Demonstration of compound arithmetic expressions in Python
"""
# Expressions can include multiple operations
print("Compound expressions")
print(3 + 5 + 7 + 27)
#Operator with same precedence are evaluated from left to right
print(18 - 6 + 4)
print("")
# Operator precedence defines how expressions are evaluated
print("Operator precedence")
print(7 + 3 * 5)
print(5.5 * 6 // 2 + 8)
print(-3 ** 2)
print("")
# Use parentheses to change evaluation order
print("Grouping with parentheses")
print((7 + 3) * 5)
print(5.5 * ((6 // 2) + 8))
print((-3) ** 2)
"""
Demonstration of the use of variables and how to assign values to
them.
"""
# The = operator can be used to assign values to variables
bakers_dozen = 12 + 1
temperature = 93
# Variables can be used as values and in expressions
print(temperature, bakers_dozen)
print("celsius:", (temperature - 32) * 5 / 9)
print("fahrenheit:", float(temperature))
# You can assign a different value to an existing variable
temperature = 26
print("new value:", temperature)
# Multiple variables can be used in arbitrary expressions
offset = 32
multiplier = 5.0 / 9.0
celsius = (temperature - offset) * multiplier
print("celsius value:", celsius)
| """
Demonstration of numbers in Python
"""
print('int')
print('---')
print(0)
print(1)
print(-3)
print(70383028364830)
print('')
print('float')
print('-----')
print(0.0)
print(7.35)
print(-43.2)
print('')
print('Precision')
print('---------')
print(4.563728838323318)
print(1.2345678901234567)
print('')
print('Scientific notation')
print('-------------------')
print(5e+32)
print(1e+39)
print('')
print('Infinity')
print('--------')
print(1e309)
print(-1e309)
print('')
print('Conversions between numeric types')
print('---------------------------------')
print(float(3))
print(float(99999999999999999999999999999999999999))
print(int(3.0))
print(int(3.7))
print(int(-3.7))
'\nDemonstration of simple arithmetic expressions in Python\n'
print('Unary operators')
print(+3)
print(-5)
print(+7.86)
print(-3348.63)
print('')
print('Addition and Subtraction')
print(1 + 2)
print(48 - 89)
print(3.45 + 2.7)
print(87.3384 - 12.35)
print(3 + 6.7)
print(9.8 - 4)
print('')
print('Multiplication')
print(3 * 2)
print(7.8 * 27.54)
print(7 * 8.2)
print('')
print('Division')
print(8 / 2)
print(3 / 2)
print(7.538 / 14.3)
print(8 // 2)
print(3 // 2)
print(7.538 // 14.3)
print('')
print('Exponentiation')
print(3 ** 2)
print(5 ** 4)
print(32.6 ** 7)
print(9 ** 0.5)
'\nDemonstration of compound arithmetic expressions in Python\n'
print('Compound expressions')
print(3 + 5 + 7 + 27)
print(18 - 6 + 4)
print('')
print('Operator precedence')
print(7 + 3 * 5)
print(5.5 * 6 // 2 + 8)
print(-3 ** 2)
print('')
print('Grouping with parentheses')
print((7 + 3) * 5)
print(5.5 * (6 // 2 + 8))
print((-3) ** 2)
'\nDemonstration of the use of variables and how to assign values to\nthem.\n'
bakers_dozen = 12 + 1
temperature = 93
print(temperature, bakers_dozen)
print('celsius:', (temperature - 32) * 5 / 9)
print('fahrenheit:', float(temperature))
temperature = 26
print('new value:', temperature)
offset = 32
multiplier = 5.0 / 9.0
celsius = (temperature - offset) * multiplier
print('celsius value:', celsius) |
# Natural Language Toolkit: Language Models
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
class ModelI(object):
"""
A processing interface for assigning a probability to the next word.
"""
def __init__(self):
'''Create a new language model.'''
raise NotImplementedError()
def train(self, text):
'''Train the model on the text.'''
raise NotImplementedError()
def probability(self, word, context):
'''Evaluate the probability of this word in this context.'''
raise NotImplementedError()
def choose_random_word(self, context):
'''Randomly select a word that is likely to appear in this context.'''
raise NotImplementedError()
def entropy(self, text):
'''Evaluate the total entropy of a message with respect to the model.
This is the sum of the log probability of each word in the message.'''
raise NotImplementedError()
| class Modeli(object):
"""
A processing interface for assigning a probability to the next word.
"""
def __init__(self):
"""Create a new language model."""
raise not_implemented_error()
def train(self, text):
"""Train the model on the text."""
raise not_implemented_error()
def probability(self, word, context):
"""Evaluate the probability of this word in this context."""
raise not_implemented_error()
def choose_random_word(self, context):
"""Randomly select a word that is likely to appear in this context."""
raise not_implemented_error()
def entropy(self, text):
"""Evaluate the total entropy of a message with respect to the model.
This is the sum of the log probability of each word in the message."""
raise not_implemented_error() |
def aaa():
# trick sphinx to build link in doc
pass
# retired
ibmqx2_c_to_tars =\
{
0: [1, 2],
1: [2],
2: [],
3: [2, 4],
4: [2]
} # 6 edges
# retired
ibmqx4_c_to_tars =\
{
0: [],
1: [0],
2: [0, 1, 4],
3: [2, 4],
4: []
} # 6 edges
# retired
ibmq16Rus_c_to_tars = \
{
0: [],
1: [0, 2],
2: [3],
3: [4, 14],
4: [],
5: [4],
6: [5, 7, 11],
7: [10],
8: [7],
9: [8, 10],
10: [],
11: [10],
12: [5, 11, 13],
13: [4, 14],
14: [],
15: [0, 2, 14]
} # 22 edges
ibm20AustinTokyo_c_to_tars = \
{
0: [1, 5],
1: [0, 2, 6, 7],
2: [1, 3, 6, 7],
3: [2, 4, 8, 9],
4: [3, 8, 9],
5: [0, 6, 10, 11],
6: [1, 2, 5, 7, 10, 11],
7: [1, 2, 6, 8, 12, 13],
8: [3, 4, 7, 9, 12, 13],
9: [3, 4, 8, 14],
10: [5, 6, 11, 15],
11: [5, 6, 10, 12, 16, 17],
12: [7, 8, 11, 13, 16, 17],
13: [7, 8, 12, 14, 18, 19],
14: [9, 13, 18, 19],
15: [10, 16],
16: [11, 12, 15, 17],
17: [11, 12, 16, 18],
18: [13, 14, 17, 19],
19: [13, 14, 18]
} # 86 edges
ibmq5YorktownTenerife_c_to_tars = \
{
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 4],
3: [2, 4],
4: [2, 3]
} # 12 edges
ibmq14Melb_c_to_tars = \
{
0: [1],
1: [0, 2, 13],
2: [1, 3, 12],
3: [2, 4, 11],
4: [3, 5, 10],
5: [4, 6, 9],
6: [5, 8],
7: [8],
8: [6, 7, 9],
9: [5, 8, 10],
10: [4, 9, 11],
11: [3, 10, 12],
12: [2, 11, 13],
13: [1, 12]
} # 36 edges
| def aaa():
pass
ibmqx2_c_to_tars = {0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2]}
ibmqx4_c_to_tars = {0: [], 1: [0], 2: [0, 1, 4], 3: [2, 4], 4: []}
ibmq16_rus_c_to_tars = {0: [], 1: [0, 2], 2: [3], 3: [4, 14], 4: [], 5: [4], 6: [5, 7, 11], 7: [10], 8: [7], 9: [8, 10], 10: [], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14: [], 15: [0, 2, 14]}
ibm20_austin_tokyo_c_to_tars = {0: [1, 5], 1: [0, 2, 6, 7], 2: [1, 3, 6, 7], 3: [2, 4, 8, 9], 4: [3, 8, 9], 5: [0, 6, 10, 11], 6: [1, 2, 5, 7, 10, 11], 7: [1, 2, 6, 8, 12, 13], 8: [3, 4, 7, 9, 12, 13], 9: [3, 4, 8, 14], 10: [5, 6, 11, 15], 11: [5, 6, 10, 12, 16, 17], 12: [7, 8, 11, 13, 16, 17], 13: [7, 8, 12, 14, 18, 19], 14: [9, 13, 18, 19], 15: [10, 16], 16: [11, 12, 15, 17], 17: [11, 12, 16, 18], 18: [13, 14, 17, 19], 19: [13, 14, 18]}
ibmq5_yorktown_tenerife_c_to_tars = {0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 4], 3: [2, 4], 4: [2, 3]}
ibmq14_melb_c_to_tars = {0: [1], 1: [0, 2, 13], 2: [1, 3, 12], 3: [2, 4, 11], 4: [3, 5, 10], 5: [4, 6, 9], 6: [5, 8], 7: [8], 8: [6, 7, 9], 9: [5, 8, 10], 10: [4, 9, 11], 11: [3, 10, 12], 12: [2, 11, 13], 13: [1, 12]} |
class Donation_text:
# Shown as a message across the top of the page on return from a donation
# used in views.py:new_donation()
thank_you = (
"Thank you for your donation. "
"You may need to refresh this page to see the donation."
)
confirmation_email_subject = (
'Thank you for donating to the Triple Crown for Heart! '
)
# Start of the email sent confirming the paypal payment has gone through
# used in paypal.py:process_paypal()
confirmation_email_opening = (
'Thank you for your donation of '
)
# Closing of the email sent confirming the paypal payment has gone through
# used in paypal.py:process_paypal()
confirmation_email_closing = (
'.\n\nFor all donations over $20, you will receive a tax receipt for '
'the 2019 tax year.'
'\nYour PayPal receipt should arrive in a separate email.\n'
)
notification_email_subject = (
"You got a donation!"
)
notification_email_opening = (
"Great news! You've just received a donation of "
)
notification_email_closing = (
"\n\nAwesome work! They would probably appreciate "
"a quick thank you email.\n\n"
"-- Triple Crown for Heart\n"
)
class Fundraiser_text:
# Subject of the email sent on signup
signup_email_subject = (
"Welcome to fundraising for the Triple Crown for Heart!"
)
# Start of the email sent when someone signs up
# used in views.py:signup()
signup_email_opening = (
"Thanks for signing up to fundraise with us!\n"
"Your fundraising page can be found at:\n"
)
# Closing of the email sent when someone signs up
# used in views.py:signup()
signup_email_closing = (
'\n\nYou can change your information by using the "Login" link at the '
'top of that page.'
'\n\nThe easiest way to start fundraising is to post the above link '
'on social media or write a short email to your friends telling them '
'about your ride.'
'\nDon\'t forget to include the link to your page!\n'
)
# Message show at the top of the fundraiser page after signing up
# used in views.py:signup()
signup_return_message = (
"Thank you for signing up. Sharing your fundraiser page on social "
"media or over email is the best way to get donations."
)
signup_wrong_password_existing_user = (
"The username already exists, but the password entered is incorrect. "
"If you were already a fundraiser for a previous campaign, please "
"enter your previous password or use "
"<a href='/team_fundraising/accounts/password_reset/'>"
"Forgot your password</a>. If this is your first campaign, "
"please choose a different username."
)
| class Donation_Text:
thank_you = 'Thank you for your donation. You may need to refresh this page to see the donation.'
confirmation_email_subject = 'Thank you for donating to the Triple Crown for Heart! '
confirmation_email_opening = 'Thank you for your donation of '
confirmation_email_closing = '.\n\nFor all donations over $20, you will receive a tax receipt for the 2019 tax year.\nYour PayPal receipt should arrive in a separate email.\n'
notification_email_subject = 'You got a donation!'
notification_email_opening = "Great news! You've just received a donation of "
notification_email_closing = '\n\nAwesome work! They would probably appreciate a quick thank you email.\n\n-- Triple Crown for Heart\n'
class Fundraiser_Text:
signup_email_subject = 'Welcome to fundraising for the Triple Crown for Heart!'
signup_email_opening = 'Thanks for signing up to fundraise with us!\nYour fundraising page can be found at:\n'
signup_email_closing = '\n\nYou can change your information by using the "Login" link at the top of that page.\n\nThe easiest way to start fundraising is to post the above link on social media or write a short email to your friends telling them about your ride.\nDon\'t forget to include the link to your page!\n'
signup_return_message = 'Thank you for signing up. Sharing your fundraiser page on social media or over email is the best way to get donations.'
signup_wrong_password_existing_user = "The username already exists, but the password entered is incorrect. If you were already a fundraiser for a previous campaign, please enter your previous password or use <a href='/team_fundraising/accounts/password_reset/'>Forgot your password</a>. If this is your first campaign, please choose a different username." |
class Yaratik(object):
def move_left(self):
print('Moving left...')
def move_right(self):
print('Moving left...')
class Ejderha(Yaratik):
def Ates_puskurtme(self):
print('ates puskurtum!')
class Zombie(Yaratik):
def Isirmak(self):
print('Isirdim simdi!')
enemy = Yaratik()
enemy.move_left()
# ejderha also includes all functions from parent class (yaratik)
ejderha = Ejderha()
ejderha.move_left()
ejderha.Ates_puskurtme()
# Zombie is called the (child class), inherits from Yaratik (parent class)
zombie = Zombie()
zombie.move_right()
zombie.Isirmak()
| class Yaratik(object):
def move_left(self):
print('Moving left...')
def move_right(self):
print('Moving left...')
class Ejderha(Yaratik):
def ates_puskurtme(self):
print('ates puskurtum!')
class Zombie(Yaratik):
def isirmak(self):
print('Isirdim simdi!')
enemy = yaratik()
enemy.move_left()
ejderha = ejderha()
ejderha.move_left()
ejderha.Ates_puskurtme()
zombie = zombie()
zombie.move_right()
zombie.Isirmak() |
class Solution:
def nextGreatestLetter(self, letters: list, target: str) -> str:
if target < letters[0] or target >= letters[-1]:
return letters[0]
left, right = 0, len(letters) - 1
while left < right:
mid = left + (right - left) // 2
if letters[mid] > target:
right = mid
else:
left = mid + 1
return letters[right]
if __name__ == '__main__':
letters = ["c", "f", "j"]
target = "a"
print(f"Input: letters = {letters}, target = {target}")
print(f"Output: {Solution().nextGreatestLetter(letters, target)}")
| class Solution:
def next_greatest_letter(self, letters: list, target: str) -> str:
if target < letters[0] or target >= letters[-1]:
return letters[0]
(left, right) = (0, len(letters) - 1)
while left < right:
mid = left + (right - left) // 2
if letters[mid] > target:
right = mid
else:
left = mid + 1
return letters[right]
if __name__ == '__main__':
letters = ['c', 'f', 'j']
target = 'a'
print(f'Input: letters = {letters}, target = {target}')
print(f'Output: {solution().nextGreatestLetter(letters, target)}') |
my_set = {1, 3, 5}
my_dict = {'name': 'Jose', 'age': 90}
another_dict = {1: 15, 2: 75, 3: 150}
lottery_players = [
{
'name': 'Rolf',
'numbers': (13, 45, 66, 23, 22)
},
{
'name': 'John',
'numbers': (14, 56, 80, 23, 22)
}
]
universities = [
{
'name': 'Oxford',
'location': 'UK'
},
{
'name': 'MIT',
'location': 'US'
}
] | my_set = {1, 3, 5}
my_dict = {'name': 'Jose', 'age': 90}
another_dict = {1: 15, 2: 75, 3: 150}
lottery_players = [{'name': 'Rolf', 'numbers': (13, 45, 66, 23, 22)}, {'name': 'John', 'numbers': (14, 56, 80, 23, 22)}]
universities = [{'name': 'Oxford', 'location': 'UK'}, {'name': 'MIT', 'location': 'US'}] |
""" Various generic env utilties. """
def center_crop_img(img, crop_zoom):
""" crop_zoom is amount to "zoom" into the image. E.g. 2.0 would cut out half of the width,
half of the height, and only give the center. """
raw_height, raw_width = img.shape[:2]
center = raw_height // 2, raw_width // 2
crop_size = raw_height // crop_zoom, raw_width // crop_zoom
min_y, max_y = int(center[0] - crop_size[0] // 2), int(center[0] + crop_size[0] // 2)
min_x, max_x = int(center[1] - crop_size[1] // 2), int(center[1] + crop_size[1] // 2)
img_cropped = img[min_y:max_y, min_x:max_x]
return img_cropped
def crop_img(img, relative_corners):
""" relative_corners are floats between 0 and 1 designating where the corners of a crop box
should be ([[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]]).
e.g. [[0, 0], [1, 1]] would be the full image, [[0.5, 0.5], [1, 1]] would be bottom right."""
rc = relative_corners
raw_height, raw_width = img.shape[:2]
top_left_pix = [int(rc[0][0] * raw_width), int(rc[0][1] * raw_height)]
bottom_right_pix = [int(rc[1][0] * raw_width), int(rc[1][1] * raw_height)]
img_cropped = img[top_left_pix[1]:bottom_right_pix[1], top_left_pix[0]:bottom_right_pix[0]]
return img_cropped | """ Various generic env utilties. """
def center_crop_img(img, crop_zoom):
""" crop_zoom is amount to "zoom" into the image. E.g. 2.0 would cut out half of the width,
half of the height, and only give the center. """
(raw_height, raw_width) = img.shape[:2]
center = (raw_height // 2, raw_width // 2)
crop_size = (raw_height // crop_zoom, raw_width // crop_zoom)
(min_y, max_y) = (int(center[0] - crop_size[0] // 2), int(center[0] + crop_size[0] // 2))
(min_x, max_x) = (int(center[1] - crop_size[1] // 2), int(center[1] + crop_size[1] // 2))
img_cropped = img[min_y:max_y, min_x:max_x]
return img_cropped
def crop_img(img, relative_corners):
""" relative_corners are floats between 0 and 1 designating where the corners of a crop box
should be ([[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]]).
e.g. [[0, 0], [1, 1]] would be the full image, [[0.5, 0.5], [1, 1]] would be bottom right."""
rc = relative_corners
(raw_height, raw_width) = img.shape[:2]
top_left_pix = [int(rc[0][0] * raw_width), int(rc[0][1] * raw_height)]
bottom_right_pix = [int(rc[1][0] * raw_width), int(rc[1][1] * raw_height)]
img_cropped = img[top_left_pix[1]:bottom_right_pix[1], top_left_pix[0]:bottom_right_pix[0]]
return img_cropped |
# -*- coding: utf-8 -*-
def docstring_property(class_doc):
"""Property attribute for docstrings.
Took from: https://gist.github.com/bfroehle/4041015
>>> class A(object):
... '''Main docstring'''
... def __init__(self, x):
... self.x = x
... @docstring_property(__doc__)
... def __doc__(self):
... return "My value of x is %s." % self.x
>>> A.__doc__
'Main docstring'
>>> a = A(10)
>>> a.__doc__
'My value of x is 10.'
"""
def wrapper(fget):
return DocstringProperty(class_doc, fget)
return wrapper
class DocstringProperty(object):
"""Property for the `__doc__` attribute.
Different than `property` in the following two ways:
* When the attribute is accessed from the main class, it returns the value
of `class_doc`, *not* the property itself. This is necessary so Sphinx
and other documentation tools can access the class docstring.
* Only supports getting the attribute; setting and deleting raise an
`AttributeError`.
"""
def __init__(self, class_doc, fget):
self.class_doc = class_doc
self.fget = fget
def __get__(self, obj, type=None):
if obj is None:
return self.class_doc
else:
return self.fget(obj)
def __set__(self, obj, value):
raise AttributeError("can't set attribute")
def __delete__(self, obj):
raise AttributeError("can't delete attribute")
| def docstring_property(class_doc):
"""Property attribute for docstrings.
Took from: https://gist.github.com/bfroehle/4041015
>>> class A(object):
... '''Main docstring'''
... def __init__(self, x):
... self.x = x
... @docstring_property(__doc__)
... def __doc__(self):
... return "My value of x is %s." % self.x
>>> A.__doc__
'Main docstring'
>>> a = A(10)
>>> a.__doc__
'My value of x is 10.'
"""
def wrapper(fget):
return docstring_property(class_doc, fget)
return wrapper
class Docstringproperty(object):
"""Property for the `__doc__` attribute.
Different than `property` in the following two ways:
* When the attribute is accessed from the main class, it returns the value
of `class_doc`, *not* the property itself. This is necessary so Sphinx
and other documentation tools can access the class docstring.
* Only supports getting the attribute; setting and deleting raise an
`AttributeError`.
"""
def __init__(self, class_doc, fget):
self.class_doc = class_doc
self.fget = fget
def __get__(self, obj, type=None):
if obj is None:
return self.class_doc
else:
return self.fget(obj)
def __set__(self, obj, value):
raise attribute_error("can't set attribute")
def __delete__(self, obj):
raise attribute_error("can't delete attribute") |
class PaintEventArgs(EventArgs,IDisposable):
"""
Provides data for the System.Windows.Forms.Control.Paint event.
PaintEventArgs(graphics: Graphics,clipRect: Rectangle)
"""
def Instance(self):
""" This function has been arbitrarily put into the stubs"""
return PaintEventArgs()
def Dispose(self):
"""
Dispose(self: PaintEventArgs)
Releases all resources used by the System.Windows.Forms.PaintEventArgs.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,graphics,clipRect):
""" __new__(cls: type,graphics: Graphics,clipRect: Rectangle) """
pass
ClipRectangle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the rectangle in which to paint.
Get: ClipRectangle(self: PaintEventArgs) -> Rectangle
"""
Graphics=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the graphics used to paint.
Get: Graphics(self: PaintEventArgs) -> Graphics
"""
| class Painteventargs(EventArgs, IDisposable):
"""
Provides data for the System.Windows.Forms.Control.Paint event.
PaintEventArgs(graphics: Graphics,clipRect: Rectangle)
"""
def instance(self):
""" This function has been arbitrarily put into the stubs"""
return paint_event_args()
def dispose(self):
"""
Dispose(self: PaintEventArgs)
Releases all resources used by the System.Windows.Forms.PaintEventArgs.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, graphics, clipRect):
""" __new__(cls: type,graphics: Graphics,clipRect: Rectangle) """
pass
clip_rectangle = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the rectangle in which to paint.\n\n\n\nGet: ClipRectangle(self: PaintEventArgs) -> Rectangle\n\n\n\n'
graphics = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the graphics used to paint.\n\n\n\nGet: Graphics(self: PaintEventArgs) -> Graphics\n\n\n\n' |
# Copyright (c) 2006- Facebook
# Distributed under the Thrift Software License
#
# See accompanying file LICENSE or visit the Thrift site at:
# http://developers.facebook.com/thrift/
class TType:
STOP = 0
VOID = 1
BOOL = 2
BYTE = 3
I08 = 3
DOUBLE = 4
I16 = 6
I32 = 8
I64 = 10
STRING = 11
UTF7 = 11
STRUCT = 12
MAP = 13
SET = 14
LIST = 15
UTF8 = 16
UTF16 = 17
class TMessageType:
CALL = 1
REPLY = 2
EXCEPTION = 3
class TProcessor:
"""Base class for procsessor, which works on two streams."""
def process(iprot, oprot):
pass
class TException(Exception):
"""Base class for all thrift exceptions."""
def __init__(self, message=None):
Exception.__init__(self, message)
self.message = message
class TApplicationException(TException):
"""Application level thrift exceptions."""
UNKNOWN = 0
UNKNOWN_METHOD = 1
INVALID_MESSAGE_TYPE = 2
WRONG_METHOD_NAME = 3
BAD_SEQUENCE_ID = 4
MISSING_RESULT = 5
def __init__(self, type=UNKNOWN, message=None):
TException.__init__(self, message)
self.type = type
def __str__(self):
if self.message:
return self.message
elif self.type == UNKNOWN_METHOD:
return 'Unknown method'
elif self.type == INVALID_MESSAGE_TYPE:
return 'Invalid message type'
elif self.type == WRONG_METHOD_NAME:
return 'Wrong method name'
elif self.type == BAD_SEQUENCE_ID:
return 'Bad sequence ID'
elif self.type == MISSING_RESULT:
return 'Missing result'
else:
return 'Default (unknown) TApplicationException'
def read(self, iprot):
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.message = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.type = iprot.readI32();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
oprot.writeStructBegin('TApplicationException')
if self.message != None:
oprot.writeFieldBegin('message', TType.STRING, 1)
oprot.writeString(self.message)
oprot.writeFieldEnd()
if self.type != None:
oprot.writeFieldBegin('type', TType.I32, 2)
oprot.writeI32(self.type)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
| class Ttype:
stop = 0
void = 1
bool = 2
byte = 3
i08 = 3
double = 4
i16 = 6
i32 = 8
i64 = 10
string = 11
utf7 = 11
struct = 12
map = 13
set = 14
list = 15
utf8 = 16
utf16 = 17
class Tmessagetype:
call = 1
reply = 2
exception = 3
class Tprocessor:
"""Base class for procsessor, which works on two streams."""
def process(iprot, oprot):
pass
class Texception(Exception):
"""Base class for all thrift exceptions."""
def __init__(self, message=None):
Exception.__init__(self, message)
self.message = message
class Tapplicationexception(TException):
"""Application level thrift exceptions."""
unknown = 0
unknown_method = 1
invalid_message_type = 2
wrong_method_name = 3
bad_sequence_id = 4
missing_result = 5
def __init__(self, type=UNKNOWN, message=None):
TException.__init__(self, message)
self.type = type
def __str__(self):
if self.message:
return self.message
elif self.type == UNKNOWN_METHOD:
return 'Unknown method'
elif self.type == INVALID_MESSAGE_TYPE:
return 'Invalid message type'
elif self.type == WRONG_METHOD_NAME:
return 'Wrong method name'
elif self.type == BAD_SEQUENCE_ID:
return 'Bad sequence ID'
elif self.type == MISSING_RESULT:
return 'Missing result'
else:
return 'Default (unknown) TApplicationException'
def read(self, iprot):
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.message = iprot.readString()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.type = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
oprot.writeStructBegin('TApplicationException')
if self.message != None:
oprot.writeFieldBegin('message', TType.STRING, 1)
oprot.writeString(self.message)
oprot.writeFieldEnd()
if self.type != None:
oprot.writeFieldBegin('type', TType.I32, 2)
oprot.writeI32(self.type)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd() |
class Solution:
def XXX(self, x: int) -> int:
def solve(x):
a = list(map(int,str(x)))
p = {}
d=0
for ind, val in enumerate(a):
p[ind] = val
for i, v in p.items():
d += v*(10**i)
if (2**31 - 1>= d >= -(2**31)):
return d
else:
return 0
if x>=0:
return (solve(x))
if x<0:
x = -x
return (-solve(x))
| class Solution:
def xxx(self, x: int) -> int:
def solve(x):
a = list(map(int, str(x)))
p = {}
d = 0
for (ind, val) in enumerate(a):
p[ind] = val
for (i, v) in p.items():
d += v * 10 ** i
if 2 ** 31 - 1 >= d >= -2 ** 31:
return d
else:
return 0
if x >= 0:
return solve(x)
if x < 0:
x = -x
return -solve(x) |
#------ game constants -----#
#players
WHITE = 0
BLACK = 1
BOTH = 2
#color for onTurnLabel
PLAYER_COLOR = ["white", "black"]
#figures
PAWN = 1
KNIGHT = 2
BISHOP = 3
ROOK = 4
QUEEN = 5
KING = 6
FIGURE_NAME = [ "", "pawn", "knight", "bishop", "rook", "queen", "king" ]
#used in move 32bit for promotion figure prom_figure = figure-2
PROM_KNIGHT = 0
PROM_BISHOP = 1
PROM_ROOK = 2
PROM_QUEEN = 3
#all lines
A, B, C, D, E, F, G, H = range(8)
#all squares
A1, B1, C1, D1, E1, F1, G1, H1, \
A2, B2, C2, D2, E2, F2, G2, H2, \
A3, B3, C3, D3, E3, F3, G3, H3, \
A4, B4, C4, D4, E4, F4, G4, H4, \
A5, B5, C5, D5, E5, F5, G5, H5, \
A6, B6, C6, D6, E6, F6, G6, H6, \
A7, B7, C7, D7, E7, F7, G7, H7, \
A8, B8, C8, D8, E8, F8, G8, H8 = range(64)
#----- game display constants -----#
DEFAULTBORDERWIDTH = 20
DEFAULTTILEWIDTH = 45
DEFAULTFONTSIZE = (7, 15)
COLORS = { "bg":"#EDC08C",
"border":"#B55602",
"tiles":("#FC9235", "#FFB87A") }
#----- move types -----#
NORMAL_MOVE, CAPTURE, PROMOTION, DOUBLE_STEP, ENPASSANT_CAPTURE, CASTLING, KING_CAPTURE = range(7)
#----- move 32bit reservation -----#
# a single move is stored in 32 bit as follows
# xxxxxxxx xx x xxx xxx xxxxxx xxxxxx xxx
# G F E D C B A
#
# A: move type (0-6)
# B: start sq (0-63)
# C: destination sq (0-63)
# D: start figure (1-6)
# E: captured figure (1-6)
# F: color of moved piece (0-1)
# G: promotion figure (0-3)
#NAME = (start_bit, lenght)
MOVE_TYPE = (0, 3)
MOVE_START = (3, 6)
MOVE_DEST = (9, 6)
MOVE_FIG_START = (15, 3)
MOVE_FIG_CAPTURE = (18, 3)
MOVE_COLOR = (21, 1)
MOVE_PROM = (22, 2)
#----- castling -----#
CASTLING_LEFT = 0
CASTLING_RIGHT = 1
#----- player status -----#
IDELING = 0
PICKING = 1
INF = 1000000
ASCII_FIG = [[],[]]
ASCII_FIG[WHITE] = [ 'x', chr(9817), chr(9816), chr(9815), chr(9814), chr(9813), chr(9812)]
ASCII_FIG[BLACK] = [ 'x', chr(9823), chr(9822), chr(9821), chr(9820), chr(9819), chr(9818)]
#AI constants
CASTLING_RIGHT_LOSS_PENALTY = -40
| white = 0
black = 1
both = 2
player_color = ['white', 'black']
pawn = 1
knight = 2
bishop = 3
rook = 4
queen = 5
king = 6
figure_name = ['', 'pawn', 'knight', 'bishop', 'rook', 'queen', 'king']
prom_knight = 0
prom_bishop = 1
prom_rook = 2
prom_queen = 3
(a, b, c, d, e, f, g, h) = range(8)
(a1, b1, c1, d1, e1, f1, g1, h1, a2, b2, c2, d2, e2, f2, g2, h2, a3, b3, c3, d3, e3, f3, g3, h3, a4, b4, c4, d4, e4, f4, g4, h4, a5, b5, c5, d5, e5, f5, g5, h5, a6, b6, c6, d6, e6, f6, g6, h6, a7, b7, c7, d7, e7, f7, g7, h7, a8, b8, c8, d8, e8, f8, g8, h8) = range(64)
defaultborderwidth = 20
defaulttilewidth = 45
defaultfontsize = (7, 15)
colors = {'bg': '#EDC08C', 'border': '#B55602', 'tiles': ('#FC9235', '#FFB87A')}
(normal_move, capture, promotion, double_step, enpassant_capture, castling, king_capture) = range(7)
move_type = (0, 3)
move_start = (3, 6)
move_dest = (9, 6)
move_fig_start = (15, 3)
move_fig_capture = (18, 3)
move_color = (21, 1)
move_prom = (22, 2)
castling_left = 0
castling_right = 1
ideling = 0
picking = 1
inf = 1000000
ascii_fig = [[], []]
ASCII_FIG[WHITE] = ['x', chr(9817), chr(9816), chr(9815), chr(9814), chr(9813), chr(9812)]
ASCII_FIG[BLACK] = ['x', chr(9823), chr(9822), chr(9821), chr(9820), chr(9819), chr(9818)]
castling_right_loss_penalty = -40 |
class BST:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
@staticmethod
def array2BST(array):
'''
array:sorted array
'''
n = len(array)
if n == 0: return None
m = n//2
left,root,right = array[:m],array[m],array[m+1:]
return BST(root,BST.array2BST(left),BST.array2BST(right))
@staticmethod
def BST2array(node):
'''
node:BST node
'''
if not node: return []
return BST.BST2array(node.left)+[node.val]+BST.BST2array(node.right) | class Bst:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
@staticmethod
def array2_bst(array):
"""
array:sorted array
"""
n = len(array)
if n == 0:
return None
m = n // 2
(left, root, right) = (array[:m], array[m], array[m + 1:])
return bst(root, BST.array2BST(left), BST.array2BST(right))
@staticmethod
def bst2array(node):
"""
node:BST node
"""
if not node:
return []
return BST.BST2array(node.left) + [node.val] + BST.BST2array(node.right) |
TANGO_PALLETE = [
'2e2e34343636',
'cccc00000000',
'4e4e9a9a0606',
'c4c4a0a00000',
'34346565a4a4',
'757550507b7b',
'060698989a9a',
'd3d3d7d7cfcf',
'555557575353',
'efef29292929',
'8a8ae2e23434',
'fcfce9e94f4f',
'72729f9fcfcf',
'adad7f7fa8a8',
'3434e2e2e2e2',
'eeeeeeeeecec',
]
def parse_tango_color(c):
r = int(c[:4][:2], 16)
g = int(c[4:8][:2], 16)
b = int(c[8:][:2], 16)
return [r, g, b, 0xFF]
def apply_color(cfg, color_table):
cfg.default_foreground_color = parse_tango_color('eeeeeeeeecec')
cfg.default_background_color = parse_tango_color('323232323232')
cfg.default_cursor_color = cfg.default_foreground_color
for i in range(len(TANGO_PALLETE)):
if i < len(color_table):
color_table[i] = parse_tango_color(TANGO_PALLETE[i])
| tango_pallete = ['2e2e34343636', 'cccc00000000', '4e4e9a9a0606', 'c4c4a0a00000', '34346565a4a4', '757550507b7b', '060698989a9a', 'd3d3d7d7cfcf', '555557575353', 'efef29292929', '8a8ae2e23434', 'fcfce9e94f4f', '72729f9fcfcf', 'adad7f7fa8a8', '3434e2e2e2e2', 'eeeeeeeeecec']
def parse_tango_color(c):
r = int(c[:4][:2], 16)
g = int(c[4:8][:2], 16)
b = int(c[8:][:2], 16)
return [r, g, b, 255]
def apply_color(cfg, color_table):
cfg.default_foreground_color = parse_tango_color('eeeeeeeeecec')
cfg.default_background_color = parse_tango_color('323232323232')
cfg.default_cursor_color = cfg.default_foreground_color
for i in range(len(TANGO_PALLETE)):
if i < len(color_table):
color_table[i] = parse_tango_color(TANGO_PALLETE[i]) |
def gen():
i = 0
while 1:
yield i
i += 1
g = gen()
try:
g.pend_throw
except AttributeError:
print("SKIP")
raise SystemExit
print(next(g))
print(next(g))
g.pend_throw(ValueError())
v = None
try:
v = next(g)
except Exception as e:
print("raised", repr(e))
print("ret was:", v)
# It's legal to pend exception in a just-started generator, just the same
# as it's legal to .throw() into it.
g = gen()
g.pend_throw(ValueError())
try:
next(g)
except ValueError:
print("ValueError from just-started gen")
| def gen():
i = 0
while 1:
yield i
i += 1
g = gen()
try:
g.pend_throw
except AttributeError:
print('SKIP')
raise SystemExit
print(next(g))
print(next(g))
g.pend_throw(value_error())
v = None
try:
v = next(g)
except Exception as e:
print('raised', repr(e))
print('ret was:', v)
g = gen()
g.pend_throw(value_error())
try:
next(g)
except ValueError:
print('ValueError from just-started gen') |
# Copyright (c) 2021 Food-X Technologies
#
# This file is part of foodx_devops_tools.
#
# You should have received a copy of the MIT License along with
# foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>.
"""Azure related utilities."""
| """Azure related utilities.""" |
_base_ = [
'../../../_base_/datasets/imagenet/swin_sz224_4xbs256.py',
'../../../_base_/default_runtime.py',
]
# model settings
model = dict(
type='MixUpClassification',
pretrained=None,
alpha=0.2,
mix_mode="cutmix",
mix_args=dict(
attentivemix=dict(grid_size=32, top_k=None, beta=8), # AttentiveMix+ in this repo (use pre-trained)
automix=dict(mask_adjust=0, lam_margin=0), # require pre-trained mixblock
fmix=dict(decay_power=3, size=(224,224), max_soft=0., reformulate=False),
manifoldmix=dict(layer=(0, 3)),
puzzlemix=dict(transport=True, t_batch_size=32, t_size=-1, # adjust t_batch_size if CUDA out of memory
mp=None, block_num=4, # block_num<=4 and mp=2/4 for fast training
beta=1.2, gamma=0.5, eta=0.2, neigh_size=4, n_labels=3, t_eps=0.8),
resizemix=dict(scope=(0.1, 0.8), use_alpha=True),
samix=dict(mask_adjust=0, lam_margin=0.08), # require pre-trained mixblock
),
backbone=dict(
type='ConvNeXt',
arch='tiny',
out_indices=(3,),
norm_cfg=dict(type='LN2d', eps=1e-6),
act_cfg=dict(type='GELU'),
drop_path_rate=0.1,
gap_before_final_norm=True,
),
head=dict(
type='ClsMixupHead', # mixup CE + label smooth
loss=dict(type='LabelSmoothLoss',
label_smooth_val=0.1, num_classes=1000, mode='original', loss_weight=1.0),
with_avg_pool=False, # gap_before_final_norm is True
in_channels=768, num_classes=1000)
)
# interval for accumulate gradient
update_interval = 2 # total: 8 x bs256 x 2 accumulates = bs4096
# additional hooks
custom_hooks = [
dict(type='EMAHook', # EMA_W = (1 - m) * EMA_W + m * W
momentum=0.9999,
warmup='linear',
warmup_iters=20 * 626, warmup_ratio=0.9, # warmup 20 epochs.
update_interval=update_interval,
),
]
# optimizer
optimizer = dict(
type='AdamW',
lr=4e-3, # lr = 5e-4 * (256 * 4) * 4 accumulate / 1024 = 4e-3 / bs4096
weight_decay=0.05, eps=1e-8, betas=(0.9, 0.999),
paramwise_options={
'(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.),
'bias': dict(weight_decay=0.),
})
# apex
use_fp16 = True
fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic'))
optimizer_config = dict(grad_clip=None, update_interval=update_interval, use_fp16=use_fp16)
# lr scheduler
lr_config = dict(
policy='CosineAnnealing',
by_epoch=False, min_lr=1e-5,
warmup='linear',
warmup_iters=20, warmup_by_epoch=True, # warmup 20 epochs.
warmup_ratio=1e-6,
)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=300)
| _base_ = ['../../../_base_/datasets/imagenet/swin_sz224_4xbs256.py', '../../../_base_/default_runtime.py']
model = dict(type='MixUpClassification', pretrained=None, alpha=0.2, mix_mode='cutmix', mix_args=dict(attentivemix=dict(grid_size=32, top_k=None, beta=8), automix=dict(mask_adjust=0, lam_margin=0), fmix=dict(decay_power=3, size=(224, 224), max_soft=0.0, reformulate=False), manifoldmix=dict(layer=(0, 3)), puzzlemix=dict(transport=True, t_batch_size=32, t_size=-1, mp=None, block_num=4, beta=1.2, gamma=0.5, eta=0.2, neigh_size=4, n_labels=3, t_eps=0.8), resizemix=dict(scope=(0.1, 0.8), use_alpha=True), samix=dict(mask_adjust=0, lam_margin=0.08)), backbone=dict(type='ConvNeXt', arch='tiny', out_indices=(3,), norm_cfg=dict(type='LN2d', eps=1e-06), act_cfg=dict(type='GELU'), drop_path_rate=0.1, gap_before_final_norm=True), head=dict(type='ClsMixupHead', loss=dict(type='LabelSmoothLoss', label_smooth_val=0.1, num_classes=1000, mode='original', loss_weight=1.0), with_avg_pool=False, in_channels=768, num_classes=1000))
update_interval = 2
custom_hooks = [dict(type='EMAHook', momentum=0.9999, warmup='linear', warmup_iters=20 * 626, warmup_ratio=0.9, update_interval=update_interval)]
optimizer = dict(type='AdamW', lr=0.004, weight_decay=0.05, eps=1e-08, betas=(0.9, 0.999), paramwise_options={'(bn|ln|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0.0), 'bias': dict(weight_decay=0.0)})
use_fp16 = True
fp16 = dict(type='apex', loss_scale=dict(init_scale=512.0, mode='dynamic'))
optimizer_config = dict(grad_clip=None, update_interval=update_interval, use_fp16=use_fp16)
lr_config = dict(policy='CosineAnnealing', by_epoch=False, min_lr=1e-05, warmup='linear', warmup_iters=20, warmup_by_epoch=True, warmup_ratio=1e-06)
runner = dict(type='EpochBasedRunner', max_epochs=300) |
# -*- coding: utf-8 -*-
__about__ = """
This project demonstrates a social networking site. It provides profiles,
friends, photos, blogs, tribes, wikis, tweets, bookmarks, swaps,
locations and user-to-user messaging.
In 0.5 this was called "complete_project".
"""
| __about__ = '\nThis project demonstrates a social networking site. It provides profiles,\nfriends, photos, blogs, tribes, wikis, tweets, bookmarks, swaps,\nlocations and user-to-user messaging.\n\nIn 0.5 this was called "complete_project".\n' |
# Level: Hard
def isMatch(s: str, p: str) -> bool:
if not p:
return not s
n_s = len(s)
n_p = len(p)
j = 0
i = -1
while i < n_s-1:
i = i+ 1
if j >= n_p:
return False
if p[j] == '*':
while s[i]==s[i-1]:
i += 1
j += 1
if p[j] == '.' or s[i] == p[j]:
j += 1
# continue
elif s[i] != p[j] and j<n_p-1:
j += 2
else:
return False
return True
if __name__ == "__main__":
ss = 'abbbbbc'
p = 'a*'
print(isMatch(ss, p)) | def is_match(s: str, p: str) -> bool:
if not p:
return not s
n_s = len(s)
n_p = len(p)
j = 0
i = -1
while i < n_s - 1:
i = i + 1
if j >= n_p:
return False
if p[j] == '*':
while s[i] == s[i - 1]:
i += 1
j += 1
if p[j] == '.' or s[i] == p[j]:
j += 1
elif s[i] != p[j] and j < n_p - 1:
j += 2
else:
return False
return True
if __name__ == '__main__':
ss = 'abbbbbc'
p = 'a*'
print(is_match(ss, p)) |
#######################
# Dennis MUD #
# locate_item.py #
# Copyright 2018-2020 #
# Michael D. Reiley #
#######################
# **********
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# **********
NAME = "locate item"
CATEGORIES = ["items"]
ALIASES = ["find item"]
USAGE = "locate item <item_id>"
DESCRIPTION = """Find out what room the item <item_id> is in, or who is holding it.
You can only locate an item that you own.
Wizards can locate any item.
Ex. `locate item 4`"""
def COMMAND(console, args):
# Perform initial checks.
if not COMMON.check(NAME, console, args, argc=1):
return False
# Perform argument type checks and casts.
itemid = COMMON.check_argtypes(NAME, console, args, checks=[[0, int]], retargs=0)
if itemid is None:
return False
# Check if the item exists.
thisitem = COMMON.check_item(NAME, console, itemid, owner=True, holding=False)
if not thisitem:
return False
# Keep track of whether we found anything in case the item is duplified and we can't return right away.
found_something = False
# Check if we are holding the item.
if itemid in console.user["inventory"]:
console.msg("{0}: {1} ({2}) is in your inventory.".format(NAME, thisitem["name"], thisitem["id"]))
# If the item is duplified we need to keep looking for other copies.
if not thisitem["duplified"]:
return True
found_something = True
# Check if someone else is holding the item.
for targetuser in console.database.users.all():
if targetuser["name"] == console.user["name"]:
continue
if itemid in targetuser["inventory"]:
console.msg("{0}: {1} ({2}) is in the inventory of: {3}.".format(NAME, thisitem["name"], thisitem["id"],
targetuser["name"]))
# If the item is duplified we need to keep looking for other copies.
if not thisitem["duplified"]:
return True
found_something = True
# Check if the item is in a room.
for targetroom in console.database.rooms.all():
if itemid in targetroom["items"]:
console.msg("{0}: {1} ({2}) is in room: {3} ({4})".format(NAME, thisitem["name"], thisitem["id"],
targetroom["name"], targetroom["id"]))
# If the item is duplified we need to keep looking for other copies.
if not thisitem["duplified"]:
return True
found_something = True
# Couldn't find the item.
if not found_something:
console.log.error("Item exists but has no location: {item}", item=itemid)
console.msg("{0}: ERROR: Item exists but has no location. Use `requisition` to fix this.".format(NAME))
return False
# Finished.
return True
| name = 'locate item'
categories = ['items']
aliases = ['find item']
usage = 'locate item <item_id>'
description = 'Find out what room the item <item_id> is in, or who is holding it.\n\nYou can only locate an item that you own.\nWizards can locate any item.\n\nEx. `locate item 4`'
def command(console, args):
if not COMMON.check(NAME, console, args, argc=1):
return False
itemid = COMMON.check_argtypes(NAME, console, args, checks=[[0, int]], retargs=0)
if itemid is None:
return False
thisitem = COMMON.check_item(NAME, console, itemid, owner=True, holding=False)
if not thisitem:
return False
found_something = False
if itemid in console.user['inventory']:
console.msg('{0}: {1} ({2}) is in your inventory.'.format(NAME, thisitem['name'], thisitem['id']))
if not thisitem['duplified']:
return True
found_something = True
for targetuser in console.database.users.all():
if targetuser['name'] == console.user['name']:
continue
if itemid in targetuser['inventory']:
console.msg('{0}: {1} ({2}) is in the inventory of: {3}.'.format(NAME, thisitem['name'], thisitem['id'], targetuser['name']))
if not thisitem['duplified']:
return True
found_something = True
for targetroom in console.database.rooms.all():
if itemid in targetroom['items']:
console.msg('{0}: {1} ({2}) is in room: {3} ({4})'.format(NAME, thisitem['name'], thisitem['id'], targetroom['name'], targetroom['id']))
if not thisitem['duplified']:
return True
found_something = True
if not found_something:
console.log.error('Item exists but has no location: {item}', item=itemid)
console.msg('{0}: ERROR: Item exists but has no location. Use `requisition` to fix this.'.format(NAME))
return False
return True |
class Metric(object):
"""Base class for all metrics.
From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py
"""
def reset(self):
pass
def add(self):
pass
def value(self):
pass
| class Metric(object):
"""Base class for all metrics.
From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py
"""
def reset(self):
pass
def add(self):
pass
def value(self):
pass |
# Take number, and convert integer to string
# Calculate and return number of digits
def get_num_digits(num):
# Convert int to str
num_str = str(num)
# Calculate number of digits
digits = len(num_str)
return digits
# Define main function
def main():
# Prompt user for an integer
number = int(input('Enter an integer: '))
# Obtain number of digits
num_digits = get_num_digits(number)
# Display result
print(f'The number of digits in number {number} is {num_digits}.')
# Call main function
main()
| def get_num_digits(num):
num_str = str(num)
digits = len(num_str)
return digits
def main():
number = int(input('Enter an integer: '))
num_digits = get_num_digits(number)
print(f'The number of digits in number {number} is {num_digits}.')
main() |
#Atoi stands for ASCII to Integer Conversion
def atoi(string):
res = 0
# Iterate through all characters of
# input and update result
for i in range(len(string)):
res = res * 10 + (ord(string[i]) - ord('0'))
return res
#Adjustment contains rule of three for calculating an integer given another integer representing a percentage
def Adjustment(a, b):
return (a * b) / 100
| def atoi(string):
res = 0
for i in range(len(string)):
res = res * 10 + (ord(string[i]) - ord('0'))
return res
def adjustment(a, b):
return a * b / 100 |
def bypass_incompatible_branch(job):
return (job.settings.bypass_incompatible_branch or
job.author_bypass.get('bypass_incompatible_branch', False))
def bypass_peer_approval(job):
return (job.settings.bypass_peer_approval or
job.author_bypass.get('bypass_peer_approval', False))
def bypass_leader_approval(job):
return (job.settings.bypass_leader_approval or
job.author_bypass.get('bypass_leader_approval', False))
def bypass_author_approval(job):
return (job.settings.bypass_author_approval or
job.author_bypass.get('bypass_author_approval', False))
def bypass_build_status(job):
return (job.settings.bypass_build_status or
job.author_bypass.get('bypass_build_status', False))
def bypass_jira_check(job):
return (job.settings.bypass_jira_check or
job.author_bypass.get('bypass_jira_check', False))
| def bypass_incompatible_branch(job):
return job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False)
def bypass_peer_approval(job):
return job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False)
def bypass_leader_approval(job):
return job.settings.bypass_leader_approval or job.author_bypass.get('bypass_leader_approval', False)
def bypass_author_approval(job):
return job.settings.bypass_author_approval or job.author_bypass.get('bypass_author_approval', False)
def bypass_build_status(job):
return job.settings.bypass_build_status or job.author_bypass.get('bypass_build_status', False)
def bypass_jira_check(job):
return job.settings.bypass_jira_check or job.author_bypass.get('bypass_jira_check', False) |
class Heap:
def __init__(self):
self.items = dict() # key - (value, index)
self.indexes = [] # index - key // to know indexes
# Usefull functions
def swap(self, i, j):
x = self.indexes[i] # key of 1 item
y = self.indexes[j] # key of 2 item
# swap keys in index array
self.indexes[i] = y
self.indexes[j] = x
temp = self.items[x][1] # index of 1 item
# swap indexes in dictionary
self.items.update({x: (self.items[x][0], self.items[y][1])})
self.items.update({y: (self.items[y][0], temp)})
def bigger(self, i, j):
if self.indexes[i] <= self.indexes[j]:
return False
else:
return True
# Check family UwU
def hasParent(self, i):
if (i - 1)/2 >= 0:
return True
return False
def parentIndex(self, i):
return int((i - 1)/2)
def hasLeft(self, i):
if i*2 + 1 < len(self.indexes):
return True
return False
def leftIndex(self, i):
return int(i*2 + 1)
def hasRight(self, i):
if i*2 + 2 < len(self.indexes):
return True
return False
def rightIndex(self, i):
return int(i*2 + 2)
# heapifys
def heapifyUp(self, i=None):
if i:
index = i
else:
index = len(self.indexes) - 1
while self.hasParent(index) and self.bigger(self.parentIndex(index), index):
self.swap(self.parentIndex(index), index)
index = self.parentIndex(index)
def heapifyDown(self, i=0):
index = i
while self.hasLeft(index):
smaller = self.leftIndex(index)
if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)):
smaller = self.rightIndex(index)
if self.bigger(smaller, index):
break
else:
self.swap(index, smaller)
index = smaller
# all needed methods
def add(self, key, data):
if self.items.get(key, None):
raise(Exception)
self.items[key] = (data, int(len(self.indexes)))
self.indexes.append(key)
self.heapifyUp()
def set(self, key, data):
temp = self.items.get(key, None)
if not temp:
raise(Exception)
self.items[key] = (data, temp[1])
def delete(self, key):
temp = self.items.get(key, None)
if not temp:
raise(Exception)
if len(self.indexes) > 1:
lastKey = self.indexes[-1]
last = self.items.get(lastKey, None)
# set last item index of deleted
self.items.update({lastKey: (last[0], temp[1])})
# set key of last item to deleted index
self.indexes[temp[1]] = lastKey
self.indexes.pop()
del self.items[key]
if temp[1] < len(self.indexes): # dont heapify if deleted last element
self.heapifyDown(i=temp[1])
self.heapifyUp(i=temp[1])
def search(self, key):
temp = self.items.get(key, None)
if temp:
print('1', temp[1], temp[0])
else:
print('0')
def min(self):
if len(self.indexes) == 0:
raise(Exception)
key = self.indexes[0]
print(key, '0', self.items[key][0])
def max(self):
if len(self.indexes) == 0:
raise(Exception)
i = int(len(self.indexes)/2)
maxKey = self.indexes[i]
index = i
while i < len(self.indexes):
if maxKey < self.indexes[i]:
maxKey = self.indexes[i]
index = i
i += 1
print(maxKey, index, self.items[maxKey][0])
def extract(self):
if len(self.indexes) == 0:
raise(Exception)
rootKey = self.indexes[0]
rootData = self.items[rootKey][0]
del self.items[rootKey]
if len(self.indexes) > 1:
self.indexes[0] = self.indexes.pop()
# set top item index to 0
self.items.update({self.indexes[0] : (self.items[self.indexes[0]][0], 0)})
self.heapifyDown()
else:
self.indexes.pop()
print(rootKey, rootData)
def print(self):
height = 0
index = 0
out = ''
i = 0
if len(self.indexes) == 0:
out += '_\n'
print('_')
return
while i < len(self.indexes):
lineLen = 1 << height
index += 1
key = self.indexes[i]
out += '[' + str(key) + ' ' + self.items[key][0]
if height != 0:
out += ' ' + str(self.indexes[self.parentIndex(i)])
out += ']'
if index == lineLen:
out += '\n'
index = 0
height += 1
else:
out += ' '
i += 1
if index != 0 and index < lineLen:
out += '_ ' * (lineLen - index)
print(out[0:-1])
else:
print(out, end='')
cycle = True
heap = Heap()
while cycle:
try:
line = input()
cmd = line.split(' ', 2)
try:
if len(cmd) == 1 and cmd[0] == '':
continue
if len(cmd) == 2 and cmd[0] == '' and cmd[1] == '':
continue
if cmd[0] == 'add':
heap.add(int(cmd[1]), cmd[2])
elif cmd[0] == 'set':
heap.set(int(cmd[1]), cmd[2])
elif cmd[0] == 'delete':
heap.delete(int(cmd[1]))
elif cmd[0] == 'search':
heap.search(int(cmd[1]))
elif cmd[0] == 'min':
heap.min()
elif cmd[0] == 'max':
heap.max()
elif cmd[0] == 'extract':
heap.extract()
elif cmd[0] == 'print':
heap.print()
else:
raise(Exception)
except Exception:
print('error')
continue
except Exception:
cycle = False
| class Heap:
def __init__(self):
self.items = dict()
self.indexes = []
def swap(self, i, j):
x = self.indexes[i]
y = self.indexes[j]
self.indexes[i] = y
self.indexes[j] = x
temp = self.items[x][1]
self.items.update({x: (self.items[x][0], self.items[y][1])})
self.items.update({y: (self.items[y][0], temp)})
def bigger(self, i, j):
if self.indexes[i] <= self.indexes[j]:
return False
else:
return True
def has_parent(self, i):
if (i - 1) / 2 >= 0:
return True
return False
def parent_index(self, i):
return int((i - 1) / 2)
def has_left(self, i):
if i * 2 + 1 < len(self.indexes):
return True
return False
def left_index(self, i):
return int(i * 2 + 1)
def has_right(self, i):
if i * 2 + 2 < len(self.indexes):
return True
return False
def right_index(self, i):
return int(i * 2 + 2)
def heapify_up(self, i=None):
if i:
index = i
else:
index = len(self.indexes) - 1
while self.hasParent(index) and self.bigger(self.parentIndex(index), index):
self.swap(self.parentIndex(index), index)
index = self.parentIndex(index)
def heapify_down(self, i=0):
index = i
while self.hasLeft(index):
smaller = self.leftIndex(index)
if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)):
smaller = self.rightIndex(index)
if self.bigger(smaller, index):
break
else:
self.swap(index, smaller)
index = smaller
def add(self, key, data):
if self.items.get(key, None):
raise Exception
self.items[key] = (data, int(len(self.indexes)))
self.indexes.append(key)
self.heapifyUp()
def set(self, key, data):
temp = self.items.get(key, None)
if not temp:
raise Exception
self.items[key] = (data, temp[1])
def delete(self, key):
temp = self.items.get(key, None)
if not temp:
raise Exception
if len(self.indexes) > 1:
last_key = self.indexes[-1]
last = self.items.get(lastKey, None)
self.items.update({lastKey: (last[0], temp[1])})
self.indexes[temp[1]] = lastKey
self.indexes.pop()
del self.items[key]
if temp[1] < len(self.indexes):
self.heapifyDown(i=temp[1])
self.heapifyUp(i=temp[1])
def search(self, key):
temp = self.items.get(key, None)
if temp:
print('1', temp[1], temp[0])
else:
print('0')
def min(self):
if len(self.indexes) == 0:
raise Exception
key = self.indexes[0]
print(key, '0', self.items[key][0])
def max(self):
if len(self.indexes) == 0:
raise Exception
i = int(len(self.indexes) / 2)
max_key = self.indexes[i]
index = i
while i < len(self.indexes):
if maxKey < self.indexes[i]:
max_key = self.indexes[i]
index = i
i += 1
print(maxKey, index, self.items[maxKey][0])
def extract(self):
if len(self.indexes) == 0:
raise Exception
root_key = self.indexes[0]
root_data = self.items[rootKey][0]
del self.items[rootKey]
if len(self.indexes) > 1:
self.indexes[0] = self.indexes.pop()
self.items.update({self.indexes[0]: (self.items[self.indexes[0]][0], 0)})
self.heapifyDown()
else:
self.indexes.pop()
print(rootKey, rootData)
def print(self):
height = 0
index = 0
out = ''
i = 0
if len(self.indexes) == 0:
out += '_\n'
print('_')
return
while i < len(self.indexes):
line_len = 1 << height
index += 1
key = self.indexes[i]
out += '[' + str(key) + ' ' + self.items[key][0]
if height != 0:
out += ' ' + str(self.indexes[self.parentIndex(i)])
out += ']'
if index == lineLen:
out += '\n'
index = 0
height += 1
else:
out += ' '
i += 1
if index != 0 and index < lineLen:
out += '_ ' * (lineLen - index)
print(out[0:-1])
else:
print(out, end='')
cycle = True
heap = heap()
while cycle:
try:
line = input()
cmd = line.split(' ', 2)
try:
if len(cmd) == 1 and cmd[0] == '':
continue
if len(cmd) == 2 and cmd[0] == '' and (cmd[1] == ''):
continue
if cmd[0] == 'add':
heap.add(int(cmd[1]), cmd[2])
elif cmd[0] == 'set':
heap.set(int(cmd[1]), cmd[2])
elif cmd[0] == 'delete':
heap.delete(int(cmd[1]))
elif cmd[0] == 'search':
heap.search(int(cmd[1]))
elif cmd[0] == 'min':
heap.min()
elif cmd[0] == 'max':
heap.max()
elif cmd[0] == 'extract':
heap.extract()
elif cmd[0] == 'print':
heap.print()
else:
raise Exception
except Exception:
print('error')
continue
except Exception:
cycle = False |
class Solution(object):
def rearrangeString(self, str, k):
"""
:type str: str
:type k: int
:rtype: str
"""
## greedy: count keeps the # of chars, valid keeps the leftmost valid index of a char.
res=[]
# count # of chars
d=collections.defaultdict(int)
for c in str:
d[c]+=1
# create a valid dict
v=collections.defaultdict(int)
# add char one by one, that with max # first, must have valid leftmost index
for i in range(len(str)):
c=None
for key in d:
if (not c or d[key]>d[c]) and d[key]>0 and v[key]<=i: # get c with max # and be valid
c=key
if not c: return ''
res.append(c)
d[c]-=1
v[c]=i+k
return ''.join(res) | class Solution(object):
def rearrange_string(self, str, k):
"""
:type str: str
:type k: int
:rtype: str
"""
res = []
d = collections.defaultdict(int)
for c in str:
d[c] += 1
v = collections.defaultdict(int)
for i in range(len(str)):
c = None
for key in d:
if (not c or d[key] > d[c]) and d[key] > 0 and (v[key] <= i):
c = key
if not c:
return ''
res.append(c)
d[c] -= 1
v[c] = i + k
return ''.join(res) |
'''
All the reserved, individual words used in MAlice.
'''
A = "a"
ALICE = "Alice"
AND = "and"
ATE = "ate"
BECAME = "became"
BECAUSE = "because"
BUT = "but"
CLOSED = "closed"
COMMA = ","
CONTAINED = "contained"
DOT = "."
DRANK = "drank"
EITHER = "either"
ENOUGH = "enough"
EVENTUALLY = "eventually"
FOUND = "found"
HAD = "had"
HATTA = "hatta"
LETTER = "letter"
LOOKING_GLASS = "looking-glass"
LPAR = "("
MAYBE = "maybe"
NUMBER = "number"
OF = "of"
OPENED = "opened"
OR = "or"
PERHAPS = "perhaps"
PIECE = "piece"
QUESTION = "?"
ROOM = "room"
RPAR = ")"
S = "'s"
SAID = "said"
SENTENCE = "sentence"
SO = "so"
SPIDER = "spider"
SPOKE = "spoke"
THE = "The"
THEN = "then"
TIMES = "times"
TOO = "too"
UNDERSCORE = "_"
UNSURE = "unsure"
WAS = "was"
WHAT = "what"
WHICH = "which"
RESTRICTED = [ A, ALICE, AND, ATE, BECAME ,BECAUSE ,BUT ,CLOSED ,COMMA ,CONTAINED ,DOT ,DRANK ,EITHER ,ENOUGH ,EVENTUALLY ,FOUND ,HAD ,HATTA ,LETTER ,LOOKING_GLASS ,LPAR ,MAYBE ,NUMBER ,OF ,OPENED ,OR ,PERHAPS ,PIECE ,QUESTION ,ROOM ,RPAR ,S ,SAID, SENTENCE ,SO ,SPIDER ,SPOKE ,THE ,THEN ,TIMES ,TOO ,UNDERSCORE ,UNSURE ,WAS ,WHAT ,WHICH]
| """
All the reserved, individual words used in MAlice.
"""
a = 'a'
alice = 'Alice'
and = 'and'
ate = 'ate'
became = 'became'
because = 'because'
but = 'but'
closed = 'closed'
comma = ','
contained = 'contained'
dot = '.'
drank = 'drank'
either = 'either'
enough = 'enough'
eventually = 'eventually'
found = 'found'
had = 'had'
hatta = 'hatta'
letter = 'letter'
looking_glass = 'looking-glass'
lpar = '('
maybe = 'maybe'
number = 'number'
of = 'of'
opened = 'opened'
or = 'or'
perhaps = 'perhaps'
piece = 'piece'
question = '?'
room = 'room'
rpar = ')'
s = "'s"
said = 'said'
sentence = 'sentence'
so = 'so'
spider = 'spider'
spoke = 'spoke'
the = 'The'
then = 'then'
times = 'times'
too = 'too'
underscore = '_'
unsure = 'unsure'
was = 'was'
what = 'what'
which = 'which'
restricted = [A, ALICE, AND, ATE, BECAME, BECAUSE, BUT, CLOSED, COMMA, CONTAINED, DOT, DRANK, EITHER, ENOUGH, EVENTUALLY, FOUND, HAD, HATTA, LETTER, LOOKING_GLASS, LPAR, MAYBE, NUMBER, OF, OPENED, OR, PERHAPS, PIECE, QUESTION, ROOM, RPAR, S, SAID, SENTENCE, SO, SPIDER, SPOKE, THE, THEN, TIMES, TOO, UNDERSCORE, UNSURE, WAS, WHAT, WHICH] |
def migrate():
print('migrating to version 2')
| def migrate():
print('migrating to version 2') |
test = { 'name': 'q2b3',
'points': 5,
'suites': [ { 'cases': [ { 'code': '>>> '
'histories_2b[2].model.count_params()\n'
'119260',
'hidden': False,
'locked': False},
{ 'code': '>>> '
'histories_2b[2].model.layers[1].activation.__name__\n'
"'sigmoid'",
'hidden': False,
'locked': False},
{ 'code': '>>> '
'histories_2b[2].model.layers[1].units\n'
'150',
'hidden': False,
'locked': False},
{ 'code': '>>> '
"histories_2b[2].history['loss'][4] "
'<= '
"histories_2b[1].history['loss'][4]\n"
'True',
'hidden': False,
'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
| test = {'name': 'q2b3', 'points': 5, 'suites': [{'cases': [{'code': '>>> histories_2b[2].model.count_params()\n119260', 'hidden': False, 'locked': False}, {'code': ">>> histories_2b[2].model.layers[1].activation.__name__\n'sigmoid'", 'hidden': False, 'locked': False}, {'code': '>>> histories_2b[2].model.layers[1].units\n150', 'hidden': False, 'locked': False}, {'code': ">>> histories_2b[2].history['loss'][4] <= histories_2b[1].history['loss'][4]\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
# Time: O(n*2^n)
# Space: O(2^n)
class Solution(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, used, todo, lookup):
if lookup[used] is None:
targ = (todo-1)%target + 1
lookup[used] = any(dfs(nums, target, used | (1<<i), todo-num, lookup) \
for i, num in enumerate(nums) \
if ((used>>i) & 1) == 0 and num <= targ)
return lookup[used]
total = sum(nums)
if total%k or max(nums) > total//k:
return False
lookup = [None] * (1 << len(nums))
lookup[-1] = True
return dfs(nums, total//k, 0, total, lookup)
# Time: O(k^(n-k) * k!)
# Space: O(n)
# DFS solution with pruning.
class Solution2(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, i, subset_sums):
if i == len(nums):
return True
for k in range(len(subset_sums)):
if subset_sums[k]+nums[i] > target:
continue
subset_sums[k] += nums[i]
if dfs(nums, target, i+1, subset_sums):
return True
subset_sums[k] -= nums[i]
if not subset_sums[k]: break
return False
total = sum(nums)
if total%k != 0 or max(nums) > total//k:
return False
nums.sort(reverse=True)
subset_sums = [0] * k
return dfs(nums, total//k, 0, subset_sums)
| class Solution(object):
def can_partition_k_subsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, used, todo, lookup):
if lookup[used] is None:
targ = (todo - 1) % target + 1
lookup[used] = any((dfs(nums, target, used | 1 << i, todo - num, lookup) for (i, num) in enumerate(nums) if used >> i & 1 == 0 and num <= targ))
return lookup[used]
total = sum(nums)
if total % k or max(nums) > total // k:
return False
lookup = [None] * (1 << len(nums))
lookup[-1] = True
return dfs(nums, total // k, 0, total, lookup)
class Solution2(object):
def can_partition_k_subsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, i, subset_sums):
if i == len(nums):
return True
for k in range(len(subset_sums)):
if subset_sums[k] + nums[i] > target:
continue
subset_sums[k] += nums[i]
if dfs(nums, target, i + 1, subset_sums):
return True
subset_sums[k] -= nums[i]
if not subset_sums[k]:
break
return False
total = sum(nums)
if total % k != 0 or max(nums) > total // k:
return False
nums.sort(reverse=True)
subset_sums = [0] * k
return dfs(nums, total // k, 0, subset_sums) |
#!/usr/bin/env python
# License: Apache-2.0
# Copyright (C) 2020 Mikhail f. Shiryaev
class Column(object):
"""
Represents ClickHouse column
"""
def __init__(
self,
database: str,
table: str,
name: str,
type: str,
default_kind: str,
default_expression: str,
comment: str,
compression_codec: str,
is_in_partition_key: bool,
is_in_sorting_key: bool,
is_in_primary_key: bool,
is_in_sampling_key: bool,
):
self.database = database
self.table = table
self.name = name
self.type = type
self.default_kind = default_kind
self.default_expression = default_expression
self.comment = comment
self.compression_codec = compression_codec
self.is_in_partition_key = is_in_partition_key
self.is_in_sorting_key = is_in_sorting_key
self.is_in_primary_key = is_in_primary_key
self.is_in_sampling_key = is_in_sampling_key
@property
def db_table(self):
return "{}.{}".format(self.database, self.table)
def __str__(self):
return self.name
| class Column(object):
"""
Represents ClickHouse column
"""
def __init__(self, database: str, table: str, name: str, type: str, default_kind: str, default_expression: str, comment: str, compression_codec: str, is_in_partition_key: bool, is_in_sorting_key: bool, is_in_primary_key: bool, is_in_sampling_key: bool):
self.database = database
self.table = table
self.name = name
self.type = type
self.default_kind = default_kind
self.default_expression = default_expression
self.comment = comment
self.compression_codec = compression_codec
self.is_in_partition_key = is_in_partition_key
self.is_in_sorting_key = is_in_sorting_key
self.is_in_primary_key = is_in_primary_key
self.is_in_sampling_key = is_in_sampling_key
@property
def db_table(self):
return '{}.{}'.format(self.database, self.table)
def __str__(self):
return self.name |
def solve(n, red , blue):
rcount = bcount = 0
for i in range(n):
if int(red[i]) > int(blue[i]):
rcount = rcount +1
elif int(red[i]) < int(blue[i]):
bcount = bcount + 1
print( 'RED' if rcount>bcount else ('BLUE' if bcount>rcount else 'EQUAL'))
if __name__ == "__main__":
T = int(input())
for t in range(T):
n = int(input())
red = input()
blue = input()
solve(n, red, blue) | def solve(n, red, blue):
rcount = bcount = 0
for i in range(n):
if int(red[i]) > int(blue[i]):
rcount = rcount + 1
elif int(red[i]) < int(blue[i]):
bcount = bcount + 1
print('RED' if rcount > bcount else 'BLUE' if bcount > rcount else 'EQUAL')
if __name__ == '__main__':
t = int(input())
for t in range(T):
n = int(input())
red = input()
blue = input()
solve(n, red, blue) |
class a:
def __init__(self,da):
self.da = da
return
def go(self):
dd()
return None
def dd():
print('ok')
return None
aa = a(1)
aa.go() | class A:
def __init__(self, da):
self.da = da
return
def go(self):
dd()
return None
def dd():
print('ok')
return None
aa = a(1)
aa.go() |
"""
These methods can be called inside WebCAT to determine which tests are loaded
for a given section/exam pair. This allows a common WebCAT submission site to
support different project tests
"""
def section():
# Instructor section (instructor to change before distribution)
#return 8527
#return 8528
return 8529
def exam():
# A or B exam (instructor to change to match specific project distribution
return "A"
#return "B"
| """
These methods can be called inside WebCAT to determine which tests are loaded
for a given section/exam pair. This allows a common WebCAT submission site to
support different project tests
"""
def section():
return 8529
def exam():
return 'A' |
"""
PermCheck
Check whether array A is a permutation.
https://codility.com/demo/results/demoANZ7M2-GFU/
Task description
A non-empty zero-indexed array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
is a permutation, but array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
"""
def solution(A):
# write your code in Python 2.7
s = set(A)
N_set = len(s) #O(n)
N = len(A)
if N != N_set: return 0
sum_N = N*(N+1)/2 #O(1)
sum_A = sum(A) #O(n)
return 1 if sum_N == sum_A else 0 | """
PermCheck
Check whether array A is a permutation.
https://codility.com/demo/results/demoANZ7M2-GFU/
Task description
A non-empty zero-indexed array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
is a permutation, but array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
"""
def solution(A):
s = set(A)
n_set = len(s)
n = len(A)
if N != N_set:
return 0
sum_n = N * (N + 1) / 2
sum_a = sum(A)
return 1 if sum_N == sum_A else 0 |
'''
Created on Dec 27, 2019
@author: duane
'''
DOLLAR = ord('$')
LBRACE = ord('{')
RBRACE = ord('}')
LPAREN = ord('(')
RPAREN = ord(')')
class IStrFindResult(object):
OK = 0
NOTFOUND = 1
SYNTAX = 2
def __init__(self):
self.result = IStrFindResult.SYNTAX
self.lhs = 0
self.rhs = 0
self.name = None
class IStr(list):
'''
This closely models a basic ASCII string
Note: Unicode strings are expressly not supported here.
The problem this addresses occurs during macro processing.
Sometimes macros are defined externally
Other times, macros are fully defined with a package.
Often macros need to be resolved either partially or fully
When a macro is only external - they get in the way of resolving other macros
To work around that, we convert the string into an array of integers
Then for every macro byte that is 'external' we add 0x100
This makes the byte 'non-matchable'
Later, when we convert the resolved string into we strip the 0x100.
'''
IGNORE = 0x100
def __init__(self, s):
'''
Constructor
'''
# convert to integers
list.__init__(self, map(ord, s))
def __str__(self):
# return as string, stripping flags
return ''.join(map(lambda v: chr(v & 0xff), self))
def sslice(self, lhs, rhs):
# return as string, stripping flags
return ''.join(map(lambda v: chr(v & 0xff), self[lhs:rhs]))
def iarray(self):
return self[:]
def mark(self, lhs, rhs, flagvalue=IGNORE):
'''
Apply flags to locations between left and right hand sides, ie: [lhs:rhs]
'''
for idx in range(lhs, rhs):
self[idx] |= flagvalue
def locate(self, needle, lhs, rhs):
'''Find this needle(char) in the hay stack(list).'''
try:
return self.index(needle, lhs, rhs)
except:
# not found
return -1
def replace(self, lhs, rhs, newcontent):
'''replace the data between [lhs:rhs] with newcontent'''
self[lhs: rhs] = map(ord, newcontent)
def next_macro(self, lhs, rhs):
'''
Find a macro within the string, return (lhs,rhs) if found
If not found, return (-1,-1)
If syntax error, return (-2,-2)
'''
result = IStrFindResult()
result.lhs = lhs
result.rhs = rhs
# if it is not long enough...
if (rhs - lhs) < 4:
result.code = result.NOTFOUND
return result
# We search for the CLOSING
# Consider nested: ${ ${foo}_${bar} }
# The first thing we must do is "foo"
# So find the close
tmp = self.locate(RBRACE, result.lhs,result.rhs)
if tmp >= 0:
_open_symbol = LBRACE
else:
tmp = self.locate(RPAREN,result.lhs,result.rhs)
_open_symbol = RPAREN
if tmp < 0:
# not found
result.code = result.NOTFOUND
return result
# We want to end at RHS where the closing symbol is
result.rhs = tmp
while result.lhs < result.rhs:
# find DOLLAR
dollar_loc = self.locate(DOLLAR, result.lhs, result.rhs)
if dollar_loc < 0:
# above, we know we have a CLOSE
# We could call this a SYNTAX error
# but ... we won't we'll leave this as NOT FOUND
result.code = result.NOTFOUND
return result
# we have: DOLLAR + CLOSE
# Can we find DOLLAR + OPEN?
ch = self[dollar_loc+1]
if ch != _open_symbol:
# Nope... try again after dollar
result.lhs = dollar_loc+1
continue
result.lhs = dollar_loc
# Do we have a nested macro, ie: ${${x}}
tmp = self.locate(DOLLAR, dollar_loc + 1, result.rhs)
if tmp >= 0:
# we do have a nested macro
result.lhs = tmp
continue
# nope, we are good
# Everything between LHS and RHS should be a macro
result.code = result.OK
result.name = self.sslice(result.lhs + 2, result.rhs)
# the RHS should include the closing symbol
result.rhs += 1
return result
# not found syntax stray dollar or brace
result.code = result.SYNTAX
return result
def test_istr():
def check2(l, r, text, dut):
print("----")
print("Check (%d,%d)" % (l, r))
print("s = %s" % str(dut))
print("i = %s" % dut.iarray())
result = dut.next_macro(0, len(dut))
if (result.lhs != l) or (result.rhs != r):
print("str = %s" % str(dut))
print("int = %s" % dut.iarray())
print("Error: (%d,%d) != (%d,%d)" % (l, r, result.lhs, result.rhs))
assert (False)
if text is not None:
assert( result.name == text )
dut.mark(l, r)
return dut
def check(l, r, s):
if l >= 0:
expected = s[l + 2:r - 1]
else:
expected = None
dut = IStr(s)
check2(l, r, expected, dut)
st = str(dut)
assert (st == s)
return dut
check(-1, -1, "")
check(-1, -1, "a")
check(-1, -1, "ab")
check(-1, -1, "abc")
check(-1, -1, "abcd")
check(-1, -1, "abcde")
check(-1, -1, "abcdef")
check(0, 4, "${a}")
check(0, 5, "${ab}")
check(0, 6, "${abc}")
check(0, 7, "${abcd}")
check(1, 5, "a${a}")
check(2, 6, "ab${a}")
check(3, 7, "abc${a}")
check(4, 8, "abcd${a}")
check(5, 9, "abcde${a}")
check(0, 4, "${a}a")
check(0, 4, "${a}ab")
check(0, 4, "${a}abc")
check(0, 4, "${a}abcd")
check(0, 4, "${a}abcde")
dut = check(4, 8, "abcd${a}xyz")
dut.replace(4, 8, "X")
check2(-1, -1, None, dut)
r = str(dut)
print("Got: %s" % r)
assert ("abcdXxyz" == str(dut))
# now nested tests
dut = check(5, 9, "abc${${Y}}xyz")
dut.replace(5, 9, "X")
r = str(dut)
assert (r == "abc${X}xyz")
dut = check2(3, 7, "${X}", dut)
dut.replace(3, 7, "ABC")
s = str(dut)
r = "abcABCxyz"
assert (s == r)
print("Success")
if __name__ == '__main__':
test_istr()
| """
Created on Dec 27, 2019
@author: duane
"""
dollar = ord('$')
lbrace = ord('{')
rbrace = ord('}')
lparen = ord('(')
rparen = ord(')')
class Istrfindresult(object):
ok = 0
notfound = 1
syntax = 2
def __init__(self):
self.result = IStrFindResult.SYNTAX
self.lhs = 0
self.rhs = 0
self.name = None
class Istr(list):
"""
This closely models a basic ASCII string
Note: Unicode strings are expressly not supported here.
The problem this addresses occurs during macro processing.
Sometimes macros are defined externally
Other times, macros are fully defined with a package.
Often macros need to be resolved either partially or fully
When a macro is only external - they get in the way of resolving other macros
To work around that, we convert the string into an array of integers
Then for every macro byte that is 'external' we add 0x100
This makes the byte 'non-matchable'
Later, when we convert the resolved string into we strip the 0x100.
"""
ignore = 256
def __init__(self, s):
"""
Constructor
"""
list.__init__(self, map(ord, s))
def __str__(self):
return ''.join(map(lambda v: chr(v & 255), self))
def sslice(self, lhs, rhs):
return ''.join(map(lambda v: chr(v & 255), self[lhs:rhs]))
def iarray(self):
return self[:]
def mark(self, lhs, rhs, flagvalue=IGNORE):
"""
Apply flags to locations between left and right hand sides, ie: [lhs:rhs]
"""
for idx in range(lhs, rhs):
self[idx] |= flagvalue
def locate(self, needle, lhs, rhs):
"""Find this needle(char) in the hay stack(list)."""
try:
return self.index(needle, lhs, rhs)
except:
return -1
def replace(self, lhs, rhs, newcontent):
"""replace the data between [lhs:rhs] with newcontent"""
self[lhs:rhs] = map(ord, newcontent)
def next_macro(self, lhs, rhs):
"""
Find a macro within the string, return (lhs,rhs) if found
If not found, return (-1,-1)
If syntax error, return (-2,-2)
"""
result = i_str_find_result()
result.lhs = lhs
result.rhs = rhs
if rhs - lhs < 4:
result.code = result.NOTFOUND
return result
tmp = self.locate(RBRACE, result.lhs, result.rhs)
if tmp >= 0:
_open_symbol = LBRACE
else:
tmp = self.locate(RPAREN, result.lhs, result.rhs)
_open_symbol = RPAREN
if tmp < 0:
result.code = result.NOTFOUND
return result
result.rhs = tmp
while result.lhs < result.rhs:
dollar_loc = self.locate(DOLLAR, result.lhs, result.rhs)
if dollar_loc < 0:
result.code = result.NOTFOUND
return result
ch = self[dollar_loc + 1]
if ch != _open_symbol:
result.lhs = dollar_loc + 1
continue
result.lhs = dollar_loc
tmp = self.locate(DOLLAR, dollar_loc + 1, result.rhs)
if tmp >= 0:
result.lhs = tmp
continue
result.code = result.OK
result.name = self.sslice(result.lhs + 2, result.rhs)
result.rhs += 1
return result
result.code = result.SYNTAX
return result
def test_istr():
def check2(l, r, text, dut):
print('----')
print('Check (%d,%d)' % (l, r))
print('s = %s' % str(dut))
print('i = %s' % dut.iarray())
result = dut.next_macro(0, len(dut))
if result.lhs != l or result.rhs != r:
print('str = %s' % str(dut))
print('int = %s' % dut.iarray())
print('Error: (%d,%d) != (%d,%d)' % (l, r, result.lhs, result.rhs))
assert False
if text is not None:
assert result.name == text
dut.mark(l, r)
return dut
def check(l, r, s):
if l >= 0:
expected = s[l + 2:r - 1]
else:
expected = None
dut = i_str(s)
check2(l, r, expected, dut)
st = str(dut)
assert st == s
return dut
check(-1, -1, '')
check(-1, -1, 'a')
check(-1, -1, 'ab')
check(-1, -1, 'abc')
check(-1, -1, 'abcd')
check(-1, -1, 'abcde')
check(-1, -1, 'abcdef')
check(0, 4, '${a}')
check(0, 5, '${ab}')
check(0, 6, '${abc}')
check(0, 7, '${abcd}')
check(1, 5, 'a${a}')
check(2, 6, 'ab${a}')
check(3, 7, 'abc${a}')
check(4, 8, 'abcd${a}')
check(5, 9, 'abcde${a}')
check(0, 4, '${a}a')
check(0, 4, '${a}ab')
check(0, 4, '${a}abc')
check(0, 4, '${a}abcd')
check(0, 4, '${a}abcde')
dut = check(4, 8, 'abcd${a}xyz')
dut.replace(4, 8, 'X')
check2(-1, -1, None, dut)
r = str(dut)
print('Got: %s' % r)
assert 'abcdXxyz' == str(dut)
dut = check(5, 9, 'abc${${Y}}xyz')
dut.replace(5, 9, 'X')
r = str(dut)
assert r == 'abc${X}xyz'
dut = check2(3, 7, '${X}', dut)
dut.replace(3, 7, 'ABC')
s = str(dut)
r = 'abcABCxyz'
assert s == r
print('Success')
if __name__ == '__main__':
test_istr() |
P, R = input().split()
if P == '0': print('C')
elif R == '0': print('B')
else: print('A') | (p, r) = input().split()
if P == '0':
print('C')
elif R == '0':
print('B')
else:
print('A') |
md_template_d144 = """verbosity=0
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=160
ny=80
nz=80
[Domain]
ox=0.
oy=0.
oz=0.
lx=42.4813
ly=21.2406
lz=21.2406
[Potentials]
pseudopotential=pseudo.D_tm_pbe
[Poisson]
solver=@
max_steps_initial=@50
max_steps=@50
reset=@
bcx=periodic
bcy=periodic
bcz=periodic
[Run]
type=MD
[MD]
type=@
num_steps=@
dt=@15.
[XLBOMD]
dissipation=@5
align=@
[Quench]
max_steps=@5
max_steps_tight=@
atol=1.e-@10
num_lin_iterations=3
ortho_freq=100
[SpreadPenalty]
type=@energy
damping=@
target=@1.75
alpha=@0.01
[Orbitals]
initial_type=Gaussian
initial_width=1.5
overallocate_factor=@2.
[ProjectedMatrices]
solver=@short_sighted
[LocalizationRegions]
radius=@8.
auxiliary_radius=@
move_tol=@0.1
[Restart]
input_filename=wave.out
input_level=3
interval=@
"""
md_template_H2O_64 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=128
ny=128
nz=128
[Domain]
ox=0.
oy=0.
oz=0.
lx=23.4884
ly=23.4884
lz=23.4884
[Potentials]
pseudopotential=pseudo.O_ONCV_PBE_SG15
pseudopotential=pseudo.D_ONCV_PBE_SG15
[Poisson]
solver=@
max_steps=@
[Run]
type=MD
[Quench]
max_steps=1000
atol=1.e-@
[MD]
type=@
num_steps=@
dt=10.
print_interval=5
[XLBOMD]
dissipation=@
align=@
[Restart]
input_filename=wave.out
input_level=4
output_level=4
interval=@
"""
quench_template_H2O_64 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=128
ny=128
nz=128
[Domain]
ox=0.
oy=0.
oz=0.
lx=23.4884
ly=23.4884
lz=23.4884
[Potentials]
pseudopotential=pseudo.O_ONCV_PBE_SG15
pseudopotential=pseudo.D_ONCV_PBE_SG15
[Run]
type=QUENCH
[Quench]
max_steps=1000
atol=1.e-8
[Orbitals]
initial_type=Fourier
[Restart]
output_level=4
"""
quench_template_d144 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=160
ny=80
nz=80
[Domain]
ox=0.
oy=0.
oz=0.
lx=42.4813
ly=21.2406
lz=21.2406
[Potentials]
pseudopotential=pseudo.D_tm_pbe
[Poisson]
solver=@
max_steps_initial=@50
max_steps=@50
bcx=periodic
bcy=periodic
bcz=periodic
[Run]
type=QUENCH
[Quench]
max_steps=200
atol=1.e-7
num_lin_iterations=3
ortho_freq=100
[SpreadPenalty]
type=@energy
damping=@
target=@1.75
alpha=@0.01
[Orbitals]
initial_type=Gaussian
initial_width=1.5
[ProjectedMatrices]
solver=@short_sighted
[LocalizationRegions]
radius=@8.
[Restart]
output_type=distributed
"""
H2O_64_params={
'nodes': '32',
'ntasks': '256',
'omp_num_threads': 8 if omp_num_threads == 4 else omp_num_threads,
'cores_per_task': '2',
'potentials': 'ln -s $maindir/potentials/pseudo.O_ONCV_PBE_SG15\nln -s $maindir/potentials/pseudo.D_ONCV_PBE_SG15',
'lrs': '',
'jobname': 'H2O_64',
}
d144_params={
'nodes': '8',
'walltime': '01:30:00',
'ntasks': '125',
'omp_num_threads': omp_num_threads,
'cores_per_task': '1',
'potentials': 'ln -s $maindir/potentials/pseudo.D_tm_pbe',
'lrs': '-l lrs.in',
'jobname': 'd144',
}
vulcan_params={
'queue': 'psmall',
'scratch_path': '/p/lscratchv/mgmolu/dunn27/mgmol/',
'gres': 'lscratchv',
'exe': 'mgmol-bgq',
}
cab_params={
'queue': 'pbatch',
'scratch_path': '/p/lscratchd/dunn27/mgmol/',
'gres': 'lscratchd',
'omp_num_threads': '1',
'exe': 'mgmol-pel',
'walltime': '01:30:00',
}
runfile_quench_template="""#!/bin/tcsh
#MSUB -l nodes={nodes},walltime={walltime}
#MSUB -o mgmol.out
#MSUB -q {queue}
#MSUB -A comp
#MSUB -l gres={gres}
#MSUB -N {jobname}
rm -f queued
echo ' ' > running
use boost-nompi-1.55.0
export BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0
export Boost_NO_SYSTEM_PATHS=ON
setenv OMP_NUM_THREADS {omp_num_threads}
set ntasks = {ntasks}
set maindir = $home/mgmol
set exe = $maindir/bin/{exe}
set datadir = `pwd`
set scratchdir = {scratch_path}`basename $datadir`
mkdir $scratchdir
cd $scratchdir
echo ' ' > running
set cfg_quench = mgmol_quench.cfg
cp $datadir/$cfg_quench .
cp $datadir/coords.in .
cp $datadir/lrs.in .
{potentials}
#1st run
srun -n $ntasks -c {cores_per_task} $exe -c $cfg_quench -i coords.in {lrs}
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
rm -f running
echo ' ' > queued
"""
runfile_md_template="""#!/bin/tcsh
#MSUB -l nodes={nodes},walltime={walltime}
#MSUB -o mgmol.out
#MSUB -q {queue}
#MSUB -A comp
#MSUB -l gres={gres}
#MSUB -N {jobname}
rm -f queued
echo ' ' > running
use boost-nompi-1.55.0
export BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0
export Boost_NO_SYSTEM_PATHS=ON
setenv OMP_NUM_THREADS {omp_num_threads}
set ntasks = {ntasks}
set maindir = $home/mgmol
set exe = $maindir/bin/{exe}
set datadir = `pwd`
set scratchdir = {scratch_path}`basename $datadir`
mkdir $scratchdir
cd $scratchdir
echo ' ' > running
set cfg_md = mgmol_md.cfg
cp $datadir/$cfg_md .
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
#MD run
srun -n $ntasks -c {cores_per_task} $exe -c $cfg_md
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
rm -f running
echo ' ' > queued
"""
| md_template_d144 = 'verbosity=0\nxcFunctional=PBE\nFDtype=4th\n[Mesh]\nnx=160\nny=80\nnz=80\n[Domain]\nox=0.\noy=0.\noz=0.\nlx=42.4813\nly=21.2406\nlz=21.2406\n[Potentials]\npseudopotential=pseudo.D_tm_pbe\n[Poisson]\nsolver=@\nmax_steps_initial=@50\nmax_steps=@50\nreset=@\nbcx=periodic\nbcy=periodic\nbcz=periodic\n[Run]\ntype=MD\n[MD]\ntype=@\nnum_steps=@\ndt=@15.\n[XLBOMD]\ndissipation=@5\nalign=@\n[Quench]\nmax_steps=@5\nmax_steps_tight=@\natol=1.e-@10\nnum_lin_iterations=3\northo_freq=100\n[SpreadPenalty]\ntype=@energy\ndamping=@\ntarget=@1.75\nalpha=@0.01\n[Orbitals]\ninitial_type=Gaussian\ninitial_width=1.5\noverallocate_factor=@2.\n[ProjectedMatrices]\nsolver=@short_sighted\n[LocalizationRegions]\nradius=@8.\nauxiliary_radius=@\nmove_tol=@0.1\n[Restart]\ninput_filename=wave.out\ninput_level=3\ninterval=@\n'
md_template_h2_o_64 = 'verbosity=1\nxcFunctional=PBE\nFDtype=4th\n[Mesh]\nnx=128\nny=128\nnz=128\n[Domain]\nox=0.\noy=0.\noz=0.\nlx=23.4884\nly=23.4884\nlz=23.4884\n[Potentials]\npseudopotential=pseudo.O_ONCV_PBE_SG15\npseudopotential=pseudo.D_ONCV_PBE_SG15\n[Poisson]\nsolver=@\nmax_steps=@\n[Run]\ntype=MD\n[Quench]\nmax_steps=1000\natol=1.e-@\n[MD]\ntype=@\nnum_steps=@\ndt=10.\nprint_interval=5\n[XLBOMD]\ndissipation=@\nalign=@\n[Restart]\ninput_filename=wave.out\ninput_level=4\noutput_level=4\ninterval=@\n'
quench_template_h2_o_64 = 'verbosity=1\nxcFunctional=PBE\nFDtype=4th\n[Mesh]\nnx=128\nny=128\nnz=128\n[Domain]\nox=0.\noy=0.\noz=0.\nlx=23.4884\nly=23.4884\nlz=23.4884\n[Potentials]\npseudopotential=pseudo.O_ONCV_PBE_SG15\npseudopotential=pseudo.D_ONCV_PBE_SG15\n[Run]\ntype=QUENCH\n[Quench]\nmax_steps=1000\natol=1.e-8\n[Orbitals]\ninitial_type=Fourier\n[Restart]\noutput_level=4\n'
quench_template_d144 = 'verbosity=1\nxcFunctional=PBE\nFDtype=4th\n[Mesh]\nnx=160\nny=80\nnz=80\n[Domain]\nox=0.\noy=0.\noz=0.\nlx=42.4813\nly=21.2406\nlz=21.2406\n[Potentials]\npseudopotential=pseudo.D_tm_pbe\n[Poisson]\nsolver=@\nmax_steps_initial=@50\nmax_steps=@50\nbcx=periodic\nbcy=periodic\nbcz=periodic\n[Run]\ntype=QUENCH\n[Quench]\nmax_steps=200\natol=1.e-7\nnum_lin_iterations=3\northo_freq=100\n[SpreadPenalty]\ntype=@energy\ndamping=@\ntarget=@1.75\nalpha=@0.01\n[Orbitals]\ninitial_type=Gaussian\ninitial_width=1.5\n[ProjectedMatrices]\nsolver=@short_sighted\n[LocalizationRegions]\nradius=@8.\n[Restart]\noutput_type=distributed\n'
h2_o_64_params = {'nodes': '32', 'ntasks': '256', 'omp_num_threads': 8 if omp_num_threads == 4 else omp_num_threads, 'cores_per_task': '2', 'potentials': 'ln -s $maindir/potentials/pseudo.O_ONCV_PBE_SG15\nln -s $maindir/potentials/pseudo.D_ONCV_PBE_SG15', 'lrs': '', 'jobname': 'H2O_64'}
d144_params = {'nodes': '8', 'walltime': '01:30:00', 'ntasks': '125', 'omp_num_threads': omp_num_threads, 'cores_per_task': '1', 'potentials': 'ln -s $maindir/potentials/pseudo.D_tm_pbe', 'lrs': '-l lrs.in', 'jobname': 'd144'}
vulcan_params = {'queue': 'psmall', 'scratch_path': '/p/lscratchv/mgmolu/dunn27/mgmol/', 'gres': 'lscratchv', 'exe': 'mgmol-bgq'}
cab_params = {'queue': 'pbatch', 'scratch_path': '/p/lscratchd/dunn27/mgmol/', 'gres': 'lscratchd', 'omp_num_threads': '1', 'exe': 'mgmol-pel', 'walltime': '01:30:00'}
runfile_quench_template = "#!/bin/tcsh\n#MSUB -l nodes={nodes},walltime={walltime}\n#MSUB -o mgmol.out\n#MSUB -q {queue}\n#MSUB -A comp\n#MSUB -l gres={gres}\n#MSUB -N {jobname}\n\nrm -f queued\necho ' ' > running\n\nuse boost-nompi-1.55.0\nexport BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0\nexport Boost_NO_SYSTEM_PATHS=ON\n\nsetenv OMP_NUM_THREADS {omp_num_threads}\n\nset ntasks = {ntasks}\n\nset maindir = $home/mgmol\n\nset exe = $maindir/bin/{exe}\n\nset datadir = `pwd`\n\nset scratchdir = {scratch_path}`basename $datadir`\nmkdir $scratchdir\ncd $scratchdir\n\necho ' ' > running\n\nset cfg_quench = mgmol_quench.cfg\n\ncp $datadir/$cfg_quench .\ncp $datadir/coords.in .\ncp $datadir/lrs.in .\n\n{potentials}\n\n#1st run\nsrun -n $ntasks -c {cores_per_task} $exe -c $cfg_quench -i coords.in {lrs}\n\n#restart\nrm -f wave.out\nset restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`\nln -s -f $restart_file wave.out\n\nrm -f running\necho ' ' > queued\n"
runfile_md_template = "#!/bin/tcsh\n#MSUB -l nodes={nodes},walltime={walltime}\n#MSUB -o mgmol.out\n#MSUB -q {queue}\n#MSUB -A comp\n#MSUB -l gres={gres}\n#MSUB -N {jobname}\n\nrm -f queued\necho ' ' > running\n\nuse boost-nompi-1.55.0\nexport BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0\nexport Boost_NO_SYSTEM_PATHS=ON\n\nsetenv OMP_NUM_THREADS {omp_num_threads}\n\nset ntasks = {ntasks}\n\nset maindir = $home/mgmol\n\nset exe = $maindir/bin/{exe}\n\nset datadir = `pwd`\n\nset scratchdir = {scratch_path}`basename $datadir`\nmkdir $scratchdir\ncd $scratchdir\n\necho ' ' > running\n\nset cfg_md = mgmol_md.cfg\n\ncp $datadir/$cfg_md .\n\n#restart\nrm -f wave.out\nset restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`\nln -s -f $restart_file wave.out\n\n#MD run\nsrun -n $ntasks -c {cores_per_task} $exe -c $cfg_md\n\n#restart\nrm -f wave.out\nset restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`\nln -s -f $restart_file wave.out\n\nrm -f running\necho ' ' > queued\n" |
"""
[E] Given a sorted array, create a new array containing squares of all the
number of the input array in the sorted order.
Input: [-2, -1, 0, 2, 3]
Output: [0, 1, 4, 4, 9]
"""
# Time: O(N) Space: O(n)
def make_squares(arr):
n = len(arr)
squares = [0 for x in range(n)]
highestSquareIdx = n - 1
left, right = 0, n - 1
while left <= right:
leftSquare = arr[left] * arr[left]
rightSquare = arr[right] * arr[right]
if leftSquare > rightSquare:
squares[highestSquareIdx] = leftSquare
left += 1
else:
squares[highestSquareIdx] = rightSquare
right -= 1
highestSquareIdx -= 1
return squares
| """
[E] Given a sorted array, create a new array containing squares of all the
number of the input array in the sorted order.
Input: [-2, -1, 0, 2, 3]
Output: [0, 1, 4, 4, 9]
"""
def make_squares(arr):
n = len(arr)
squares = [0 for x in range(n)]
highest_square_idx = n - 1
(left, right) = (0, n - 1)
while left <= right:
left_square = arr[left] * arr[left]
right_square = arr[right] * arr[right]
if leftSquare > rightSquare:
squares[highestSquareIdx] = leftSquare
left += 1
else:
squares[highestSquareIdx] = rightSquare
right -= 1
highest_square_idx -= 1
return squares |
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rules for importing and registering a local JDK."""
load(":default_java_toolchain.bzl", "JVM8_TOOLCHAIN_CONFIGURATION", "default_java_toolchain")
def _detect_java_version(repository_ctx, java_bin):
properties_out = repository_ctx.execute([java_bin, "-XshowSettings:properties"]).stderr
# This returns an indented list of properties separated with newlines:
# " java.vendor.url.bug = ... \n"
# " java.version = 11.0.8\n"
# " java.version.date = 2020-11-05\"
strip_properties = [property.strip() for property in properties_out.splitlines()]
version_property = [property for property in strip_properties if property.startswith("java.version = ")]
if len(version_property) != 1:
return None
version_value = version_property[0][len("java.version = "):]
parts = version_value.split(".")
major = parts[0]
if len(parts) == 1:
return major
elif major == "1": # handles versions below 1.8
minor = parts[1]
return minor
return major
def local_java_runtime(name, java_home, version, runtime_name = None, visibility = ["//visibility:public"]):
"""Defines a java_runtime target together with Java runtime and compile toolchain definitions.
Java runtime toolchain is constrained by flag --java_runtime_version having
value set to either name or version argument.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation. This requires a different configuration for JDK8
than the newer versions.
Args:
name: name of the target.
java_home: Path to the JDK.
version: Version of the JDK.
runtime_name: name of java_runtime target if it already exists.
visibility: Visibility that will be applied to the java runtime target
"""
if runtime_name == None:
runtime_name = name
native.java_runtime(
name = runtime_name,
java_home = java_home,
visibility = visibility,
)
native.config_setting(
name = name + "_name_setting",
values = {"java_runtime_version": name},
visibility = ["//visibility:private"],
)
native.config_setting(
name = name + "_version_setting",
values = {"java_runtime_version": version},
visibility = ["//visibility:private"],
)
native.config_setting(
name = name + "_name_version_setting",
values = {"java_runtime_version": name + "_" + version},
visibility = ["//visibility:private"],
)
native.alias(
name = name + "_settings_alias",
actual = select({
name + "_name_setting": name + "_name_setting",
name + "_version_setting": name + "_version_setting",
"//conditions:default": name + "_name_version_setting",
}),
visibility = ["//visibility:private"],
)
native.toolchain(
name = "runtime_toolchain_definition",
target_settings = [":%s_settings_alias" % name],
toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",
toolchain = runtime_name,
)
if version == "8":
default_java_toolchain(
name = name + "_toolchain_java8",
configuration = JVM8_TOOLCHAIN_CONFIGURATION,
source_version = version,
target_version = version,
java_runtime = runtime_name,
)
elif type(version) == type("") and version.isdigit() and int(version) > 8:
for version in range(8, int(version) + 1):
default_java_toolchain(
name = name + "_toolchain_java" + str(version),
source_version = str(version),
target_version = str(version),
java_runtime = runtime_name,
)
# else version is not recognized and no compilation toolchains are predefined
def _local_java_repository_impl(repository_ctx):
"""Repository rule local_java_repository implementation.
Args:
repository_ctx: repository context
"""
java_home = repository_ctx.attr.java_home
java_home_path = repository_ctx.path(java_home)
if not java_home_path.exists:
fail('The path indicated by the "java_home" attribute "%s" (absolute: "%s") ' +
"does not exist." % (java_home, str(java_home_path)))
repository_ctx.file(
"WORKSPACE",
"# DO NOT EDIT: automatically generated WORKSPACE file for local_java_repository\n" +
"workspace(name = \"{name}\")\n".format(name = repository_ctx.name),
)
extension = ".exe" if repository_ctx.os.name.lower().find("windows") != -1 else ""
java_bin = java_home_path.get_child("bin").get_child("java" + extension)
if not java_bin.exists:
# Java binary does not exist
repository_ctx.file(
"BUILD.bazel",
_NOJDK_BUILD_TPL.format(
local_jdk = repository_ctx.name,
java_binary = "bin/java" + extension,
java_home = java_home,
),
False,
)
return
# Detect version
version = repository_ctx.attr.version if repository_ctx.attr.version != "" else _detect_java_version(repository_ctx, java_bin)
# Prepare BUILD file using "local_java_runtime" macro
build_file = ""
if repository_ctx.attr.build_file != None:
build_file = repository_ctx.read(repository_ctx.path(repository_ctx.attr.build_file))
runtime_name = '"jdk"' if repository_ctx.attr.build_file else None
local_java_runtime_macro = """
local_java_runtime(
name = "%s",
runtime_name = %s,
java_home = "%s",
version = "%s",
)
""" % (repository_ctx.name, runtime_name, java_home, version)
repository_ctx.file(
"BUILD.bazel",
'load("@bazel_tools//tools/jdk:local_java_repository.bzl", "local_java_runtime")\n' +
build_file +
local_java_runtime_macro,
)
# Symlink all files
for file in repository_ctx.path(java_home).readdir():
repository_ctx.symlink(file, file.basename)
# Build file template, when JDK does not exist
_NOJDK_BUILD_TPL = '''load("@bazel_tools//tools/jdk:fail_rule.bzl", "fail_rule")
fail_rule(
name = "jdk",
header = "Auto-Configuration Error:",
message = ("Cannot find Java binary {java_binary} in {java_home}; either correct your JAVA_HOME, " +
"PATH or specify Java from remote repository (e.g. " +
"--java_runtime_version=remotejdk_11")
)
config_setting(
name = "localjdk_setting",
values = {{"java_runtime_version": "{local_jdk}"}},
visibility = ["//visibility:private"],
)
toolchain(
name = "runtime_toolchain_definition",
target_settings = [":localjdk_setting"],
toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",
toolchain = ":jdk",
)
'''
_local_java_repository_rule = repository_rule(
implementation = _local_java_repository_impl,
local = True,
configure = True,
attrs = {
"java_home": attr.string(),
"version": attr.string(),
"build_file": attr.label(),
},
)
def local_java_repository(name, java_home, version = "", build_file = None):
"""Registers a runtime toolchain for local JDK and creates an unregistered compile toolchain.
Toolchain resolution is constrained with --java_runtime_version flag
having value of the "name" or "version" parameter.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation.
If there is no JDK "virtual" targets are created, which fail only when actually needed.
Args:
name: A unique name for this rule.
java_home: Location of the JDK imported.
build_file: optionally BUILD file template
version: optionally java version
"""
_local_java_repository_rule(name = name, java_home = java_home, version = version, build_file = build_file)
native.register_toolchains("@" + name + "//:runtime_toolchain_definition")
| """Rules for importing and registering a local JDK."""
load(':default_java_toolchain.bzl', 'JVM8_TOOLCHAIN_CONFIGURATION', 'default_java_toolchain')
def _detect_java_version(repository_ctx, java_bin):
properties_out = repository_ctx.execute([java_bin, '-XshowSettings:properties']).stderr
strip_properties = [property.strip() for property in properties_out.splitlines()]
version_property = [property for property in strip_properties if property.startswith('java.version = ')]
if len(version_property) != 1:
return None
version_value = version_property[0][len('java.version = '):]
parts = version_value.split('.')
major = parts[0]
if len(parts) == 1:
return major
elif major == '1':
minor = parts[1]
return minor
return major
def local_java_runtime(name, java_home, version, runtime_name=None, visibility=['//visibility:public']):
"""Defines a java_runtime target together with Java runtime and compile toolchain definitions.
Java runtime toolchain is constrained by flag --java_runtime_version having
value set to either name or version argument.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation. This requires a different configuration for JDK8
than the newer versions.
Args:
name: name of the target.
java_home: Path to the JDK.
version: Version of the JDK.
runtime_name: name of java_runtime target if it already exists.
visibility: Visibility that will be applied to the java runtime target
"""
if runtime_name == None:
runtime_name = name
native.java_runtime(name=runtime_name, java_home=java_home, visibility=visibility)
native.config_setting(name=name + '_name_setting', values={'java_runtime_version': name}, visibility=['//visibility:private'])
native.config_setting(name=name + '_version_setting', values={'java_runtime_version': version}, visibility=['//visibility:private'])
native.config_setting(name=name + '_name_version_setting', values={'java_runtime_version': name + '_' + version}, visibility=['//visibility:private'])
native.alias(name=name + '_settings_alias', actual=select({name + '_name_setting': name + '_name_setting', name + '_version_setting': name + '_version_setting', '//conditions:default': name + '_name_version_setting'}), visibility=['//visibility:private'])
native.toolchain(name='runtime_toolchain_definition', target_settings=[':%s_settings_alias' % name], toolchain_type='@bazel_tools//tools/jdk:runtime_toolchain_type', toolchain=runtime_name)
if version == '8':
default_java_toolchain(name=name + '_toolchain_java8', configuration=JVM8_TOOLCHAIN_CONFIGURATION, source_version=version, target_version=version, java_runtime=runtime_name)
elif type(version) == type('') and version.isdigit() and (int(version) > 8):
for version in range(8, int(version) + 1):
default_java_toolchain(name=name + '_toolchain_java' + str(version), source_version=str(version), target_version=str(version), java_runtime=runtime_name)
def _local_java_repository_impl(repository_ctx):
"""Repository rule local_java_repository implementation.
Args:
repository_ctx: repository context
"""
java_home = repository_ctx.attr.java_home
java_home_path = repository_ctx.path(java_home)
if not java_home_path.exists:
fail('The path indicated by the "java_home" attribute "%s" (absolute: "%s") ' + 'does not exist.' % (java_home, str(java_home_path)))
repository_ctx.file('WORKSPACE', '# DO NOT EDIT: automatically generated WORKSPACE file for local_java_repository\n' + 'workspace(name = "{name}")\n'.format(name=repository_ctx.name))
extension = '.exe' if repository_ctx.os.name.lower().find('windows') != -1 else ''
java_bin = java_home_path.get_child('bin').get_child('java' + extension)
if not java_bin.exists:
repository_ctx.file('BUILD.bazel', _NOJDK_BUILD_TPL.format(local_jdk=repository_ctx.name, java_binary='bin/java' + extension, java_home=java_home), False)
return
version = repository_ctx.attr.version if repository_ctx.attr.version != '' else _detect_java_version(repository_ctx, java_bin)
build_file = ''
if repository_ctx.attr.build_file != None:
build_file = repository_ctx.read(repository_ctx.path(repository_ctx.attr.build_file))
runtime_name = '"jdk"' if repository_ctx.attr.build_file else None
local_java_runtime_macro = '\nlocal_java_runtime(\n name = "%s",\n runtime_name = %s,\n java_home = "%s",\n version = "%s",\n)\n' % (repository_ctx.name, runtime_name, java_home, version)
repository_ctx.file('BUILD.bazel', 'load("@bazel_tools//tools/jdk:local_java_repository.bzl", "local_java_runtime")\n' + build_file + local_java_runtime_macro)
for file in repository_ctx.path(java_home).readdir():
repository_ctx.symlink(file, file.basename)
_nojdk_build_tpl = 'load("@bazel_tools//tools/jdk:fail_rule.bzl", "fail_rule")\nfail_rule(\n name = "jdk",\n header = "Auto-Configuration Error:",\n message = ("Cannot find Java binary {java_binary} in {java_home}; either correct your JAVA_HOME, " +\n "PATH or specify Java from remote repository (e.g. " +\n "--java_runtime_version=remotejdk_11")\n)\nconfig_setting(\n name = "localjdk_setting",\n values = {{"java_runtime_version": "{local_jdk}"}},\n visibility = ["//visibility:private"],\n)\ntoolchain(\n name = "runtime_toolchain_definition",\n target_settings = [":localjdk_setting"],\n toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",\n toolchain = ":jdk",\n)\n'
_local_java_repository_rule = repository_rule(implementation=_local_java_repository_impl, local=True, configure=True, attrs={'java_home': attr.string(), 'version': attr.string(), 'build_file': attr.label()})
def local_java_repository(name, java_home, version='', build_file=None):
"""Registers a runtime toolchain for local JDK and creates an unregistered compile toolchain.
Toolchain resolution is constrained with --java_runtime_version flag
having value of the "name" or "version" parameter.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation.
If there is no JDK "virtual" targets are created, which fail only when actually needed.
Args:
name: A unique name for this rule.
java_home: Location of the JDK imported.
build_file: optionally BUILD file template
version: optionally java version
"""
_local_java_repository_rule(name=name, java_home=java_home, version=version, build_file=build_file)
native.register_toolchains('@' + name + '//:runtime_toolchain_definition') |
"""
Here you find either new implemented modules or alternate implementations
of already modules. This directory is intended to have a second implementation
beside the main implementation to have a discussion which implementation to
favor on the long run.
"""
| """
Here you find either new implemented modules or alternate implementations
of already modules. This directory is intended to have a second implementation
beside the main implementation to have a discussion which implementation to
favor on the long run.
""" |
"""Registry utilities to handle formats for gmso Topology."""
class UnsupportedFileFormatError(Exception):
"""Exception to be raised whenever the file loading or saving is not supported."""
class Registry:
"""A registry to incorporate a callable with a file extension."""
def __init__(self):
self.handlers = {}
def _assert_can_process(self, extension):
if extension not in self.handlers:
raise UnsupportedFileFormatError(
f"Extension {extension} cannot be processed as no utility "
f"is defined in the current API to handle {extension} files."
)
def get_callable(self, extension):
"""Get the callable associated with extension."""
self._assert_can_process(extension)
return self.handlers[extension]
SaversRegistry = Registry()
LoadersRegistry = Registry()
class saves_as:
"""Decorator to aid saving."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as saver for an extension."""
for ext in self.extensions:
SaversRegistry.handlers[ext] = method
return method
class loads_as:
"""Decorator to aid loading."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as loader for an extension."""
for ext in self.extensions:
LoadersRegistry.handlers[ext] = method
return method
| """Registry utilities to handle formats for gmso Topology."""
class Unsupportedfileformaterror(Exception):
"""Exception to be raised whenever the file loading or saving is not supported."""
class Registry:
"""A registry to incorporate a callable with a file extension."""
def __init__(self):
self.handlers = {}
def _assert_can_process(self, extension):
if extension not in self.handlers:
raise unsupported_file_format_error(f'Extension {extension} cannot be processed as no utility is defined in the current API to handle {extension} files.')
def get_callable(self, extension):
"""Get the callable associated with extension."""
self._assert_can_process(extension)
return self.handlers[extension]
savers_registry = registry()
loaders_registry = registry()
class Saves_As:
"""Decorator to aid saving."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as saver for an extension."""
for ext in self.extensions:
SaversRegistry.handlers[ext] = method
return method
class Loads_As:
"""Decorator to aid loading."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as loader for an extension."""
for ext in self.extensions:
LoadersRegistry.handlers[ext] = method
return method |
dosyaadi = input("Enter file name: ")
dosyaadi = str(dosyaadi + ".txt")
with open(dosyaadi, 'r') as file :
dosyaicerigi = file.read()
silinecek = str(input("Enter the text that you wish to delete: "))
dosyaicerigi = dosyaicerigi.replace(silinecek, '')
with open(dosyaadi, 'w') as file:
file.write(dosyaicerigi)
file.close()
print("-" * 30)
print("Successfully deleted!")
print("-" * 30)
| dosyaadi = input('Enter file name: ')
dosyaadi = str(dosyaadi + '.txt')
with open(dosyaadi, 'r') as file:
dosyaicerigi = file.read()
silinecek = str(input('Enter the text that you wish to delete: '))
dosyaicerigi = dosyaicerigi.replace(silinecek, '')
with open(dosyaadi, 'w') as file:
file.write(dosyaicerigi)
file.close()
print('-' * 30)
print('Successfully deleted!')
print('-' * 30) |
"""
decoded AUTH_HEADER (newlines added for readability):
{
"identity": {
"account_number": "1234",
"internal": {
"org_id": "5678"
},
"type": "User",
"user": {
"email": "test@example.com",
"first_name": "Firstname",
"is_active": true,
"is_internal": true,
"is_org_admin": false,
"last_name": "Lastname",
"locale": "en_US",
"username": "test_username"
}
}
"entitlements": {
"smart_management": {
"is_entitled": true
}
}
}
"""
AUTH_HEADER = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6"
"IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiI1"
"Njc4In0sInR5cGUiOiJVc2VyIiwidXNlciI6eyJl"
"bWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJmaXJz"
"dF9uYW1lIjoiRmlyc3RuYW1lIiwiaXNfYWN0aXZl"
"Ijp0cnVlLCJpc19pbnRlcm5hbCI6dHJ1ZSwiaXNf"
"b3JnX2FkbWluIjpmYWxzZSwibGFzdF9uYW1lIjoi"
"TGFzdG5hbWUiLCJsb2NhbGUiOiJlbl9VUyIsInVz"
"ZXJuYW1lIjoidGVzdF91c2VybmFtZSJ9fSwiZW50"
"aXRsZW1lbnRzIjogeyJzbWFydF9tYW5hZ2VtZW50"
"IjogeyJpc19lbnRpdGxlZCI6IHRydWUgfX19Cg=="
}
AUTH_HEADER_NO_ENTITLEMENTS = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6Ij"
"EyMzQiLCJ0eXBlIjoiVXNlciIsInVzZXIiOnsidXNl"
"cm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIiwiZW1haWwiOi"
"J0ZXN0QGV4YW1wbGUuY29tIiwiZmlyc3RfbmFtZSI6"
"IkZpcnN0bmFtZSIsImxhc3RfbmFtZSI6Ikxhc3RuYW"
"1lIiwiaXNfYWN0aXZlIjp0cnVlLCJpc19vcmdfYWRt"
"aW4iOmZhbHNlLCJpc19pbnRlcm5hbCI6dHJ1ZSwibG"
"9jYWxlIjoiZW5fVVMifSwiaW50ZXJuYWwiOnsib3Jn"
"X2lkIjoiNTY3OCJ9fX0KCg=="
}
AUTH_HEADER_SMART_MGMT_FALSE = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6"
"IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiAi"
"NTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1c2VyIjp7"
"ImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImZp"
"cnN0X25hbWUiOiJGaXJzdG5hbWUiLCJpc19hY3Rp"
"dmUiOnRydWUsImlzX2ludGVybmFsIjp0cnVlLCJp"
"c19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0X25hbWUi"
"OiJMYXN0bmFtZSIsImxvY2FsZSI6ImVuX1VTIiwi"
"dXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIn19LCJl"
"bnRpdGxlbWVudHMiOnsic21hcnRfbWFuYWdlbWVu"
"dCI6eyJpc19lbnRpdGxlZCI6IGZhbHNlfX19Cg=="
}
# this can't happen in real life, adding test anyway
AUTH_HEADER_NO_ACCT_BUT_HAS_ENTS = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJpbnRlcm5hbCI6eyJvcmdf"
"aWQiOiAiNTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1"
"c2VyIjp7ImVtYWlsIjoidGVzdEBleGFtcGxlLmNv"
"bSIsImZpcnN0X25hbWUiOiJGaXJzdG5hbWUiLCJp"
"c19hY3RpdmUiOnRydWUsImlzX2ludGVybmFsIjp0"
"cnVlLCJpc19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0"
"X25hbWUiOiJMYXN0bmFtZSIsImxvY2FsZSI6ImVu"
"X1VTIiwidXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1l"
"In19LCJlbnRpdGxlbWVudHMiOnsic21hcnRfbWFu"
"YWdlbWVudCI6eyJpc19lbnRpdGxlZCI6IHRydWV9"
"fX0K"
}
"""
decoded AUTH_HEADER_NO_ACCT (newlines added for readablity):
{
"identity": {
"internal": {
"org_id": "9999"
},
"type": "User",
"user": {
"email": "nonumber@example.com",
"first_name": "No",
"is_active": true,
"is_internal": true,
"is_org_admin": false,
"last_name": "Number",
"locale": "en_US",
"username": "nonumber"
}
}
}
"""
AUTH_HEADER_NO_ACCT = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJ0eXBlIjoiVXNlciIsInVzZXIiO"
"nsidXNlcm5hbWUiOiJub251bWJlciIsImVtYWlsIjoibm"
"9udW1iZXJAZXhhbXBsZS5jb20iLCJmaXJzdF9uYW1lIjo"
"iTm8iLCJsYXN0X25hbWUiOiJOdW1iZXIiLCJpc19hY3Rp"
"dmUiOnRydWUsImlzX29yZ19hZG1pbiI6ZmFsc2UsImlzX"
"2ludGVybmFsIjp0cnVlLCJsb2NhbGUiOiJlbl9VUyJ9LC"
"JpbnRlcm5hbCI6eyJvcmdfaWQiOiI5OTk5In19fQo="
}
BASELINE_ONE_LOAD = {
"baseline_facts": [
{"name": "arch", "value": "x86_64"},
{"name": "phony.arch.fact", "value": "some value"},
],
"display_name": "arch baseline",
}
BASELINE_TWO_LOAD = {
"baseline_facts": [
{"name": "memory", "value": "64GB"},
{"name": "cpu_sockets", "value": "16"},
],
"display_name": "cpu + mem baseline",
}
BASELINE_THREE_LOAD = {
"baseline_facts": [
{"name": "nested", "values": [{"name": "cpu_sockets", "value": "16"}]}
],
"display_name": "cpu + mem baseline",
}
BASELINE_PARTIAL_ONE = {"baseline_facts": [{"name": "hello", "value": "world"}]}
BASELINE_PARTIAL_TWO = {
"display_name": "ABCDE",
"baseline_facts": [
{
"name": "hello",
"values": [
{"name": "nested_one", "value": "one"},
{"name": "nested_two", "value": "two"},
],
}
],
}
BASELINE_PARTIAL_CONFLICT = {"display_name": "arch baseline"}
CREATE_FROM_INVENTORY = {
"display_name": "created_from_inventory",
"inventory_uuid": "df925152-c45d-11e9-a1f0-c85b761454fa",
}
SYSTEM_WITH_PROFILE = {
"account": "9876543",
"bios_uuid": "e380fd4a-28ae-11e9-974c-c85b761454fb",
"created": "2018-01-31T13:00:00.100010Z",
"display_name": None,
"fqdn": None,
"id": "bbbbbbbb-28ae-11e9-afd9-c85b761454fa",
"insights_id": "00000000-28af-11e9-9ab0-c85b761454fa",
"ip_addresses": ["10.0.0.3", "2620:52:0:2598:5054:ff:fecd:ae15"],
"mac_addresses": ["52:54:00:cd:ae:00", "00:00:00:00:00:00"],
"rhel_machine_id": None,
"satellite_id": None,
"subscription_manager_id": "RHN Classic and Red Hat Subscription Management",
"system_profile": {
"salutation": "hi",
"system_profile_exists": False,
"installed_packages": [
"openssl-1.1.1c-2.fc30.x86_64",
"python2-libs-2.7.16-2.fc30.x86_64",
],
"id": "bbbbbbbb-28ae-11e9-afd9-c85b761454fa",
},
"tags": [],
"updated": "2018-01-31T14:00:00.500000Z",
}
| """
decoded AUTH_HEADER (newlines added for readability):
{
"identity": {
"account_number": "1234",
"internal": {
"org_id": "5678"
},
"type": "User",
"user": {
"email": "test@example.com",
"first_name": "Firstname",
"is_active": true,
"is_internal": true,
"is_org_admin": false,
"last_name": "Lastname",
"locale": "en_US",
"username": "test_username"
}
}
"entitlements": {
"smart_management": {
"is_entitled": true
}
}
}
"""
auth_header = {'X-RH-IDENTITY': 'eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiI1Njc4In0sInR5cGUiOiJVc2VyIiwidXNlciI6eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJmaXJzdF9uYW1lIjoiRmlyc3RuYW1lIiwiaXNfYWN0aXZlIjp0cnVlLCJpc19pbnRlcm5hbCI6dHJ1ZSwiaXNfb3JnX2FkbWluIjpmYWxzZSwibGFzdF9uYW1lIjoiTGFzdG5hbWUiLCJsb2NhbGUiOiJlbl9VUyIsInVzZXJuYW1lIjoidGVzdF91c2VybmFtZSJ9fSwiZW50aXRsZW1lbnRzIjogeyJzbWFydF9tYW5hZ2VtZW50IjogeyJpc19lbnRpdGxlZCI6IHRydWUgfX19Cg=='}
auth_header_no_entitlements = {'X-RH-IDENTITY': 'eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6IjEyMzQiLCJ0eXBlIjoiVXNlciIsInVzZXIiOnsidXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIiwiZmlyc3RfbmFtZSI6IkZpcnN0bmFtZSIsImxhc3RfbmFtZSI6Ikxhc3RuYW1lIiwiaXNfYWN0aXZlIjp0cnVlLCJpc19vcmdfYWRtaW4iOmZhbHNlLCJpc19pbnRlcm5hbCI6dHJ1ZSwibG9jYWxlIjoiZW5fVVMifSwiaW50ZXJuYWwiOnsib3JnX2lkIjoiNTY3OCJ9fX0KCg=='}
auth_header_smart_mgmt_false = {'X-RH-IDENTITY': 'eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiAiNTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1c2VyIjp7ImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImZpcnN0X25hbWUiOiJGaXJzdG5hbWUiLCJpc19hY3RpdmUiOnRydWUsImlzX2ludGVybmFsIjp0cnVlLCJpc19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0X25hbWUiOiJMYXN0bmFtZSIsImxvY2FsZSI6ImVuX1VTIiwidXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIn19LCJlbnRpdGxlbWVudHMiOnsic21hcnRfbWFuYWdlbWVudCI6eyJpc19lbnRpdGxlZCI6IGZhbHNlfX19Cg=='}
auth_header_no_acct_but_has_ents = {'X-RH-IDENTITY': 'eyJpZGVudGl0eSI6eyJpbnRlcm5hbCI6eyJvcmdfaWQiOiAiNTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1c2VyIjp7ImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImZpcnN0X25hbWUiOiJGaXJzdG5hbWUiLCJpc19hY3RpdmUiOnRydWUsImlzX2ludGVybmFsIjp0cnVlLCJpc19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0X25hbWUiOiJMYXN0bmFtZSIsImxvY2FsZSI6ImVuX1VTIiwidXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIn19LCJlbnRpdGxlbWVudHMiOnsic21hcnRfbWFuYWdlbWVudCI6eyJpc19lbnRpdGxlZCI6IHRydWV9fX0K'}
'\ndecoded AUTH_HEADER_NO_ACCT (newlines added for readablity):\n{\n "identity": {\n "internal": {\n "org_id": "9999"\n },\n "type": "User",\n "user": {\n "email": "nonumber@example.com",\n "first_name": "No",\n "is_active": true,\n "is_internal": true,\n "is_org_admin": false,\n "last_name": "Number",\n "locale": "en_US",\n "username": "nonumber"\n }\n }\n}\n'
auth_header_no_acct = {'X-RH-IDENTITY': 'eyJpZGVudGl0eSI6eyJ0eXBlIjoiVXNlciIsInVzZXIiOnsidXNlcm5hbWUiOiJub251bWJlciIsImVtYWlsIjoibm9udW1iZXJAZXhhbXBsZS5jb20iLCJmaXJzdF9uYW1lIjoiTm8iLCJsYXN0X25hbWUiOiJOdW1iZXIiLCJpc19hY3RpdmUiOnRydWUsImlzX29yZ19hZG1pbiI6ZmFsc2UsImlzX2ludGVybmFsIjp0cnVlLCJsb2NhbGUiOiJlbl9VUyJ9LCJpbnRlcm5hbCI6eyJvcmdfaWQiOiI5OTk5In19fQo='}
baseline_one_load = {'baseline_facts': [{'name': 'arch', 'value': 'x86_64'}, {'name': 'phony.arch.fact', 'value': 'some value'}], 'display_name': 'arch baseline'}
baseline_two_load = {'baseline_facts': [{'name': 'memory', 'value': '64GB'}, {'name': 'cpu_sockets', 'value': '16'}], 'display_name': 'cpu + mem baseline'}
baseline_three_load = {'baseline_facts': [{'name': 'nested', 'values': [{'name': 'cpu_sockets', 'value': '16'}]}], 'display_name': 'cpu + mem baseline'}
baseline_partial_one = {'baseline_facts': [{'name': 'hello', 'value': 'world'}]}
baseline_partial_two = {'display_name': 'ABCDE', 'baseline_facts': [{'name': 'hello', 'values': [{'name': 'nested_one', 'value': 'one'}, {'name': 'nested_two', 'value': 'two'}]}]}
baseline_partial_conflict = {'display_name': 'arch baseline'}
create_from_inventory = {'display_name': 'created_from_inventory', 'inventory_uuid': 'df925152-c45d-11e9-a1f0-c85b761454fa'}
system_with_profile = {'account': '9876543', 'bios_uuid': 'e380fd4a-28ae-11e9-974c-c85b761454fb', 'created': '2018-01-31T13:00:00.100010Z', 'display_name': None, 'fqdn': None, 'id': 'bbbbbbbb-28ae-11e9-afd9-c85b761454fa', 'insights_id': '00000000-28af-11e9-9ab0-c85b761454fa', 'ip_addresses': ['10.0.0.3', '2620:52:0:2598:5054:ff:fecd:ae15'], 'mac_addresses': ['52:54:00:cd:ae:00', '00:00:00:00:00:00'], 'rhel_machine_id': None, 'satellite_id': None, 'subscription_manager_id': 'RHN Classic and Red Hat Subscription Management', 'system_profile': {'salutation': 'hi', 'system_profile_exists': False, 'installed_packages': ['openssl-1.1.1c-2.fc30.x86_64', 'python2-libs-2.7.16-2.fc30.x86_64'], 'id': 'bbbbbbbb-28ae-11e9-afd9-c85b761454fa'}, 'tags': [], 'updated': '2018-01-31T14:00:00.500000Z'} |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 22:23:07 2020
@author: Neal LONG
Try to construct URL with string.format
"""
base_url = "http://quotes.money.163.com/service/gszl_{:>06}.html?type={}"
stock = "000002"
api_type = 'cp'
print("http://quotes.money.163.com/service/gszl_"+stock+".html?type="+api_type)
print(base_url.format(stock,api_type))
print('='*40)
stock = "00002"
print("http://quotes.money.163.com/service/gszl_"+stock+".html?type="+api_type)
print(base_url.format(stock,api_type))
print('='*40)
print('='*40)
print('{:>6}'.format('236'))
print('{:>06}'.format('236'))
print("Every {} should know the use of {}-{} programming and {}"
.format("programmer", "Open", "Source", "Operating Systems"))
print("Every {3} should know the use of {2}-{1} programming and {0}"
.format("programmer", "Open", "Source", "Operating Systems")) | """
Created on Wed Feb 26 22:23:07 2020
@author: Neal LONG
Try to construct URL with string.format
"""
base_url = 'http://quotes.money.163.com/service/gszl_{:>06}.html?type={}'
stock = '000002'
api_type = 'cp'
print('http://quotes.money.163.com/service/gszl_' + stock + '.html?type=' + api_type)
print(base_url.format(stock, api_type))
print('=' * 40)
stock = '00002'
print('http://quotes.money.163.com/service/gszl_' + stock + '.html?type=' + api_type)
print(base_url.format(stock, api_type))
print('=' * 40)
print('=' * 40)
print('{:>6}'.format('236'))
print('{:>06}'.format('236'))
print('Every {} should know the use of {}-{} programming and {}'.format('programmer', 'Open', 'Source', 'Operating Systems'))
print('Every {3} should know the use of {2}-{1} programming and {0}'.format('programmer', 'Open', 'Source', 'Operating Systems')) |
'''
DNA++ (c) DNA++ 2017
All rights reserved.
@author: neilswainston
'''
| """
DNA++ (c) DNA++ 2017
All rights reserved.
@author: neilswainston
""" |
"""Mock responses for recommendations."""
SEARCH_REQ = {
"criteria": {
"policy_type": ['reputation_override'],
"status": ['NEW', 'REJECTED', 'ACCEPTED'],
"hashes": ['111', '222']
},
"rows": 50,
"sort": [
{
"field": "impact_score",
"order": "DESC"
}
]
}
SEARCH_RESP = {
"results": [
{
"recommendation_id": "91e9158f-23cc-47fd-af7f-8f56e2206523",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede",
"filename": "XprotectService",
"application": {
"type": "EXE",
"value": "FOO"
}
},
"workflow": {
"status": "NEW",
"changed_by": "rbaratheon@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T20:53:39.000Z",
"comment": "Ours is the fury"
},
"impact": {
"org_adoption": "LOW",
"impacted_devices": 45,
"event_count": 76,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
},
{
"recommendation_id": "bd50c2b2-5403-4e9e-8863-9991f70df026",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0",
"filename": "sophos ui.msi"
},
"workflow": {
"status": "NEW",
"changed_by": "tlannister@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T20:53:09.000Z",
"comment": "Always pay your debts"
},
"impact": {
"org_adoption": "HIGH",
"impacted_devices": 8,
"event_count": 25,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
},
{
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "NEW",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
],
"num_found": 3
}
ACTION_INIT = {
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "NEW",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
ACTION_REQS = [
{
"action": "ACCEPT",
"comment": "Alpha"
},
{
"action": "RESET"
},
{
"action": "REJECT",
"comment": "Charlie"
},
]
ACTION_REFRESH_SEARCH = {
"criteria": {
"status": ['NEW', 'REJECTED', 'ACCEPTED'],
"policy_type": ['reputation_override']
},
"rows": 50
}
ACTION_SEARCH_RESP = {
"results": [ACTION_INIT],
"num_found": 1
}
ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED']
ACTION_INIT_ACCEPTED = {
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "ACCEPTED",
"ref_id": "e9410b754ea011ebbfd0db2585a41b07",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
| """Mock responses for recommendations."""
search_req = {'criteria': {'policy_type': ['reputation_override'], 'status': ['NEW', 'REJECTED', 'ACCEPTED'], 'hashes': ['111', '222']}, 'rows': 50, 'sort': [{'field': 'impact_score', 'order': 'DESC'}]}
search_resp = {'results': [{'recommendation_id': '91e9158f-23cc-47fd-af7f-8f56e2206523', 'rule_type': 'reputation_override', 'policy_id': 0, 'new_rule': {'override_type': 'SHA256', 'override_list': 'WHITE_LIST', 'sha256_hash': '32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede', 'filename': 'XprotectService', 'application': {'type': 'EXE', 'value': 'FOO'}}, 'workflow': {'status': 'NEW', 'changed_by': 'rbaratheon@example.com', 'create_time': '2021-05-18T16:37:07.000Z', 'update_time': '2021-08-31T20:53:39.000Z', 'comment': 'Ours is the fury'}, 'impact': {'org_adoption': 'LOW', 'impacted_devices': 45, 'event_count': 76, 'impact_score': 0, 'update_time': '2021-05-18T16:37:07.000Z'}}, {'recommendation_id': 'bd50c2b2-5403-4e9e-8863-9991f70df026', 'rule_type': 'reputation_override', 'policy_id': 0, 'new_rule': {'override_type': 'SHA256', 'override_list': 'WHITE_LIST', 'sha256_hash': '0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0', 'filename': 'sophos ui.msi'}, 'workflow': {'status': 'NEW', 'changed_by': 'tlannister@example.com', 'create_time': '2021-05-18T16:37:07.000Z', 'update_time': '2021-08-31T20:53:09.000Z', 'comment': 'Always pay your debts'}, 'impact': {'org_adoption': 'HIGH', 'impacted_devices': 8, 'event_count': 25, 'impact_score': 0, 'update_time': '2021-05-18T16:37:07.000Z'}}, {'recommendation_id': '0d9da444-cfa7-4488-9fad-e2abab099b68', 'rule_type': 'reputation_override', 'policy_id': 0, 'new_rule': {'override_type': 'SHA256', 'override_list': 'WHITE_LIST', 'sha256_hash': '2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124', 'filename': 'mimecast for outlook 7.8.0.125 (x86).msi'}, 'workflow': {'status': 'NEW', 'changed_by': 'estark@example.com', 'create_time': '2021-05-18T16:37:07.000Z', 'update_time': '2021-08-31T15:13:40.000Z', 'comment': 'Winter is coming'}, 'impact': {'org_adoption': 'MEDIUM', 'impacted_devices': 45, 'event_count': 79, 'impact_score': 0, 'update_time': '2021-05-18T16:37:07.000Z'}}], 'num_found': 3}
action_init = {'recommendation_id': '0d9da444-cfa7-4488-9fad-e2abab099b68', 'rule_type': 'reputation_override', 'policy_id': 0, 'new_rule': {'override_type': 'SHA256', 'override_list': 'WHITE_LIST', 'sha256_hash': '2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124', 'filename': 'mimecast for outlook 7.8.0.125 (x86).msi'}, 'workflow': {'status': 'NEW', 'changed_by': 'estark@example.com', 'create_time': '2021-05-18T16:37:07.000Z', 'update_time': '2021-08-31T15:13:40.000Z', 'comment': 'Winter is coming'}, 'impact': {'org_adoption': 'MEDIUM', 'impacted_devices': 45, 'event_count': 79, 'impact_score': 0, 'update_time': '2021-05-18T16:37:07.000Z'}}
action_reqs = [{'action': 'ACCEPT', 'comment': 'Alpha'}, {'action': 'RESET'}, {'action': 'REJECT', 'comment': 'Charlie'}]
action_refresh_search = {'criteria': {'status': ['NEW', 'REJECTED', 'ACCEPTED'], 'policy_type': ['reputation_override']}, 'rows': 50}
action_search_resp = {'results': [ACTION_INIT], 'num_found': 1}
action_refresh_status = ['ACCEPTED', 'NEW', 'REJECTED']
action_init_accepted = {'recommendation_id': '0d9da444-cfa7-4488-9fad-e2abab099b68', 'rule_type': 'reputation_override', 'policy_id': 0, 'new_rule': {'override_type': 'SHA256', 'override_list': 'WHITE_LIST', 'sha256_hash': '2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124', 'filename': 'mimecast for outlook 7.8.0.125 (x86).msi'}, 'workflow': {'status': 'ACCEPTED', 'ref_id': 'e9410b754ea011ebbfd0db2585a41b07', 'changed_by': 'estark@example.com', 'create_time': '2021-05-18T16:37:07.000Z', 'update_time': '2021-08-31T15:13:40.000Z', 'comment': 'Winter is coming'}, 'impact': {'org_adoption': 'MEDIUM', 'impacted_devices': 45, 'event_count': 79, 'impact_score': 0, 'update_time': '2021-05-18T16:37:07.000Z'}} |
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
return root
return None | class Solution:
def invert_tree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
(root.left, root.right) = (self.invertTree(root.right), self.invertTree(root.left))
return root
return None |
def assert_not_none(actual_result, message=""):
if not message:
message = f"{actual_result} resulted with None"
assert actual_result, message
def assert_equal(actual_result, expected_result, message=""):
if not message:
message = f"{actual_result} is not equal to expected " \
f"result {expected_result}"
assert actual_result == expected_result, message
def assert_in_list(searched_list, wanted_element, message=""):
if not message:
message = f"Failed to find '{wanted_element}' in list {searched_list}"
assert wanted_element in searched_list, message
def assert_not_in_list(searched_list, unwanted_element, message=""):
if not message:
message = f"'{unwanted_element}' found in list {searched_list} \n " \
f"although it should not be"
assert unwanted_element not in searched_list, message
def assert_of_type(wanted_type, wanted_object, message=""):
if not message:
message = f"{wanted_object} is not of type: {wanted_type}"
assert isinstance(wanted_object, wanted_type), message
| def assert_not_none(actual_result, message=''):
if not message:
message = f'{actual_result} resulted with None'
assert actual_result, message
def assert_equal(actual_result, expected_result, message=''):
if not message:
message = f'{actual_result} is not equal to expected result {expected_result}'
assert actual_result == expected_result, message
def assert_in_list(searched_list, wanted_element, message=''):
if not message:
message = f"Failed to find '{wanted_element}' in list {searched_list}"
assert wanted_element in searched_list, message
def assert_not_in_list(searched_list, unwanted_element, message=''):
if not message:
message = f"'{unwanted_element}' found in list {searched_list} \n although it should not be"
assert unwanted_element not in searched_list, message
def assert_of_type(wanted_type, wanted_object, message=''):
if not message:
message = f'{wanted_object} is not of type: {wanted_type}'
assert isinstance(wanted_object, wanted_type), message |
"""
This is the doc for the Grid Diagnostics module. These functions
are based on the grid diagnostics from the GEneral Meteorological
PAcKage (GEMPAK). Note that the names are case sensitive and some
are named slightly different from GEMPAK functions to avoid conflicts
with Jython built-ins (e.g. str).
<P>
In the following operators, scalar operands are named S<sub>n</sub> and
vector operands are named V<sub>n</sub>. Lowercase u and v refer to the
grid relative components of a vector.
"""
def GRAVITY():
""" Gravity constant """
return DerivedGridFactory.GRAVITY;
# Math functions
def atn2(S1,S2,WA=0):
""" Wrapper for atan2 built-in
<div class=jython>
ATN2 (S1, S2) = ATAN ( S1 / S2 )<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.atan2(S1,S2,WA)
def add(S1,S2,WA=0):
""" Addition
<div class=jython>
ADD (S1, S2) = S1 + S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.add(S1,S2,WA)
def mul(S1,S2,WA=0):
""" Multiply
<div class=jython>
MUL (S1, S2) = S1 * S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.multiply(S1,S2,WA)
def quo(S1,S2,WA=0):
""" Divide
<div class=jython>
QUO (S1, S2) = S1 / S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.divide(S1,S2,WA)
def sub(S1,S2,WA=0):
""" Subtract
<div class=jython>
SUB (S1, S2) = S1 - S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.subtract(S1,S2,WA)
# Scalar quantities
def adv(S,V):
""" Horizontal Advection, negative by convention
<div class=jython>
ADV ( S, V ) = - ( u * DDX (S) + v * DDY (S) )
</div>
"""
return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S)))
def avg(S1,S2):
""" Average of 2 scalars
<div class=jython>
AVG (S1, S2) = ( S1 + S2 ) / 2
</div>
"""
return add(S1,S2)/2
def avor(V):
""" Absolute Vorticity
<div class=jython>
AVOR ( V ) = VOR ( V ) + CORL(V)
</div>
"""
relv = vor(V)
return add(relv,corl(relv))
def circs(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CIRC", int(D))
def corl(S):
""" Coriolis Parameter for all points in a grid
<div class=jython>
CORL = TWO_OMEGA*sin(latr)
</div>
"""
return DerivedGridFactory.createCoriolisGrid(S)
def cress(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CRES", int(D))
def cros(V1,V2):
""" Vector cross product magnitude
<div class=jython>
CROS ( V1, V2 ) = u1 * v2 - u2 * v1
</div>
"""
return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1)))
def ddx(S):
""" Take the derivative with respect to the domain's X coordinate
"""
return GridMath.ddx(S);
def ddy(S):
""" Take the derivative with respect to the domain's Y coordinate
"""
return GridMath.ddy(S);
def defr(V):
""" Total deformation
<div class=jython>
DEF ( V ) = ( STRD (V) ** 2 + SHR (V) ** 2 ) ** .5
</div>
"""
return mag(strd(V),shr(V))
def div(V):
""" Horizontal Divergence
<div class=jython>
DIV ( V ) = DDX ( u ) + DDY ( v )
</div>
"""
return add(ddx(ur(V)),ddy(vr(V)))
def dirn(V):
""" North relative direction of a vector
<div class=jython>
DIRN ( V ) = DIRR ( un(v), vn(v) )
</div>
"""
return dirr(DerivedGridFactory.createTrueFlowVector(V))
def dirr(V):
""" Grid relative direction of a vector
"""
return DerivedGridFactory.createVectorDirection(V)
def dot(V1,V2):
""" Vector dot product
<div class=jython>
DOT ( V1, V2 ) = u1 * u2 + v1 * v2
</div>
"""
product = mul(V1,V2)
return add(ur(product),vr(product))
def gwfs(S, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return GridUtil.smooth(S, "GWFS", int(N))
def jcbn(S1,S2):
""" Jacobian Determinant
<div class=jython>
JCBN ( S1, S2 ) = DDX (S1) * DDY (S2) - DDY (S1) * DDX (S2)
</div>
"""
return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2)))
def latr(S):
""" Latitudue all points in a grid
"""
return DerivedGridFactory.createLatitudeGrid(S)
def lap(S):
""" Laplacian operator
<div class=jython>
LAP ( S ) = DIV ( GRAD (S) )
</div>
"""
grads = grad(S)
return div(grads)
def lav(S,level1=None,level2=None, unit=None):
""" Layer Average of a multi layer grid
<div class=jython>
LAV ( S ) = ( S (level1) + S (level2) ) / 2.
</div>
"""
if level1 == None:
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE)
else:
return layerAverage(S,level1,level2, unit)
def ldf(S,level1,level2, unit=None):
""" Layer Difference
<div class=jython>
LDF ( S ) = S (level1) - S (level2)
</div>
"""
return layerDiff(S,level1,level2, unit);
def mag(*a):
""" Magnitude of a vector
"""
if (len(a) == 1):
return DerivedGridFactory.createVectorMagnitude(a[0]);
else:
return DerivedGridFactory.createVectorMagnitude(a[0],a[1]);
def mixr(temp,rh):
""" Mixing Ratio from Temperature, RH (requires pressure domain)
"""
return DerivedGridFactory.createMixingRatio(temp,rh)
def relh(temp,mixr):
""" Create Relative Humidity from Temperature, mixing ratio (requires pressure domain)
"""
return DerivedGridFactory.createRelativeHumidity(temp,mixr)
def pvor(S,V):
""" Potetial Vorticity (usually from theta and wind)
"""
return DerivedGridFactory.createPotentialVorticity(S,V)
def rects(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "RECT", int(D))
def savg(S):
""" Average over whole grid
<div class=jython>
SAVG ( S ) = average of all non-missing grid point values
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def savs(S):
""" Average over grid subset
<div class=jython>
SAVS ( S ) = average of all non-missing grid point values in the subset
area
</div>
"""
return savg(S)
def sdiv(S,V):
""" Horizontal Flux Divergence
<div class=jython>
SDIV ( S, V ) = S * DIV ( V ) + DOT ( V, GRAD ( S ) )
</div>
"""
return add(mul(S,(div(V))) , dot(V,grad(S)))
def shr(V):
""" Shear Deformation
<div class=jython>
SHR ( V ) = DDX ( v ) + DDY ( u )
</div>
"""
return add(ddx(vr(V)),ddy(ur(V)))
def sm5s(S):
""" Smooth a scalar grid using a 5-point smoother
<div class=jython>
SM5S ( S ) = .5 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
</div>
"""
return GridUtil.smooth(S, "SM5S")
def sm9s(S):
""" Smooth a scalar grid using a 9-point smoother
<div class=jython>
SM9S ( S ) = .25 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
+ .0625 * ( S (i+1,j+1) +
S (i+1,j-1) +
S (i-1,j+1) +
S (i-1,j-1) )
</div>
"""
return GridUtil.smooth(S, "SM9S")
def strd(V):
""" Stretching Deformation
<div class=jython>
STRD ( V ) = DDX ( u ) - DDY ( v )
</div>
"""
return sub(ddx(ur(V)),ddy(vr(V)))
def thta(temp):
""" Potential Temperature from Temperature (requires pressure domain)
"""
return DerivedGridFactory.createPotentialTemperature(temp)
def thte(temp,rh):
""" Equivalent Potential Temperature from Temperature and Relative
humidity (requires pressure domain)
"""
return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh)
def un(V):
""" North relative u component
"""
return ur(DerivedGridFactory.createTrueFlowVector(V))
def ur(V):
""" Grid relative u component
"""
return DerivedGridFactory.getUComponent(V)
def vn(V):
""" North relative v component
"""
return vr(DerivedGridFactory.createTrueFlowVector(V))
def vor(V):
""" Relative Vorticity
<div class=jython>
VOR ( V ) = DDX ( v ) - DDY ( u )
</div>
"""
return sub(ddx(vr(V)),ddy(ur(V)))
def vr(V):
""" Grid relative v component
"""
return DerivedGridFactory.getVComponent(V)
def xav(S):
""" Average along a grid row
<div class=jython>
XAV (S) = ( S (X1) + S (X2) + ... + S (KXD) ) / KNT
KXD = number of points in row
KNT = number of non-missing points in row
XAV for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X)
def xsum(S):
""" Sum along a grid row
<div class=jython>
XSUM (S) = ( S (X1) + S (X2) + ... + S (KXD) )
KXD = number of points in row
XSUM for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X)
def yav(S):
""" Average along a grid column
<div class=jython>
YAV (S) = ( S (Y1) + S (Y2) + ... + S (KYD) ) / KNT
KYD = number of points in column
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y)
def ysum(S):
""" Sum along a grid column
<div class=jython>
YSUM (S) = ( S (Y1) + S (Y2) + ... + S (KYD) )
KYD = number of points in row
YSUM for a column is stored at every point in that column.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y)
def zav(S):
""" Average across the levels of a grid at all points
<div class=jython>
ZAV (S) = ( S (Z1) + S (Z2) + ... + S (KZD) ) / KNT
KZD = number of levels
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def zsum(S):
""" Sum across the levels of a grid at all points
<div class=jython>
ZSUM (S) = ( S (Z1) + S (Z2) + ... + S (KZD) )
KZD = number of levels
ZSUM for a vertical column is stored at every point
</div>
"""
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM)
def wshr(V, Z, top, bottom):
""" Magnitude of the vertical wind shear in a layer
<div class=jython>
WSHR ( V ) = MAG [ VLDF (V) ] / LDF (Z)
</div>
"""
dv = mag(vldf(V,top,bottom))
dz = ldf(Z,top,bottom)
return quo(dv,dz)
# Vector output
def age(obs,geo):
""" Ageostrophic wind
<div class=jython>
AGE ( S ) = [ u (OBS) - u (GEO(S)), v (OBS) - v (GEO(S)) ]
</div>
"""
return sub(obs,geo)
def circv(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CIRC", int(D))
def cresv(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CRES", int(D))
def dvdx(V):
""" Partial x derivative of a vector
<div class=jython>
DVDX ( V ) = [ DDX (u), DDX (v) ]
</div>
"""
return vecr(ddx(ur(V)), ddx(vr(V)))
def dvdy(V):
""" Partial x derivative of a vector
<div class=jython>
DVDY ( V ) = [ DDY (u), DDY (v) ]
</div>
"""
return vecr(ddy(ur(V)), ddy(vr(V)))
def frnt(S,V):
""" Frontogenesis function from theta and the wind
<div class=jython>
FRNT ( THTA, V ) = 1/2 * MAG ( GRAD (THTA) ) *
( DEF * COS (2 * BETA) - DIV ) <p>
Where: BETA = ASIN ( (-DDX (THTA) * COS (PSI) <br>
- DDY (THTA) * SIN (PSI))/ <br>
MAG ( GRAD (THTA) ) ) <br>
PSI = 1/2 ATAN2 ( SHR / STR ) <br>
</div>
"""
shear = shr(V)
strch = strd(V)
psi = .5*atn2(shear,strch)
dxt = ddx(S)
dyt = ddy(S)
cosd = cos(psi)
sind = sin(psi)
gradt = grad(S)
mgradt = mag(gradt)
a = -cosd*dxt-sind*dyt
beta = asin(a/mgradt)
frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V))
return frnto
def geo(z):
""" geostrophic wind from height
<div class=jython>
GEO ( S ) = [ - DDY (S) * const / CORL, DDX (S) * const / CORL ]
</div>
"""
return DerivedGridFactory.createGeostrophicWindVector(z)
def grad(S):
""" Gradient of a scalar
<div class=jython>
GRAD ( S ) = [ DDX ( S ), DDY ( S ) ]
</div>
"""
return vecr(ddx(S),ddy(S))
def gwfv(V, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return gwfs(V, N)
def inad(V1,V2):
""" Inertial advective wind
<div class=jython>
INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ),
DOT ( V1, GRAD (v2) ) ]
</div>
"""
return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2))))
def qvec(S,V):
""" Q-vector at a level ( K / m / s )
<div class=jython>
QVEC ( S, V ) = [ - ( DOT ( DVDX (V), GRAD (S) ) ),
- ( DOT ( DVDY (V), GRAD (S) ) ) ]
where S can be any thermal paramenter, usually THTA.
</div>
"""
grads = grad(S)
qvecu = newName(-dot(dvdx(V),grads),"qvecu")
qvecv = newName(-dot(dvdy(V),grads),"qvecv")
return vecr(qvecu,qvecv)
def qvcl(THTA,V):
""" Q-vector ( K / m / s )
<div class=jython>
QVCL ( THTA, V ) = ( 1/( D (THTA) / DP ) ) *
[ ( DOT ( DVDX (V), GRAD (THTA) ) ),
( DOT ( DVDY (V), GRAD (THTA) ) ) ]
</div>
"""
dtdp = GridMath.partial(THTA,2)
gradt = grad(THTA)
qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),"qvecudp")
qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),"qvecvdp")
return vecr(qvecudp,qvecvdp)
def rectv(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "RECT", int(D))
def sm5v(V):
""" Smooth a scalar grid using a 5-point smoother (see sm5s)
"""
return sm5s(V)
def sm9v(V):
""" Smooth a scalar grid using a 9-point smoother (see sm9s)
"""
return sm9s(V)
def thrm(S, level1, level2, unit=None):
""" Thermal wind
<div class=jython>
THRM ( S ) = [ u (GEO(S)) (level1) - u (GEO(S)) (level2),
v (GEO(S)) (level1) - v (GEO(S)) (level2) ]
</div>
"""
return vldf(geo(S),level1,level2, unit)
def vadd(V1,V2):
""" add the components of 2 vectors
<div class=jython>
VADD (V1, V2) = [ u1+u2, v1+v2 ]
</div>
"""
return add(V1,V2)
def vecn(S1,S2):
""" Make a true north vector from two components
<div class=jython>
VECN ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return makeTrueVector(S1,S2)
def vecr(S1,S2):
""" Make a vector from two components
<div class=jython>
VECR ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return makeVector(S1,S2)
def vlav(V,level1,level2, unit=None):
""" calculate the vector layer average
<div class=jython>
VLDF(V) = [(u(level1) - u(level2))/2,
(v(level1) - v(level2))/2]
</div>
"""
return layerAverage(V, level1, level2, unit)
def vldf(V,level1,level2, unit=None):
""" calculate the vector layer difference
<div class=jython>
VLDF(V) = [u(level1) - u(level2),
v(level1) - v(level2)]
</div>
"""
return layerDiff(V,level1,level2, unit)
def vmul(V1,V2):
""" Multiply the components of 2 vectors
<div class=jython>
VMUL (V1, V2) = [ u1*u2, v1*v2 ]
</div>
"""
return mul(V1,V2)
def vquo(V1,V2):
""" Divide the components of 2 vectors
<div class=jython>
VQUO (V1, V2) = [ u1/u2, v1/v2 ]
</div>
"""
return quo(V1,V2)
def vsub(V1,V2):
""" subtract the components of 2 vectors
<div class=jython>
VSUB (V1, V2) = [ u1-u2, v1-v2 ]
</div>
"""
return sub(V1,V2)
def LPIndex(u, v, z, t, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52
</div>
"""
Z = windShear(u, v, z, top, bottom, unit)*7.268
uwind = getSliceAtLevel(u, top)
vwind = getSliceAtLevel(v, top)
temp = newUnit(getSliceAtLevel(t, top), "temperature", "celsius")
HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718
HU = (ddx(vwind) + ddy(uwind))*0.318
L = add(noUnit(Z), add(noUnit(HU), noUnit(HT)))
L = (L - 2.520)*(-0.59)
P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,"exp"))
LP = setLevel(P ,top, unit)
return LP
def EllrodIndex(u, v, z, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
EI = VWS X ( DEF + DIV)
</div>
"""
VWS = windShear(u, v, z, top, bottom, unit)*100.0
#
uwind = getSliceAtLevel(u, top)
vwind = getSliceAtLevel(v, top)
DIV = (ddx(uwind) + ddy(vwind))* (-1.0)
#
DSH = ddx(vwind) + ddy(uwind)
DST = ddx(uwind) - ddy(vwind)
DEF = sqrt(DSH * DSH + DST * DST)
EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV)))
return setLevel(EI, top, unit)
| """
This is the doc for the Grid Diagnostics module. These functions
are based on the grid diagnostics from the GEneral Meteorological
PAcKage (GEMPAK). Note that the names are case sensitive and some
are named slightly different from GEMPAK functions to avoid conflicts
with Jython built-ins (e.g. str).
<P>
In the following operators, scalar operands are named S<sub>n</sub> and
vector operands are named V<sub>n</sub>. Lowercase u and v refer to the
grid relative components of a vector.
"""
def gravity():
""" Gravity constant """
return DerivedGridFactory.GRAVITY
def atn2(S1, S2, WA=0):
""" Wrapper for atan2 built-in
<div class=jython>
ATN2 (S1, S2) = ATAN ( S1 / S2 )<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.atan2(S1, S2, WA)
def add(S1, S2, WA=0):
""" Addition
<div class=jython>
ADD (S1, S2) = S1 + S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.add(S1, S2, WA)
def mul(S1, S2, WA=0):
""" Multiply
<div class=jython>
MUL (S1, S2) = S1 * S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.multiply(S1, S2, WA)
def quo(S1, S2, WA=0):
""" Divide
<div class=jython>
QUO (S1, S2) = S1 / S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.divide(S1, S2, WA)
def sub(S1, S2, WA=0):
""" Subtract
<div class=jython>
SUB (S1, S2) = S1 - S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.subtract(S1, S2, WA)
def adv(S, V):
""" Horizontal Advection, negative by convention
<div class=jython>
ADV ( S, V ) = - ( u * DDX (S) + v * DDY (S) )
</div>
"""
return -add(mul(ur(V), ddx(S)), mul(vr(V), ddy(S)))
def avg(S1, S2):
""" Average of 2 scalars
<div class=jython>
AVG (S1, S2) = ( S1 + S2 ) / 2
</div>
"""
return add(S1, S2) / 2
def avor(V):
""" Absolute Vorticity
<div class=jython>
AVOR ( V ) = VOR ( V ) + CORL(V)
</div>
"""
relv = vor(V)
return add(relv, corl(relv))
def circs(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'CIRC', int(D))
def corl(S):
""" Coriolis Parameter for all points in a grid
<div class=jython>
CORL = TWO_OMEGA*sin(latr)
</div>
"""
return DerivedGridFactory.createCoriolisGrid(S)
def cress(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'CRES', int(D))
def cros(V1, V2):
""" Vector cross product magnitude
<div class=jython>
CROS ( V1, V2 ) = u1 * v2 - u2 * v1
</div>
"""
return sub(mul(ur(V1), vr(V2)), mul(ur(V2), vr(V1)))
def ddx(S):
""" Take the derivative with respect to the domain's X coordinate
"""
return GridMath.ddx(S)
def ddy(S):
""" Take the derivative with respect to the domain's Y coordinate
"""
return GridMath.ddy(S)
def defr(V):
""" Total deformation
<div class=jython>
DEF ( V ) = ( STRD (V) ** 2 + SHR (V) ** 2 ) ** .5
</div>
"""
return mag(strd(V), shr(V))
def div(V):
""" Horizontal Divergence
<div class=jython>
DIV ( V ) = DDX ( u ) + DDY ( v )
</div>
"""
return add(ddx(ur(V)), ddy(vr(V)))
def dirn(V):
""" North relative direction of a vector
<div class=jython>
DIRN ( V ) = DIRR ( un(v), vn(v) )
</div>
"""
return dirr(DerivedGridFactory.createTrueFlowVector(V))
def dirr(V):
""" Grid relative direction of a vector
"""
return DerivedGridFactory.createVectorDirection(V)
def dot(V1, V2):
""" Vector dot product
<div class=jython>
DOT ( V1, V2 ) = u1 * u2 + v1 * v2
</div>
"""
product = mul(V1, V2)
return add(ur(product), vr(product))
def gwfs(S, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return GridUtil.smooth(S, 'GWFS', int(N))
def jcbn(S1, S2):
""" Jacobian Determinant
<div class=jython>
JCBN ( S1, S2 ) = DDX (S1) * DDY (S2) - DDY (S1) * DDX (S2)
</div>
"""
return sub(mul(ddx(S1), ddy(S2)), mul(ddy(S1), ddx(S2)))
def latr(S):
""" Latitudue all points in a grid
"""
return DerivedGridFactory.createLatitudeGrid(S)
def lap(S):
""" Laplacian operator
<div class=jython>
LAP ( S ) = DIV ( GRAD (S) )
</div>
"""
grads = grad(S)
return div(grads)
def lav(S, level1=None, level2=None, unit=None):
""" Layer Average of a multi layer grid
<div class=jython>
LAV ( S ) = ( S (level1) + S (level2) ) / 2.
</div>
"""
if level1 == None:
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE)
else:
return layer_average(S, level1, level2, unit)
def ldf(S, level1, level2, unit=None):
""" Layer Difference
<div class=jython>
LDF ( S ) = S (level1) - S (level2)
</div>
"""
return layer_diff(S, level1, level2, unit)
def mag(*a):
""" Magnitude of a vector
"""
if len(a) == 1:
return DerivedGridFactory.createVectorMagnitude(a[0])
else:
return DerivedGridFactory.createVectorMagnitude(a[0], a[1])
def mixr(temp, rh):
""" Mixing Ratio from Temperature, RH (requires pressure domain)
"""
return DerivedGridFactory.createMixingRatio(temp, rh)
def relh(temp, mixr):
""" Create Relative Humidity from Temperature, mixing ratio (requires pressure domain)
"""
return DerivedGridFactory.createRelativeHumidity(temp, mixr)
def pvor(S, V):
""" Potetial Vorticity (usually from theta and wind)
"""
return DerivedGridFactory.createPotentialVorticity(S, V)
def rects(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'RECT', int(D))
def savg(S):
""" Average over whole grid
<div class=jython>
SAVG ( S ) = average of all non-missing grid point values
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def savs(S):
""" Average over grid subset
<div class=jython>
SAVS ( S ) = average of all non-missing grid point values in the subset
area
</div>
"""
return savg(S)
def sdiv(S, V):
""" Horizontal Flux Divergence
<div class=jython>
SDIV ( S, V ) = S * DIV ( V ) + DOT ( V, GRAD ( S ) )
</div>
"""
return add(mul(S, div(V)), dot(V, grad(S)))
def shr(V):
""" Shear Deformation
<div class=jython>
SHR ( V ) = DDX ( v ) + DDY ( u )
</div>
"""
return add(ddx(vr(V)), ddy(ur(V)))
def sm5s(S):
""" Smooth a scalar grid using a 5-point smoother
<div class=jython>
SM5S ( S ) = .5 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
</div>
"""
return GridUtil.smooth(S, 'SM5S')
def sm9s(S):
""" Smooth a scalar grid using a 9-point smoother
<div class=jython>
SM9S ( S ) = .25 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
+ .0625 * ( S (i+1,j+1) +
S (i+1,j-1) +
S (i-1,j+1) +
S (i-1,j-1) )
</div>
"""
return GridUtil.smooth(S, 'SM9S')
def strd(V):
""" Stretching Deformation
<div class=jython>
STRD ( V ) = DDX ( u ) - DDY ( v )
</div>
"""
return sub(ddx(ur(V)), ddy(vr(V)))
def thta(temp):
""" Potential Temperature from Temperature (requires pressure domain)
"""
return DerivedGridFactory.createPotentialTemperature(temp)
def thte(temp, rh):
""" Equivalent Potential Temperature from Temperature and Relative
humidity (requires pressure domain)
"""
return DerivedGridFactory.createEquivalentPotentialTemperature(temp, rh)
def un(V):
""" North relative u component
"""
return ur(DerivedGridFactory.createTrueFlowVector(V))
def ur(V):
""" Grid relative u component
"""
return DerivedGridFactory.getUComponent(V)
def vn(V):
""" North relative v component
"""
return vr(DerivedGridFactory.createTrueFlowVector(V))
def vor(V):
""" Relative Vorticity
<div class=jython>
VOR ( V ) = DDX ( v ) - DDY ( u )
</div>
"""
return sub(ddx(vr(V)), ddy(ur(V)))
def vr(V):
""" Grid relative v component
"""
return DerivedGridFactory.getVComponent(V)
def xav(S):
""" Average along a grid row
<div class=jython>
XAV (S) = ( S (X1) + S (X2) + ... + S (KXD) ) / KNT
KXD = number of points in row
KNT = number of non-missing points in row
XAV for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X)
def xsum(S):
""" Sum along a grid row
<div class=jython>
XSUM (S) = ( S (X1) + S (X2) + ... + S (KXD) )
KXD = number of points in row
XSUM for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X)
def yav(S):
""" Average along a grid column
<div class=jython>
YAV (S) = ( S (Y1) + S (Y2) + ... + S (KYD) ) / KNT
KYD = number of points in column
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y)
def ysum(S):
""" Sum along a grid column
<div class=jython>
YSUM (S) = ( S (Y1) + S (Y2) + ... + S (KYD) )
KYD = number of points in row
YSUM for a column is stored at every point in that column.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y)
def zav(S):
""" Average across the levels of a grid at all points
<div class=jython>
ZAV (S) = ( S (Z1) + S (Z2) + ... + S (KZD) ) / KNT
KZD = number of levels
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def zsum(S):
""" Sum across the levels of a grid at all points
<div class=jython>
ZSUM (S) = ( S (Z1) + S (Z2) + ... + S (KZD) )
KZD = number of levels
ZSUM for a vertical column is stored at every point
</div>
"""
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM)
def wshr(V, Z, top, bottom):
""" Magnitude of the vertical wind shear in a layer
<div class=jython>
WSHR ( V ) = MAG [ VLDF (V) ] / LDF (Z)
</div>
"""
dv = mag(vldf(V, top, bottom))
dz = ldf(Z, top, bottom)
return quo(dv, dz)
def age(obs, geo):
""" Ageostrophic wind
<div class=jython>
AGE ( S ) = [ u (OBS) - u (GEO(S)), v (OBS) - v (GEO(S)) ]
</div>
"""
return sub(obs, geo)
def circv(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'CIRC', int(D))
def cresv(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'CRES', int(D))
def dvdx(V):
""" Partial x derivative of a vector
<div class=jython>
DVDX ( V ) = [ DDX (u), DDX (v) ]
</div>
"""
return vecr(ddx(ur(V)), ddx(vr(V)))
def dvdy(V):
""" Partial x derivative of a vector
<div class=jython>
DVDY ( V ) = [ DDY (u), DDY (v) ]
</div>
"""
return vecr(ddy(ur(V)), ddy(vr(V)))
def frnt(S, V):
""" Frontogenesis function from theta and the wind
<div class=jython>
FRNT ( THTA, V ) = 1/2 * MAG ( GRAD (THTA) ) *
( DEF * COS (2 * BETA) - DIV ) <p>
Where: BETA = ASIN ( (-DDX (THTA) * COS (PSI) <br>
- DDY (THTA) * SIN (PSI))/ <br>
MAG ( GRAD (THTA) ) ) <br>
PSI = 1/2 ATAN2 ( SHR / STR ) <br>
</div>
"""
shear = shr(V)
strch = strd(V)
psi = 0.5 * atn2(shear, strch)
dxt = ddx(S)
dyt = ddy(S)
cosd = cos(psi)
sind = sin(psi)
gradt = grad(S)
mgradt = mag(gradt)
a = -cosd * dxt - sind * dyt
beta = asin(a / mgradt)
frnto = 0.5 * mgradt * (defr(V) * cos(2 * beta) - div(V))
return frnto
def geo(z):
""" geostrophic wind from height
<div class=jython>
GEO ( S ) = [ - DDY (S) * const / CORL, DDX (S) * const / CORL ]
</div>
"""
return DerivedGridFactory.createGeostrophicWindVector(z)
def grad(S):
""" Gradient of a scalar
<div class=jython>
GRAD ( S ) = [ DDX ( S ), DDY ( S ) ]
</div>
"""
return vecr(ddx(S), ddy(S))
def gwfv(V, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return gwfs(V, N)
def inad(V1, V2):
""" Inertial advective wind
<div class=jython>
INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ),
DOT ( V1, GRAD (v2) ) ]
</div>
"""
return vecr(dot(V1, grad(ur(V2))), dot(V1, grad(vr(V2))))
def qvec(S, V):
""" Q-vector at a level ( K / m / s )
<div class=jython>
QVEC ( S, V ) = [ - ( DOT ( DVDX (V), GRAD (S) ) ),
- ( DOT ( DVDY (V), GRAD (S) ) ) ]
where S can be any thermal paramenter, usually THTA.
</div>
"""
grads = grad(S)
qvecu = new_name(-dot(dvdx(V), grads), 'qvecu')
qvecv = new_name(-dot(dvdy(V), grads), 'qvecv')
return vecr(qvecu, qvecv)
def qvcl(THTA, V):
""" Q-vector ( K / m / s )
<div class=jython>
QVCL ( THTA, V ) = ( 1/( D (THTA) / DP ) ) *
[ ( DOT ( DVDX (V), GRAD (THTA) ) ),
( DOT ( DVDY (V), GRAD (THTA) ) ) ]
</div>
"""
dtdp = GridMath.partial(THTA, 2)
gradt = grad(THTA)
qvecudp = new_name(quo(dot(dvdx(V), gradt), dtdp), 'qvecudp')
qvecvdp = new_name(quo(dot(dvdy(V), gradt), dtdp), 'qvecvdp')
return vecr(qvecudp, qvecvdp)
def rectv(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, 'RECT', int(D))
def sm5v(V):
""" Smooth a scalar grid using a 5-point smoother (see sm5s)
"""
return sm5s(V)
def sm9v(V):
""" Smooth a scalar grid using a 9-point smoother (see sm9s)
"""
return sm9s(V)
def thrm(S, level1, level2, unit=None):
""" Thermal wind
<div class=jython>
THRM ( S ) = [ u (GEO(S)) (level1) - u (GEO(S)) (level2),
v (GEO(S)) (level1) - v (GEO(S)) (level2) ]
</div>
"""
return vldf(geo(S), level1, level2, unit)
def vadd(V1, V2):
""" add the components of 2 vectors
<div class=jython>
VADD (V1, V2) = [ u1+u2, v1+v2 ]
</div>
"""
return add(V1, V2)
def vecn(S1, S2):
""" Make a true north vector from two components
<div class=jython>
VECN ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return make_true_vector(S1, S2)
def vecr(S1, S2):
""" Make a vector from two components
<div class=jython>
VECR ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return make_vector(S1, S2)
def vlav(V, level1, level2, unit=None):
""" calculate the vector layer average
<div class=jython>
VLDF(V) = [(u(level1) - u(level2))/2,
(v(level1) - v(level2))/2]
</div>
"""
return layer_average(V, level1, level2, unit)
def vldf(V, level1, level2, unit=None):
""" calculate the vector layer difference
<div class=jython>
VLDF(V) = [u(level1) - u(level2),
v(level1) - v(level2)]
</div>
"""
return layer_diff(V, level1, level2, unit)
def vmul(V1, V2):
""" Multiply the components of 2 vectors
<div class=jython>
VMUL (V1, V2) = [ u1*u2, v1*v2 ]
</div>
"""
return mul(V1, V2)
def vquo(V1, V2):
""" Divide the components of 2 vectors
<div class=jython>
VQUO (V1, V2) = [ u1/u2, v1/v2 ]
</div>
"""
return quo(V1, V2)
def vsub(V1, V2):
""" subtract the components of 2 vectors
<div class=jython>
VSUB (V1, V2) = [ u1-u2, v1-v2 ]
</div>
"""
return sub(V1, V2)
def lp_index(u, v, z, t, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52
</div>
"""
z = wind_shear(u, v, z, top, bottom, unit) * 7.268
uwind = get_slice_at_level(u, top)
vwind = get_slice_at_level(v, top)
temp = new_unit(get_slice_at_level(t, top), 'temperature', 'celsius')
ht = sqrt(ddx(temp) * ddx(temp) + ddy(temp) * ddy(temp)) * 0.718
hu = (ddx(vwind) + ddy(uwind)) * 0.318
l = add(no_unit(Z), add(no_unit(HU), no_unit(HT)))
l = (L - 2.52) * -0.59
p = 1.0 / (1.0 + GridMath.applyFunctionOverGridsExt(L, 'exp'))
lp = set_level(P, top, unit)
return LP
def ellrod_index(u, v, z, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
EI = VWS X ( DEF + DIV)
</div>
"""
vws = wind_shear(u, v, z, top, bottom, unit) * 100.0
uwind = get_slice_at_level(u, top)
vwind = get_slice_at_level(v, top)
div = (ddx(uwind) + ddy(vwind)) * -1.0
dsh = ddx(vwind) + ddy(uwind)
dst = ddx(uwind) - ddy(vwind)
def = sqrt(DSH * DSH + DST * DST)
ei = mul(no_unit(VWS), add(no_unit(DEF), no_unit(DIV)))
return set_level(EI, top, unit) |
# 2019 advent day 3
MOVES = {
'R': (lambda x: (x[0], x[1] + 1)),
'L': (lambda x: (x[0], x[1] - 1)),
'U': (lambda x: (x[0] + 1, x[1])),
'D': (lambda x: (x[0] - 1, x[1])),
}
def build_route(directions: list) -> list:
current_location = (0, 0)
route = []
for d in directions:
direction, amount = d[0], int(d[1:])
for _ in range(amount):
current_location = MOVES[direction](current_location)
route.append(current_location)
return route
def find_intersections(r1: list, r2: list) -> set:
return set(r1).intersection(set(r2))
def find_shortest_manhattan_distance(points: set) -> int:
return min((abs(p[0]) + abs(p[1])) for p in points)
#R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'
#R2 = 'U62,R66,U55,R34,D71,R55,D58,R83'
#R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'
#R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'
def main():
#route1 = build_route(R1.split(','))
#route2 = build_route(R2.split(','))
with open('day3input.txt') as f:
line1, line2 = f.readlines()
route1 = build_route(line1.strip().split(','))
route2 = build_route(line2.strip().split(','))
print(find_shortest_manhattan_distance(find_intersections(route1, route2)))
if __name__ == "__main__":
main()
| moves = {'R': lambda x: (x[0], x[1] + 1), 'L': lambda x: (x[0], x[1] - 1), 'U': lambda x: (x[0] + 1, x[1]), 'D': lambda x: (x[0] - 1, x[1])}
def build_route(directions: list) -> list:
current_location = (0, 0)
route = []
for d in directions:
(direction, amount) = (d[0], int(d[1:]))
for _ in range(amount):
current_location = MOVES[direction](current_location)
route.append(current_location)
return route
def find_intersections(r1: list, r2: list) -> set:
return set(r1).intersection(set(r2))
def find_shortest_manhattan_distance(points: set) -> int:
return min((abs(p[0]) + abs(p[1]) for p in points))
def main():
with open('day3input.txt') as f:
(line1, line2) = f.readlines()
route1 = build_route(line1.strip().split(','))
route2 = build_route(line2.strip().split(','))
print(find_shortest_manhattan_distance(find_intersections(route1, route2)))
if __name__ == '__main__':
main() |
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[0][0]
elif i == 0:
dp[i][j] = grid[i][j] + dp[i][j - 1]
elif j == 0:
dp[i][j] = grid[i][j] + dp[i - 1][j]
else:
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m - 1][n - 1]
| class Solution(object):
def min_path_sum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
(m, n) = (len(grid), len(grid[0]))
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[0][0]
elif i == 0:
dp[i][j] = grid[i][j] + dp[i][j - 1]
elif j == 0:
dp[i][j] = grid[i][j] + dp[i - 1][j]
else:
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m - 1][n - 1] |
budget = float(input())
nights = int(input())
price_night = float(input())
percent_extra = int(input())
if nights > 7:
price_night = price_night - (price_night * 0.05)
sum = nights * price_night
total_sum = sum + (budget * percent_extra / 100)
if total_sum <= budget:
print(f"Ivanovi will be left with {(budget - total_sum):.2f} leva after vacation.")
else:
print(f"{(total_sum - budget):.2f} leva needed.") | budget = float(input())
nights = int(input())
price_night = float(input())
percent_extra = int(input())
if nights > 7:
price_night = price_night - price_night * 0.05
sum = nights * price_night
total_sum = sum + budget * percent_extra / 100
if total_sum <= budget:
print(f'Ivanovi will be left with {budget - total_sum:.2f} leva after vacation.')
else:
print(f'{total_sum - budget:.2f} leva needed.') |
class Skidoo(object):
''' a mapping which claims to contain all keys, each with a value
of 23; item setting and deletion are no-ops; you can also call
an instance with arbitrary positional args, result is 23. '''
__metaclass__ = MetaInterfaceChecker
__implements__ = IMinimalMapping, ICallable
def __getitem__(self, key): return 23
def __setitem__(self, key, value): pass
def __delitem__(self, key): pass
def __contains__(self, key): return True
def __call__(self, *args): return 23
sk = Skidoo()
| class Skidoo(object):
""" a mapping which claims to contain all keys, each with a value
of 23; item setting and deletion are no-ops; you can also call
an instance with arbitrary positional args, result is 23. """
__metaclass__ = MetaInterfaceChecker
__implements__ = (IMinimalMapping, ICallable)
def __getitem__(self, key):
return 23
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
def __contains__(self, key):
return True
def __call__(self, *args):
return 23
sk = skidoo() |
#!/usr/bin/env python
# coding: UTF-8
#
# @package Actor
# @author Ariadne Pinheiro
# @date 26/08/2020
#
# Actor class, which is the base class for Disease objects.
#
##
class Actor:
# Holds the value of the next "free" id.
__ID = 0
##
# Construct a new Actor object.
# - Sets the initial values of its member variables.
# - Sets the unique ID for the object and initializes the reference to the World
# object to which this Actor object belongs to null.
# - The ID of the first Actor object is 0.
# - The ID gets incremented by one each time a new Actor object is created.
# - Sets the iteration counter to zero and initialize the location of the
# object to cell (0,0).
#
def __init__(self):
# X coordinate of this actor.
self.__locX = 0
# Y coordinate of this actor.
self.__locY = 0
# World this actor belongs to.
self.__world = None
# Unique identifier for this actor.
self.__actorID = Actor.__ID
Actor.__ID += 1
# Iteration counter.
self.__itCounter = 0
##
# Used for testing
# @return ActorID
#
def getID(self):
return self.__actorID
##
# Used for testing
# @return number of iterations
#
def Iteration(self):
return self.__itCounter
##
# Prints on screen in the format "Iteration <ID>: Actor <Actor ID>".
#
# The @f$<ID>@f$ is replaced by the current iteration number. @f$<Actor ID>@f$ is
# replaced by the unique ID of the Actor object that performs the act(self)
# method.
#
# For instance, the actor with ID 1 shows the following result on
# the output screen after its act(self) method has been called twice.
# <PRE>
# Iteration 0: Actor 1
# Iteration 1: Actor 1
# </PRE>
#
def act(self):
print("Iteration {}: Actor {}".format(self.__itCounter, self.__actorID))
self.__itCounter += 1
##
# Sets the cell coordinates of this object.
#
# @param x the column.
# @param y the row.
#
# @throws ValueError when x < 0 or x >= world width,
# @throws ValueError when y < 0 or y >= world height,
# @throws RuntimeError when the world is null.
#
def setLocation(self, x, y):
if self.__world is None:
raise RuntimeError
if (0 <= x < self.__world.getWidth()) and (0 <= y < self.__world.getHeight()):
self.__locX = x
self.__locY = y
else:
raise ValueError
##
# Sets the world this actor is into.
#
# @param world Reference to the World object this Actor object is added.
# @throws RuntimeError when world is null.
#
def addedToWorld(self, world):
if world is None:
raise RuntimeError
self.__world = world
##
# Gets the world this object in into.
#
# @return the world this object belongs to
#
def getWorld(self):
return self.__world
##
# Gets the X coordinate of the cell this actor object is into.
#
# @return the x coordinate of this Actor object.
#
def getX(self):
return self.__locX
##
# Gets the Y coordinate of the cell this actor object is into.
#
# @return the y coordinate of this Actor object.
#
def getY(self):
return self.__locY
##
# Return a string with this actor ID and position.
#
def __str__(self):
try:
st = "ID = %d "u'\u2192 '.encode('utf-8') % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
except TypeError:
st = "ID = %d "u'\u2192 ' % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
return st
| class Actor:
__id = 0
def __init__(self):
self.__locX = 0
self.__locY = 0
self.__world = None
self.__actorID = Actor.__ID
Actor.__ID += 1
self.__itCounter = 0
def get_id(self):
return self.__actorID
def iteration(self):
return self.__itCounter
def act(self):
print('Iteration {}: Actor {}'.format(self.__itCounter, self.__actorID))
self.__itCounter += 1
def set_location(self, x, y):
if self.__world is None:
raise RuntimeError
if 0 <= x < self.__world.getWidth() and 0 <= y < self.__world.getHeight():
self.__locX = x
self.__locY = y
else:
raise ValueError
def added_to_world(self, world):
if world is None:
raise RuntimeError
self.__world = world
def get_world(self):
return self.__world
def get_x(self):
return self.__locX
def get_y(self):
return self.__locY
def __str__(self):
try:
st = 'ID = %d → '.encode('utf-8') % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
except TypeError:
st = 'ID = %d → ' % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
return st |
NAMES_SAML2_PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol"
NAMES_SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion"
NAMEID_FORMAT_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ"
| names_saml2_protocol = 'urn:oasis:names:tc:SAML:2.0:protocol'
names_saml2_assertion = 'urn:oasis:names:tc:SAML:2.0:assertion'
nameid_format_unspecified = 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified'
bindings_http_post = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'
date_time_format = '%Y-%m-%dT%H:%M:%SZ'
date_time_format_fractional = '%Y-%m-%dT%H:%M:%S.%fZ' |
class BaseSSO:
async def get_redirect_url(self):
"""Returns redirect url for facebook."""
raise NotImplementedError("Provider not implemented")
async def verify(self, request):
"""
Fetches user details using code received in the request.
:param request: starlette request object
"""
raise NotImplementedError("Provider not implemented")
| class Basesso:
async def get_redirect_url(self):
"""Returns redirect url for facebook."""
raise not_implemented_error('Provider not implemented')
async def verify(self, request):
"""
Fetches user details using code received in the request.
:param request: starlette request object
"""
raise not_implemented_error('Provider not implemented') |
def write(message: str):
print("org.allnix", message)
def read() -> str:
"""Returns a string"""
return "org.allnix"
| def write(message: str):
print('org.allnix', message)
def read() -> str:
"""Returns a string"""
return 'org.allnix' |
groupSize = input()
groups = list(map(int,input().split(' ')))
tmpArray1 = set()
tmpArray2 = set()
for i in groups:
if i in tmpArray1:
tmpArray2.discard(i)
else:
tmpArray1.add(i)
tmpArray2.add(i)
for i in tmpArray2:
print(i)
| group_size = input()
groups = list(map(int, input().split(' ')))
tmp_array1 = set()
tmp_array2 = set()
for i in groups:
if i in tmpArray1:
tmpArray2.discard(i)
else:
tmpArray1.add(i)
tmpArray2.add(i)
for i in tmpArray2:
print(i) |
#!/usr/bin/python3
#------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [(root, 0)]
result = []
while stack:
(node, level) = stack.pop(0)
if level == len(result):
result.append([])
result[level].append(node.val)
if node.left: stack.append((node.left, level+1))
if node.right: stack.append((node.right, level+1))
return result
#------------------------------------------------------------------------------
#Testing
| class Solution:
def level_order(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [(root, 0)]
result = []
while stack:
(node, level) = stack.pop(0)
if level == len(result):
result.append([])
result[level].append(node.val)
if node.left:
stack.append((node.left, level + 1))
if node.right:
stack.append((node.right, level + 1))
return result |
"""
Your module description
"""
"""
this is my second py code
for my second lecture
"""
#print ('hello world') # this is a single line commment
# this is my second line comment
#print(type("123."))
#print ("Hello World".upper())
#print("Hello World".lower())
#print("hello" + "world" + ".")
#print(2**3)
#my_str = "hello world"
#print(my_str)
#my_str = "Tom"
#print(my_str)
my_int = 2
my_float = 3.0
print(my_int + my_float) | """
Your module description
"""
'\nthis is my second py code\n\nfor my second lecture\n'
my_int = 2
my_float = 3.0
print(my_int + my_float) |
class Calculations:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
print(self.first + self.second)
def subtract(self):
print(self.first - self.second)
def multiply(self):
print(self.first * self.second)
def divide(self):
if second == 0:
print("Can't divide by zero")
else:
print(self.first / self.second)
def main():
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop = 1
calc=Calculations(a, b)
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division "))
print(chooseop)
if chooseop == 1:
calc.add()
break
elif chooseop == 2:
calc.subtract()
break
elif chooseop == 3:
calc.multiply()
break
elif chooseop == 4:
calc.divide()
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print("Invalid operation number")
if __name__ == "__main__":
main()
| class Calculations:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
print(self.first + self.second)
def subtract(self):
print(self.first - self.second)
def multiply(self):
print(self.first * self.second)
def divide(self):
if second == 0:
print("Can't divide by zero")
else:
print(self.first / self.second)
def main():
print('Calculator has started')
while True:
a = float(input('Enter first number '))
b = float(input('Enter second number '))
chooseop = 1
calc = calculations(a, b)
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division '))
print(chooseop)
if chooseop == 1:
calc.add()
break
elif chooseop == 2:
calc.subtract()
break
elif chooseop == 3:
calc.multiply()
break
elif chooseop == 4:
calc.divide()
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print('Invalid operation number')
if __name__ == '__main__':
main() |
n, k = map(int, input().split())
w = list(map(int, input().split()))
r = sum(map(lambda x: (x+k-1)//k, w))
print((r+1)//2)
| (n, k) = map(int, input().split())
w = list(map(int, input().split()))
r = sum(map(lambda x: (x + k - 1) // k, w))
print((r + 1) // 2) |
# -*- coding: utf-8 -*-
def main():
a = input()
# See:
# https://www.slideshare.net/chokudai/abc007
if a == 'a':
print('-1')
else:
print('a')
if __name__ == '__main__':
main()
| def main():
a = input()
if a == 'a':
print('-1')
else:
print('a')
if __name__ == '__main__':
main() |
class Constants(object):
LOGGER_CONF = "common/mapr_conf/logger.yml"
USERNAME = "mapr"
GROUPNAME = "mapr"
USERID = 5000
GROUPID = 5000
ADMIN_USERNAME = "custadmin"
ADMIN_GROUPNAME = "custadmin"
ADMIN_USERID = 7000
ADMIN_GROUPID = 7000
ADMIN_PASS = "mapr"
MYSQL_USER = "admin"
MYSQL_PASS = "mapr"
LDAPADMIN_USER = "admin"
LDAPADMIN_PASS = "mapr"
LDAPBIND_USER = "readonly"
LDAPBIND_PASS = "mapr"
EXAMPLE_LDAP_NAMESPACE = "hpe-ldap"
CSI_REPO = "quay.io/k8scsi"
KDF_REPO = "docker.io/maprtech" #registry.hub.docker.com/maprtech
KUBEFLOW_REPO = "gcr.io/mapr-252711/kf-ecp-5.3.0"
OPERATOR_REPO = "gcr.io/mapr-252711"
KUBELET_DIR = "/var/lib/kubelet"
ECP_KUBELET_DIR = "/var/lib/docker/kubelet"
LOCAL_PATH_PROVISIONER_REPO= ""
KFCTL_HSP_ISTIO_REPO = ""
BUSYBOX_REPO = ""
def enum(**named_values):
return type('Enum', (), named_values)
AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP')
# OPEN SSL
OPENSSL = '/usr/bin/openssl'
KEY_SIZE = 1024
DAYS = 3650
CA_CERT = 'ca.cert'
CA_KEY = 'ca.key'
# http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS
X509_EXTRA_ARGS = ()
OPENSSL_CONFIG_TEMPLATE = """
prompt = no
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
C = US
ST = CO
L = Fort Collins
O = HPE
OU = HCP
CN = %(service)s
emailAddress = support@hpe.com
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = %(service)s
DNS.2 = %(service)s.%(namespace)s
DNS.3 = %(service)s.%(namespace)s.svc
"""
| class Constants(object):
logger_conf = 'common/mapr_conf/logger.yml'
username = 'mapr'
groupname = 'mapr'
userid = 5000
groupid = 5000
admin_username = 'custadmin'
admin_groupname = 'custadmin'
admin_userid = 7000
admin_groupid = 7000
admin_pass = 'mapr'
mysql_user = 'admin'
mysql_pass = 'mapr'
ldapadmin_user = 'admin'
ldapadmin_pass = 'mapr'
ldapbind_user = 'readonly'
ldapbind_pass = 'mapr'
example_ldap_namespace = 'hpe-ldap'
csi_repo = 'quay.io/k8scsi'
kdf_repo = 'docker.io/maprtech'
kubeflow_repo = 'gcr.io/mapr-252711/kf-ecp-5.3.0'
operator_repo = 'gcr.io/mapr-252711'
kubelet_dir = '/var/lib/kubelet'
ecp_kubelet_dir = '/var/lib/docker/kubelet'
local_path_provisioner_repo = ''
kfctl_hsp_istio_repo = ''
busybox_repo = ''
def enum(**named_values):
return type('Enum', (), named_values)
auth_types = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP')
openssl = '/usr/bin/openssl'
key_size = 1024
days = 3650
ca_cert = 'ca.cert'
ca_key = 'ca.key'
x509_extra_args = ()
openssl_config_template = '\nprompt = no\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n\n[ req_distinguished_name ]\nC = US\nST = CO\nL = Fort Collins\nO = HPE\nOU = HCP\nCN = %(service)s\nemailAddress = support@hpe.com\n[ v3_req ]\n# Extensions to add to a certificate request\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n[ alt_names ]\nDNS.1 = %(service)s\nDNS.2 = %(service)s.%(namespace)s\nDNS.3 = %(service)s.%(namespace)s.svc\n' |
# input
N, M = map(int, input().split())
Ds = [*map(int, input().split())]
# compute
dp = [False] * (N+1)
for ni in range(N+1):
if ni == 0:
dp[ni] = True
for D in Ds:
if ni >= D:
dp[ni] = dp[ni] or dp[ni-D]
# output
print("Yes" if dp[-1] else "No")
| (n, m) = map(int, input().split())
ds = [*map(int, input().split())]
dp = [False] * (N + 1)
for ni in range(N + 1):
if ni == 0:
dp[ni] = True
for d in Ds:
if ni >= D:
dp[ni] = dp[ni] or dp[ni - D]
print('Yes' if dp[-1] else 'No') |
# sorting
n=int(input())
array=list(map(int,input().split()))
i=0
count=[]
counter=0
while i<len(array):
min=i
start=i+1
while(start<len(array)):
if array[start]<array[min]:
min=start
start+=1
if i!=min:
array[i],array[min]=array[min],array[i]
count.append(i)
count.append(min)
counter+=1
i+=1
print(counter)
for i in range(0,len(count)):
print(count[i],end=" ")
| n = int(input())
array = list(map(int, input().split()))
i = 0
count = []
counter = 0
while i < len(array):
min = i
start = i + 1
while start < len(array):
if array[start] < array[min]:
min = start
start += 1
if i != min:
(array[i], array[min]) = (array[min], array[i])
count.append(i)
count.append(min)
counter += 1
i += 1
print(counter)
for i in range(0, len(count)):
print(count[i], end=' ') |
class GeomCombinationSet(APIObject, IDisposable, IEnumerable):
"""
A set that contains GeomCombination objects.
GeomCombinationSet()
"""
def Clear(self):
"""
Clear(self: GeomCombinationSet)
Removes every item GeomCombination the set,rendering it empty.
"""
pass
def Contains(self, item):
"""
Contains(self: GeomCombinationSet,item: GeomCombination) -> bool
Tests for the existence of an GeomCombination within the set.
item: The element to be searched for.
Returns: The Contains method returns True if the GeomCombination is within the set,
otherwise False.
"""
pass
def Dispose(self):
""" Dispose(self: GeomCombinationSet,A_0: bool) """
pass
def Erase(self, item):
"""
Erase(self: GeomCombinationSet,item: GeomCombination) -> int
Removes a specified GeomCombination from the set.
item: The GeomCombination to be erased.
Returns: The number of GeomCombinations that were erased from the set.
"""
pass
def ForwardIterator(self):
"""
ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def GetEnumerator(self):
"""
GetEnumerator(self: GeomCombinationSet) -> IEnumerator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def Insert(self, item):
"""
Insert(self: GeomCombinationSet,item: GeomCombination) -> bool
Insert the specified element into the set.
item: The GeomCombination to be inserted into the set.
Returns: Returns whether the GeomCombination was inserted into the set.
"""
pass
def ReleaseManagedResources(self, *args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: GeomCombinationSet) """
pass
def ReverseIterator(self):
"""
ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a backward moving iterator to the set.
Returns: Returns a backward moving iterator to the set.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self, *args):
""" __iter__(self: IEnumerable) -> object """
pass
IsEmpty = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Test to see if the set is empty.
Get: IsEmpty(self: GeomCombinationSet) -> bool
"""
Size = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Returns the number of GeomCombinations that are in the set.
Get: Size(self: GeomCombinationSet) -> int
"""
| class Geomcombinationset(APIObject, IDisposable, IEnumerable):
"""
A set that contains GeomCombination objects.
GeomCombinationSet()
"""
def clear(self):
"""
Clear(self: GeomCombinationSet)
Removes every item GeomCombination the set,rendering it empty.
"""
pass
def contains(self, item):
"""
Contains(self: GeomCombinationSet,item: GeomCombination) -> bool
Tests for the existence of an GeomCombination within the set.
item: The element to be searched for.
Returns: The Contains method returns True if the GeomCombination is within the set,
otherwise False.
"""
pass
def dispose(self):
""" Dispose(self: GeomCombinationSet,A_0: bool) """
pass
def erase(self, item):
"""
Erase(self: GeomCombinationSet,item: GeomCombination) -> int
Removes a specified GeomCombination from the set.
item: The GeomCombination to be erased.
Returns: The number of GeomCombinations that were erased from the set.
"""
pass
def forward_iterator(self):
"""
ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def get_enumerator(self):
"""
GetEnumerator(self: GeomCombinationSet) -> IEnumerator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def insert(self, item):
"""
Insert(self: GeomCombinationSet,item: GeomCombination) -> bool
Insert the specified element into the set.
item: The GeomCombination to be inserted into the set.
Returns: Returns whether the GeomCombination was inserted into the set.
"""
pass
def release_managed_resources(self, *args):
""" ReleaseManagedResources(self: APIObject) """
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: GeomCombinationSet) """
pass
def reverse_iterator(self):
"""
ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a backward moving iterator to the set.
Returns: Returns a backward moving iterator to the set.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self, *args):
""" __iter__(self: IEnumerable) -> object """
pass
is_empty = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Test to see if the set is empty.\n\n\n\nGet: IsEmpty(self: GeomCombinationSet) -> bool\n\n\n\n'
size = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Returns the number of GeomCombinations that are in the set.\n\n\n\nGet: Size(self: GeomCombinationSet) -> int\n\n\n\n' |
#Basics
a = "hello"
a += " I'm a dog"
print(a)
print(len(a))
print(a[1:]) #Output: ello I'm a dog
print(a[:5]) #Output: hello(index 5 is not included)
print(a[2:5])#Output: llo(index 2 is included)
print(a[::2])#Step size
#string is immutable so you can't assign a[1]= b
x = a.upper()
print(x)
x = a.capitalize()
print(x)
x = a.split('e')
print(x)
x = a.split() #splits the string by space
print(x)
x = a.strip() #removes any whitespace from beginning or the end
print(x)
x = a.replace('l','xxx')
print(x)
x = "Insert another string here: {}".format('insert me!')
x = "Item One: {} Item Two: {}".format('dog', 'cat')
print(x)
x = "Item One: {m} Item Two: {m}".format(m='dog', n='cat')
print(x)
#command-line string input
print("Enter your name:")
x = input()
print("Hello: {}".format(x)) | a = 'hello'
a += " I'm a dog"
print(a)
print(len(a))
print(a[1:])
print(a[:5])
print(a[2:5])
print(a[::2])
x = a.upper()
print(x)
x = a.capitalize()
print(x)
x = a.split('e')
print(x)
x = a.split()
print(x)
x = a.strip()
print(x)
x = a.replace('l', 'xxx')
print(x)
x = 'Insert another string here: {}'.format('insert me!')
x = 'Item One: {} Item Two: {}'.format('dog', 'cat')
print(x)
x = 'Item One: {m} Item Two: {m}'.format(m='dog', n='cat')
print(x)
print('Enter your name:')
x = input()
print('Hello: {}'.format(x)) |
#Copyright (c) 2017 Andre Santos
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
###############################################################################
# Language Model
###############################################################################
class CodeEntity(object):
"""Base class for all programming entities.
All code objects have a file name, a line number, a column number,
a programming scope (e.g. the function or code block they belong to)
and a parent object that should have some variable or collection
holding this object.
"""
def __init__(self, scope, parent):
"""Base constructor for code objects.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
self.scope = scope
self.parent = parent
self.file = None
self.line = None
self.column = None
def walk_preorder(self):
"""Iterates the program tree starting from this object, going down."""
yield self
for child in self._children():
for descendant in child.walk_preorder():
yield descendant
def filter(self, cls, recursive=False):
"""Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree.
"""
source = self.walk_preorder if recursive else self._children
return [
codeobj
for codeobj in source()
if isinstance(codeobj, cls)
]
def _afterpass(self):
"""Finalizes the construction of a code entity."""
pass
def _validity_check(self):
"""Check whether this object is a valid construct."""
return True
def _children(self):
"""Yield all direct children of this object."""
# The default implementation has no children, and thus should return
# an empty iterator.
return iter(())
def _lookup_parent(self, cls):
"""Lookup a transitive parent object that is an instance
of a given class."""
codeobj = self.parent
while codeobj is not None and not isinstance(codeobj, cls):
codeobj = codeobj.parent
return codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return (' ' * indent) + self.__str__()
def ast_str(self, indent=0):
"""Return a minimal string to print a tree-like structure.
Kwargs:
indent (int): The number of indentation levels.
"""
line = self.line or 0
col = self.column or 0
name = type(self).__name__
spell = getattr(self, 'name', '[no spelling]')
result = ' ({})'.format(self.result) if hasattr(self, 'result') else ''
prefix = indent * '| '
return '{}[{}:{}] {}{}: {}'.format(prefix, line, col,
name, result, spell)
def __str__(self):
"""Return a string representation of this object."""
return self.__repr__()
def __repr__(self):
"""Return a string representation of this object."""
return '[unknown]'
class CodeStatementGroup(object):
"""This class is meant to provide common utility methods for
objects that group multiple program statements together
(e.g. functions, code blocks).
It is not meant to be instantiated directly, only used for
inheritance purposes.
It defines the length of a statement group, and provides methods
for integer-based indexing of program statements (as if using a list).
"""
def statement(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.body.statement(i)
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
try:
return self.statement(i + 1)
except IndexError as e:
return None
def __getitem__(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.statement(i)
def __len__(self):
"""Return the length of the statement group."""
return len(self.body)
# ----- Common Entities -------------------------------------------------------
class CodeVariable(CodeEntity):
"""This class represents a program variable.
A variable typically has a name, a type (`result`) and a value
(or `None` for variables without a value or when the value is unknown).
Additionally, a variable has an `id` which uniquely identifies it in
the program (useful to resolve references), a list of references to it
and a list of statements that write new values to the variable.
If the variable is a *member*/*field*/*attribute* of an object,
`member_of` should contain a reference to such object, instead of `None`.
"""
def __init__(self, scope, parent, id, name, result):
"""Constructor for variables.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this variable.
name (str): The name of the variable in the program.
result (str): The type of the variable in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.value = None
self.member_of = None
self.references = []
self.writes = []
@property
def is_definition(self):
return True
@property
def is_local(self):
"""Whether this is a local variable.
In general, a variable is *local* if its containing scope is a
statement (e.g. a block), or a function, given that the variable
is not one of the function's parameters.
"""
return (isinstance(self.scope, CodeStatement)
or (isinstance(self.scope, CodeFunction)
and self not in self.scope.parameters))
@property
def is_global(self):
"""Whether this is a global variable.
In general, a variable is *global* if it is declared directly under
the program's global scope or a namespace.
"""
return isinstance(self.scope, (CodeGlobalScope, CodeNamespace))
@property
def is_parameter(self):
"""Whether this is a function parameter."""
return (isinstance(self.scope, CodeFunction)
and self in self.scope.parameters)
@property
def is_member(self):
"""Whether this is a member/attribute of a class or object."""
return isinstance(self.scope, CodeClass)
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeEntity):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '{}{} {} = {}'.format(' ' * indent, self.result, self.name,
pretty_str(self.value))
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {} = ({})'.format(self.result, self.name, self.value)
class CodeFunction(CodeEntity, CodeStatementGroup):
"""This class represents a program function.
A function typically has a name, a return type (`result`), a list
of parameters and a body (a code block). It also has an unique `id`
that identifies it in the program and a list of references to it.
If a function is a method of some class, its `member_of` should be
set to the corresponding class.
"""
def __init__(self, scope, parent, id, name, result, definition=True):
"""Constructor for functions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this function.
name (str): The name of the function in the program.
result (str): The return type of the function in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.parameters = []
self.body = CodeBlock(self, self, explicit=True)
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a function definition or just a declaration."""
return self._definition is self
@property
def is_constructor(self):
"""Whether this function is a class constructor."""
return self.member_of is not None
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, (CodeStatement, CodeExpression))
self.body._add(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.parameters:
yield codeobj
for codeobj in self.body._children():
yield codeobj
def _afterpass(self):
"""Assign a function-local index to each child object and register
write operations to variables.
This should only be called after the object is fully built.
"""
if hasattr(self, '_fi'):
return
fi = 0
for codeobj in self.walk_preorder():
codeobj._fi = fi
fi += 1
if isinstance(codeobj, CodeOperator) and codeobj.is_assignment:
if codeobj.arguments and isinstance(codeobj.arguments[0],
CodeReference):
var = codeobj.arguments[0].reference
if isinstance(var, CodeVariable):
var.writes.append(codeobj)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
params = ', '.join(map(lambda p: p.result + ' ' + p.name,
self.parameters))
if self.is_constructor:
pretty = '{}{}({}):\n'.format(spaces, self.name, params)
else:
pretty = '{}{} {}({}):\n'.format(spaces, self.result,
self.name, params)
if self._definition is not self:
pretty += spaces + ' [declaration]'
else:
pretty += self.body.pretty_str(indent + 2)
return pretty
def __repr__(self):
"""Return a string representation of this object."""
params = ', '.join(map(str, self.parameters))
return '[{}] {}({})'.format(self.result, self.name, params)
class CodeClass(CodeEntity):
"""This class represents a program class for object-oriented languages.
A class typically has a name, an unique `id`, a list of
members (variables, functions), a list of superclasses, and a list of
references.
If a class is defined within another class (inner class), it should
have its `member_of` set to the corresponding class.
"""
def __init__(self, scope, parent, id_, name, definition=True):
"""Constructor for classes.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this class.
name (str): The name of the class in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id_
self.name = name
self.members = []
self.superclasses = []
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a definition or a declaration of the class."""
return self._definition is self
def _add(self, codeobj):
"""Add a child (function, variable, class) to this object."""
assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass))
self.members.append(codeobj)
codeobj.member_of = self
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.members:
yield codeobj
def _afterpass(self):
"""Assign the `member_of` of child members and call
their `_afterpass()`.
This should only be called after the object is fully built.
"""
for codeobj in self.members:
if not codeobj.is_definition:
if not codeobj._definition is None:
codeobj._definition.member_of = self
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'class ' + self.name
if self.superclasses:
superclasses = ', '.join(self.superclasses)
pretty += '(' + superclasses + ')'
pretty += ':\n'
if self.members:
pretty += '\n\n'.join(
c.pretty_str(indent + 2)
for c in self.members
)
else:
pretty += spaces + ' [declaration]'
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[class {}]'.format(self.name)
class CodeNamespace(CodeEntity):
"""This class represents a program namespace.
A namespace is a concept that is explicit in languages such as C++,
but less explicit in many others. In Python, the closest thing should
be a module. In Java, it may be the same as a class, or non-existent.
A namespace typically has a name and a list of children objects
(variables, functions or classes).
"""
def __init__(self, scope, parent, name):
"""Constructor for namespaces.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the namespace in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass,
CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}namespace {}:\n'.format(spaces, self.name)
pretty += '\n\n'.join(c.pretty_str(indent + 2) for c in self.children)
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[namespace {}]'.format(self.name)
class CodeGlobalScope(CodeEntity):
"""This class represents the global scope of a program.
The global scope is the root object of a program. If there are no
better candidates, it is the `scope` and `parent` of all other objects.
It is also the only object that does not have a `scope` or `parent`.
"""
def __init__(self):
"""Constructor for global scope objects."""
CodeEntity.__init__(self, None, None)
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass,
CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '\n\n'.join(
codeobj.pretty_str(indent=indent)
for codeobj in self.children
)
# ----- Expression Entities ---------------------------------------------------
class CodeExpression(CodeEntity):
"""Base class for expressions within a program.
Expressions can be of many types, including literal values,
operators, references and function calls. This class is meant
to be inherited from, and not instantiated directly.
An expression typically has a name (e.g. the name of the function
in a function call) and a type (`result`). Also, an expression should
indicate whether it is enclosed in parentheses.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for expressions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the expression in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.result = result
self.parenthesis = paren
@property
def function(self):
"""The function where this expression occurs."""
return self._lookup_parent(CodeFunction)
@property
def statement(self):
"""The statement where this expression occurs."""
return self._lookup_parent(CodeStatement)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return (' ' * indent) + '(' + self.name + ')'
return (' ' * indent) + self.name
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {}'.format(self.result, self.name)
class SomeValue(CodeExpression):
"""This class represents an unknown value for diverse primitive types."""
def __init__(self, result):
"""Constructor for unknown values."""
CodeExpression.__init__(self, None, None, result, result)
def _children(self):
"""Yield all the children of this object, that is no children."""
return iter(())
SomeValue.INTEGER = SomeValue("int")
SomeValue.FLOATING = SomeValue("float")
SomeValue.CHARACTER = SomeValue("char")
SomeValue.STRING = SomeValue("string")
SomeValue.BOOL = SomeValue("bool")
class CodeLiteral(CodeExpression):
"""Base class for literal types not present in Python.
This class is meant to represent a literal whose type is not numeric,
string or boolean, as bare Python literals are used for those.
A literal has a value (e.g. a list `[1, 2, 3]`) and a type (`result`),
and could be enclosed in parentheses. It does not have a name.
"""
def __init__(self, scope, parent, value, result, paren=False):
"""Constructor for literals.
As literals have no name, a constant string is used instead.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (CodeExpression|CodeExpression[]): This literal's value.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, 'literal', result, paren)
self.value = value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return '{}({})'.format(' ' * indent, pretty_str(self.value))
return pretty_str(self.value, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {!r}'.format(self.result, self.value)
CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue,
CodeLiteral, CodeExpression)
CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral)
class CodeNull(CodeLiteral):
"""This class represents an indefinite value.
Many programming languages have their own version of this concept:
Java has null references, C/C++ NULL pointers, Python None and so on.
"""
def __init__(self, scope, parent, paren=False):
"""Constructor for null literals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
paren (bool): Whether the null literal is enclosed in parentheses.
"""
CodeLiteral.__init__(self, scope, parent, None, 'null', paren)
def _children(self):
"""Yield all the children of this object, that is no children.
This class inherits from CodeLiteral just for consistency with the
class hierarchy. It should have no children, thus an empty iterator
is returned.
"""
return iter(())
class CodeCompositeLiteral(CodeLiteral):
"""This class represents a composite literal.
A composite literal is any type of literal whose value is compound,
rather than simple. An example present in many programming languages
are list literals, often constructed as `[1, 2, 3]`.
A composite literal has a sequence of values that compose it
(`values`), a type (`result`), and it should indicate whether it is
enclosed in parentheses.
"""
def __init__(self, scope, parent, result, value=(), paren=False):
"""Constructor for a compound literal.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (iterable): The initial value sequence in this composition.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
try:
value = list(value)
except TypeError as te:
raise AssertionError(str(te))
CodeLiteral.__init__(self, scope, parent, value, result, paren)
@property
def values(self):
return tuple(self.value)
def _add_value(self, child):
"""Add a value to the sequence in this composition."""
self.value.append(child)
def _children(self):
"""Yield all direct children of this object."""
for value in self.value:
if isinstance(value, CodeEntity):
yield value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
values = '{{{}}}'.format(', '.join(map(pretty_str, self.value)))
if self.parenthesis:
return '{}({})'.format(indent, values)
return '{}{}'.format(indent, values)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {{{}}}'.format(self.result,
', '.join(map(repr, self.value)))
class CodeReference(CodeExpression):
"""This class represents a reference expression (e.g. to a variable).
A reference typically has a name (of what it is referencing),
and a return type.
If the referenced entity is known, `reference` should be set.
If the reference is a field/attribute of an object, `field_of`
should be set to that object.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for references.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the reference in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the reference is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.field_of = None
self.reference = None
def _set_field(self, codeobj):
"""Set the object that contains the attribute this is a reference of."""
assert isinstance(codeobj, CodeExpression)
self.field_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.field_of:
yield self.field_of
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
name = ('{}.{}'.format(self.field_of.pretty_str(), self.name)
if self.field_of else self.name)
return pretty.format(spaces, name)
def __str__(self):
"""Return a string representation of this object."""
return '#' + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.field_of:
return '[{}] ({}).{}'.format(self.result, self.field_of, self.name)
return '[{}] #{}'.format(self.result, self.name)
class CodeOperator(CodeExpression):
"""This class represents an operator expression (e.g. `a + b`).
Operators can be unary or binary, and often return numbers
or booleans. Some languages also support ternary operators.
Do note that assignments are often considered expressions,
and, as such, assignment operators are included here.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
_UNARY_TOKENS = ("+", "-")
_BINARY_TOKENS = ("+", "-", "*", "/", "%", "<", ">", "<=", ">=",
"==", "!=", "&&", "||", "=")
def __init__(self, scope, parent, name, result, args=None, paren=False):
"""Constructor for operators.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the operator in the program.
result (str): The return type of the operator in the program.
Kwargs:
args (tuple): Initial tuple of arguments.
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.arguments = args or ()
@property
def is_unary(self):
"""Whether this is a unary operator."""
return len(self.arguments) == 1
@property
def is_binary(self):
"""Whether this is a binary operator."""
return len(self.arguments) == 2
@property
def is_ternary(self):
"""Whether this is a ternary operator."""
return len(self.arguments) == 3
@property
def is_assignment(self):
"""Whether this is an assignment operator."""
return self.name == "="
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
if self.is_unary:
operator = self.name + pretty_str(self.arguments[0])
else:
operator = '{} {} {}'.format(pretty_str(self.arguments[0]),
self.name,
pretty_str(self.arguments[1]))
return pretty.format(indent, operator)
def __repr__(self):
"""Return a string representation of this object."""
if self.is_unary:
return '[{}] {}({})'.format(self.result, self.name,
self.arguments[0])
if self.is_binary:
return '[{}] ({}){}({})'.format(self.result, self.arguments[0],
self.name, self.arguments[1])
return '[{}] {}'.format(self.result, self.name)
class CodeFunctionCall(CodeExpression):
"""This class represents a function call.
A function call typically has a name (of the called function),
a return type, a tuple of its arguments and a reference to the
called function.
If a call references a class method, its `method_of` should be
set to the object on which a method is being called.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for function calls.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the function in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.full_name = name
self.arguments = ()
self.method_of = None
self.reference = None
@property
def is_constructor(self):
"""Whether the called function is a constructor."""
return self.result == self.name
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _set_method(self, codeobj):
"""Set the object on which a method is called."""
assert isinstance(codeobj, CodeExpression)
self.method_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.method_of:
yield self.method_of
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
args = ', '.join(map(pretty_str, self.arguments))
if self.method_of:
call = '{}.{}({})'.format(self.method_of.pretty_str(),
self.name, args)
elif self.is_constructor:
call = 'new {}({})'.format(self.name, args)
else:
call = '{}({})'.format(self.name, args)
return pretty.format(indent, call)
def __repr__(self):
"""Return a string representation of this object."""
args = ', '.join(map(str, self.arguments))
if self.is_constructor:
return '[{}] new {}({})'.format(self.result, self.name, args)
if self.method_of:
return '[{}] {}.{}({})'.format(self.result, self.method_of.name,
self.name, args)
return '[{}] {}({})'.format(self.result, self.name, args)
class CodeDefaultArgument(CodeExpression):
"""This class represents a default argument.
Some languages, such as C++, allow function parameters to have
default values when not explicitly provided by the programmer.
This class represents such omitted arguments.
A default argument has only a return type.
"""
def __init__(self, scope, parent, result):
"""Constructor for default arguments.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
result (str): The return type of the argument in the program.
"""
CodeExpression.__init__(self, scope, parent, '(default)', result)
# ----- Statement Entities ----------------------------------------------------
class CodeStatement(CodeEntity):
"""Base class for program statements.
Programming languages often define diverse types of statements
(e.g. return statements, control flow, etc.).
This class provides common functionality for such statements.
In many languages, statements must be contained within a function.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
def __init__(self, scope, parent):
"""Constructor for statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeEntity.__init__(self, scope, parent)
self._si = -1
@property
def function(self):
"""The function where this statement appears in."""
return self._lookup_parent(CodeFunction)
class CodeJumpStatement(CodeStatement):
"""This class represents a jump statement (e.g. `return`, `break`).
A jump statement has a name. In some cases, it may also have an
associated value (e.g. `return 0`).
"""
def __init__(self, scope, parent, name):
"""Constructor for jump statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.value = None
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeExpression):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
if self.value is not None:
return '{}{} {}'.format(indent, self.name, pretty_str(self.value))
return indent + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.value is not None:
return '{} {}'.format(self.name, str(self.value))
return self.name
class CodeExpressionStatement(CodeStatement):
"""This class represents an expression statement. It is only a wrapper.
Many programming languages allow expressions to be statements
on their own. A common example is the assignment operator, which
can be a statement on its own, but also returns a value when
contained within a larger expression.
"""
def __init__(self, scope, parent, expression=None):
"""Constructor for expression statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
expression (CodeExpression): The expression of this statement.
"""
CodeStatement.__init__(self, scope, parent)
self.expression = expression
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.expression, CodeExpression):
yield self.expression
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return pretty_str(self.expression, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return repr(self.expression)
class CodeBlock(CodeStatement, CodeStatementGroup):
"""This class represents a code block (e.g. `{}` in C, C++, Java, etc.).
Blocks are little more than collections of statements, while being
considered a statement themselves.
Some languages allow blocks to be implicit in some contexts, e.g.
an `if` statement omitting curly braces in C, C++, Java, etc.
This model assumes that control flow branches and functions always
have a block as their body.
"""
def __init__(self, scope, parent, explicit=True):
"""Constructor for code blocks.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
explicit (bool): Whether the block is explicit in the code.
"""
CodeStatement.__init__(self, scope, parent)
self.body = []
self.explicit = explicit
def statement(self, i):
"""Return the *i*-th statement of this block."""
return self.body[i]
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, CodeStatement)
codeobj._si = len(self.body)
self.body.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.body:
return '\n'.join(stmt.pretty_str(indent) for stmt in self.body)
else:
return (' ' * indent) + '[empty]'
def __repr__(self):
"""Return a string representation of this object."""
return str(self.body)
class CodeDeclaration(CodeStatement):
"""This class represents a declaration statement.
Some languages, such as C, C++ or Java, consider this special
kind of statement for declaring variables within a function,
for instance.
A declaration statement contains a list of all declared variables.
"""
def __init__(self, scope, parent):
"""Constructor for declaration statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.variables = []
def _add(self, codeobj):
"""Add a child (variable) to this object."""
assert isinstance(codeobj, CodeVariable)
self.variables.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.variables:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
return spaces + ', '.join(v.pretty_str() for v in self.variables)
def __repr__(self):
"""Return a string representation of this object."""
return str(self.variables)
class CodeControlFlow(CodeStatement, CodeStatementGroup):
"""Base class for control flow structures (e.g. `for` loops).
Control flow statements are assumed to have, at least, one branch
(a boolean condition and a `CodeBlock` that is executed when
the condition is met). Specific implementations may consider
more branches, or default branches (executed when no condition is met).
A control flow statement typically has a name.
"""
def __init__(self, scope, parent, name):
"""Constructor for control flow structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the control flow statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.condition = True
self.body = CodeBlock(scope, self, explicit=False)
def get_branches(self):
"""Return a list of branches, where each branch is a pair of
condition and respective body."""
return [(self.condition, self.body)]
def _set_condition(self, condition):
"""Set the condition for this control flow structure."""
assert isinstance(condition, CodeExpression.TYPES)
self.condition = condition
def _set_body(self, body):
"""Set the main body for this control flow structure."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.body = body
else:
self.body._add(body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return '{} {}'.format(self.name, self.get_branches())
class CodeConditional(CodeControlFlow):
"""This class represents a conditional (`if`).
A conditional is allowed to have a default branch (the `else` branch),
besides its mandatory one.
"""
def __init__(self, scope, parent):
"""Constructor for conditionals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, 'if')
self.else_body = CodeBlock(scope, self, explicit=False)
@property
def then_branch(self):
"""The branch associated with a condition."""
return self.condition, self.body
@property
def else_branch(self):
"""The default branch of the conditional."""
return True, self.else_body
def statement(self, i):
"""Return the *i*-th statement of this block.
Behaves as if the *then* and *else* branches were
concatenated, for indexing purposes.
"""
# ----- This code is just to avoid creating a new list and
# returning a custom exception message.
o = len(self.body)
n = o + len(self.else_body)
if i >= 0 and i < n:
if i < o:
return self.body.statement(i)
return self.else_body.statement(i - o)
elif i < 0 and i >= -n:
if i >= o - n:
return self.else_body.statement(i)
return self.body.statement(i - o + n)
raise IndexError('statement index out of range')
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
k = i + 1
o = len(self.body)
n = o + len(self.else_body)
if k > 0:
if k < o:
return self.body.statement(k)
if k > o and k < n:
return self.else_body.statement(k)
if k < 0:
if k < o - n and k > -n:
return self.body.statement(k)
if k > o - n:
return self.else_body.statement(k)
return None
def get_branches(self):
"""Return a list with the conditional branch and the default branch."""
if self.else_branch:
return [self.then_branch, self.else_branch]
return [self.then_branch]
def _add_default_branch(self, body):
"""Add a default body for this conditional (the `else` branch)."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.else_body = body
else:
self.else_body._add(body)
def __len__(self):
"""Return the length of both branches combined."""
return len(self.body) + len(self.else_body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
for codeobj in self.else_body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}if ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
if self.else_body:
pretty += '\n{}else:\n'.format(spaces)
pretty += self.else_body.pretty_str(indent=indent + 2)
return pretty
class CodeLoop(CodeControlFlow):
"""This class represents a loop (e.g. `while`, `for`).
Some languages allow loops to define local declarations, as well
as an increment statement.
A loop has only a single branch, its condition plus the body
that should be repeated while the condition holds.
"""
def __init__(self, scope, parent, name):
"""Constructor for loops.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the loop statement in the program.
"""
CodeControlFlow.__init__(self, scope, parent, name)
self.declarations = None
self.increment = None
def _set_declarations(self, declarations):
"""Set declarations local to this loop (e.g. `for` variables)."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_increment(self, statement):
"""Set the increment statement for this loop (e.g. in a `for`)."""
assert isinstance(statement, CodeStatement)
self.increment = statement
statement.scope = self.body
def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
v = self.declarations.pretty_str() if self.declarations else ''
i = self.increment.pretty_str(indent=1) if self.increment else ''
pretty = '{}for ({}; {}; {}):\n'.format(spaces, v, condition, i)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class CodeSwitch(CodeControlFlow):
"""This class represents a switch statement.
A switch evaluates a value (its `condition`) and then declares
at least one branch (*cases*) that execute when the evaluated value
is equal to the branch value. It may also have a default branch.
Switches are often one of the most complex constructs of programming
languages, so this implementation might be lackluster.
"""
def __init__(self, scope, parent):
"""Constructor for switches.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, "switch")
self.cases = []
self.default_case = None
def _add_branch(self, value, statement):
"""Add a branch/case (value and statement) to this switch."""
self.cases.append((value, statement))
def _add_default_branch(self, statement):
"""Add a default branch to this switch."""
self.default_case = statement
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}switch ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class CodeTryBlock(CodeStatement, CodeStatementGroup):
"""This class represents a try-catch block statement.
`try` blocks have a main body of statements, just like regular blocks.
Multiple `catch` blocks may be defined to handle specific types of
exceptions.
Some languages also allow a `finally` block that is executed after
the other blocks (either the `try` block, or a `catch` block, when
an exception is raised and handled).
"""
def __init__(self, scope, parent):
"""Constructor for try block structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.body = CodeBlock(scope, self, explicit=True)
self.catches = []
self.finally_body = CodeBlock(scope, self, explicit=True)
def _set_body(self, body):
"""Set the main body for try block structure."""
assert isinstance(body, CodeBlock)
self.body = body
def _add_catch(self, catch_block):
"""Add a catch block (exception variable declaration and block)
to this try block structure.
"""
assert isinstance(catch_block, self.CodeCatchBlock)
self.catches.append(catch_block)
def _set_finally_body(self, body):
"""Set the finally body for try block structure."""
assert isinstance(body, CodeBlock)
self.finally_body = body
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body._children():
yield codeobj
for catch_block in self.catches:
for codeobj in catch_block._children():
yield codeobj
for codeobj in self.finally_body._children():
yield codeobj
def __len__(self):
"""Return the length of all blocks combined."""
n = len(self.body) + len(self.catches) + len(self.finally_body)
n += sum(map(len, self.catches))
return n
def __repr__(self):
"""Return a string representation of this object."""
return 'try {} {} {}'.format(self.body, self.catches,
self.finally_body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'try:\n'
pretty += self.body.pretty_str(indent=indent + 2)
for block in self.catches:
pretty += '\n' + block.pretty_str(indent)
if len(self.finally_body) > 0:
pretty += '\n{}finally:\n'.format(spaces)
pretty += self.finally_body.pretty_str(indent=indent + 2)
return pretty
class CodeCatchBlock(CodeStatement, CodeStatementGroup):
"""Helper class for catch statements within a try-catch block."""
def __init__(self, scope, parent):
"""Constructor for catch block structures."""
CodeStatement.__init__(self, scope, parent)
self.declarations = None
self.body = CodeBlock(scope, self, explicit=True)
def _set_declarations(self, declarations):
"""Set declarations local to this catch block."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_body(self, body):
"""Set the main body of the catch block."""
assert isinstance(body, CodeBlock)
self.body = body
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.declarations, CodeStatement):
yield self.declarations
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return 'catch ({}) {}'.format(self.declarations, self.body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
decls = ('...' if self.declarations is None
else self.declarations.pretty_str())
body = self.body.pretty_str(indent=indent + 2)
pretty = '{}catch ({}):\n{}'.format(spaces, decls, body)
return pretty
###############################################################################
# Helpers
###############################################################################
def pretty_str(something, indent=0):
"""Return a human-readable string representation of an object.
Uses `pretty_str` if the given value is an instance of
`CodeEntity` and `repr` otherwise.
Args:
something: Some value to convert.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if isinstance(something, CodeEntity):
return something.pretty_str(indent=indent)
else:
return (' ' * indent) + repr(something)
| class Codeentity(object):
"""Base class for all programming entities.
All code objects have a file name, a line number, a column number,
a programming scope (e.g. the function or code block they belong to)
and a parent object that should have some variable or collection
holding this object.
"""
def __init__(self, scope, parent):
"""Base constructor for code objects.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
self.scope = scope
self.parent = parent
self.file = None
self.line = None
self.column = None
def walk_preorder(self):
"""Iterates the program tree starting from this object, going down."""
yield self
for child in self._children():
for descendant in child.walk_preorder():
yield descendant
def filter(self, cls, recursive=False):
"""Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree.
"""
source = self.walk_preorder if recursive else self._children
return [codeobj for codeobj in source() if isinstance(codeobj, cls)]
def _afterpass(self):
"""Finalizes the construction of a code entity."""
pass
def _validity_check(self):
"""Check whether this object is a valid construct."""
return True
def _children(self):
"""Yield all direct children of this object."""
return iter(())
def _lookup_parent(self, cls):
"""Lookup a transitive parent object that is an instance
of a given class."""
codeobj = self.parent
while codeobj is not None and (not isinstance(codeobj, cls)):
codeobj = codeobj.parent
return codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return ' ' * indent + self.__str__()
def ast_str(self, indent=0):
"""Return a minimal string to print a tree-like structure.
Kwargs:
indent (int): The number of indentation levels.
"""
line = self.line or 0
col = self.column or 0
name = type(self).__name__
spell = getattr(self, 'name', '[no spelling]')
result = ' ({})'.format(self.result) if hasattr(self, 'result') else ''
prefix = indent * '| '
return '{}[{}:{}] {}{}: {}'.format(prefix, line, col, name, result, spell)
def __str__(self):
"""Return a string representation of this object."""
return self.__repr__()
def __repr__(self):
"""Return a string representation of this object."""
return '[unknown]'
class Codestatementgroup(object):
"""This class is meant to provide common utility methods for
objects that group multiple program statements together
(e.g. functions, code blocks).
It is not meant to be instantiated directly, only used for
inheritance purposes.
It defines the length of a statement group, and provides methods
for integer-based indexing of program statements (as if using a list).
"""
def statement(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.body.statement(i)
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
try:
return self.statement(i + 1)
except IndexError as e:
return None
def __getitem__(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.statement(i)
def __len__(self):
"""Return the length of the statement group."""
return len(self.body)
class Codevariable(CodeEntity):
"""This class represents a program variable.
A variable typically has a name, a type (`result`) and a value
(or `None` for variables without a value or when the value is unknown).
Additionally, a variable has an `id` which uniquely identifies it in
the program (useful to resolve references), a list of references to it
and a list of statements that write new values to the variable.
If the variable is a *member*/*field*/*attribute* of an object,
`member_of` should contain a reference to such object, instead of `None`.
"""
def __init__(self, scope, parent, id, name, result):
"""Constructor for variables.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this variable.
name (str): The name of the variable in the program.
result (str): The type of the variable in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.value = None
self.member_of = None
self.references = []
self.writes = []
@property
def is_definition(self):
return True
@property
def is_local(self):
"""Whether this is a local variable.
In general, a variable is *local* if its containing scope is a
statement (e.g. a block), or a function, given that the variable
is not one of the function's parameters.
"""
return isinstance(self.scope, CodeStatement) or (isinstance(self.scope, CodeFunction) and self not in self.scope.parameters)
@property
def is_global(self):
"""Whether this is a global variable.
In general, a variable is *global* if it is declared directly under
the program's global scope or a namespace.
"""
return isinstance(self.scope, (CodeGlobalScope, CodeNamespace))
@property
def is_parameter(self):
"""Whether this is a function parameter."""
return isinstance(self.scope, CodeFunction) and self in self.scope.parameters
@property
def is_member(self):
"""Whether this is a member/attribute of a class or object."""
return isinstance(self.scope, CodeClass)
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeEntity):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '{}{} {} = {}'.format(' ' * indent, self.result, self.name, pretty_str(self.value))
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {} = ({})'.format(self.result, self.name, self.value)
class Codefunction(CodeEntity, CodeStatementGroup):
"""This class represents a program function.
A function typically has a name, a return type (`result`), a list
of parameters and a body (a code block). It also has an unique `id`
that identifies it in the program and a list of references to it.
If a function is a method of some class, its `member_of` should be
set to the corresponding class.
"""
def __init__(self, scope, parent, id, name, result, definition=True):
"""Constructor for functions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this function.
name (str): The name of the function in the program.
result (str): The return type of the function in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.parameters = []
self.body = code_block(self, self, explicit=True)
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a function definition or just a declaration."""
return self._definition is self
@property
def is_constructor(self):
"""Whether this function is a class constructor."""
return self.member_of is not None
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, (CodeStatement, CodeExpression))
self.body._add(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.parameters:
yield codeobj
for codeobj in self.body._children():
yield codeobj
def _afterpass(self):
"""Assign a function-local index to each child object and register
write operations to variables.
This should only be called after the object is fully built.
"""
if hasattr(self, '_fi'):
return
fi = 0
for codeobj in self.walk_preorder():
codeobj._fi = fi
fi += 1
if isinstance(codeobj, CodeOperator) and codeobj.is_assignment:
if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference):
var = codeobj.arguments[0].reference
if isinstance(var, CodeVariable):
var.writes.append(codeobj)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
params = ', '.join(map(lambda p: p.result + ' ' + p.name, self.parameters))
if self.is_constructor:
pretty = '{}{}({}):\n'.format(spaces, self.name, params)
else:
pretty = '{}{} {}({}):\n'.format(spaces, self.result, self.name, params)
if self._definition is not self:
pretty += spaces + ' [declaration]'
else:
pretty += self.body.pretty_str(indent + 2)
return pretty
def __repr__(self):
"""Return a string representation of this object."""
params = ', '.join(map(str, self.parameters))
return '[{}] {}({})'.format(self.result, self.name, params)
class Codeclass(CodeEntity):
"""This class represents a program class for object-oriented languages.
A class typically has a name, an unique `id`, a list of
members (variables, functions), a list of superclasses, and a list of
references.
If a class is defined within another class (inner class), it should
have its `member_of` set to the corresponding class.
"""
def __init__(self, scope, parent, id_, name, definition=True):
"""Constructor for classes.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this class.
name (str): The name of the class in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id_
self.name = name
self.members = []
self.superclasses = []
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a definition or a declaration of the class."""
return self._definition is self
def _add(self, codeobj):
"""Add a child (function, variable, class) to this object."""
assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass))
self.members.append(codeobj)
codeobj.member_of = self
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.members:
yield codeobj
def _afterpass(self):
"""Assign the `member_of` of child members and call
their `_afterpass()`.
This should only be called after the object is fully built.
"""
for codeobj in self.members:
if not codeobj.is_definition:
if not codeobj._definition is None:
codeobj._definition.member_of = self
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'class ' + self.name
if self.superclasses:
superclasses = ', '.join(self.superclasses)
pretty += '(' + superclasses + ')'
pretty += ':\n'
if self.members:
pretty += '\n\n'.join((c.pretty_str(indent + 2) for c in self.members))
else:
pretty += spaces + ' [declaration]'
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[class {}]'.format(self.name)
class Codenamespace(CodeEntity):
"""This class represents a program namespace.
A namespace is a concept that is explicit in languages such as C++,
but less explicit in many others. In Python, the closest thing should
be a module. In Java, it may be the same as a class, or non-existent.
A namespace typically has a name and a list of children objects
(variables, functions or classes).
"""
def __init__(self, scope, parent, name):
"""Constructor for namespaces.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the namespace in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}namespace {}:\n'.format(spaces, self.name)
pretty += '\n\n'.join((c.pretty_str(indent + 2) for c in self.children))
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[namespace {}]'.format(self.name)
class Codeglobalscope(CodeEntity):
"""This class represents the global scope of a program.
The global scope is the root object of a program. If there are no
better candidates, it is the `scope` and `parent` of all other objects.
It is also the only object that does not have a `scope` or `parent`.
"""
def __init__(self):
"""Constructor for global scope objects."""
CodeEntity.__init__(self, None, None)
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '\n\n'.join((codeobj.pretty_str(indent=indent) for codeobj in self.children))
class Codeexpression(CodeEntity):
"""Base class for expressions within a program.
Expressions can be of many types, including literal values,
operators, references and function calls. This class is meant
to be inherited from, and not instantiated directly.
An expression typically has a name (e.g. the name of the function
in a function call) and a type (`result`). Also, an expression should
indicate whether it is enclosed in parentheses.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for expressions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the expression in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.result = result
self.parenthesis = paren
@property
def function(self):
"""The function where this expression occurs."""
return self._lookup_parent(CodeFunction)
@property
def statement(self):
"""The statement where this expression occurs."""
return self._lookup_parent(CodeStatement)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return ' ' * indent + '(' + self.name + ')'
return ' ' * indent + self.name
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {}'.format(self.result, self.name)
class Somevalue(CodeExpression):
"""This class represents an unknown value for diverse primitive types."""
def __init__(self, result):
"""Constructor for unknown values."""
CodeExpression.__init__(self, None, None, result, result)
def _children(self):
"""Yield all the children of this object, that is no children."""
return iter(())
SomeValue.INTEGER = some_value('int')
SomeValue.FLOATING = some_value('float')
SomeValue.CHARACTER = some_value('char')
SomeValue.STRING = some_value('string')
SomeValue.BOOL = some_value('bool')
class Codeliteral(CodeExpression):
"""Base class for literal types not present in Python.
This class is meant to represent a literal whose type is not numeric,
string or boolean, as bare Python literals are used for those.
A literal has a value (e.g. a list `[1, 2, 3]`) and a type (`result`),
and could be enclosed in parentheses. It does not have a name.
"""
def __init__(self, scope, parent, value, result, paren=False):
"""Constructor for literals.
As literals have no name, a constant string is used instead.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (CodeExpression|CodeExpression[]): This literal's value.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, 'literal', result, paren)
self.value = value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return '{}({})'.format(' ' * indent, pretty_str(self.value))
return pretty_str(self.value, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {!r}'.format(self.result, self.value)
CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression)
CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral)
class Codenull(CodeLiteral):
"""This class represents an indefinite value.
Many programming languages have their own version of this concept:
Java has null references, C/C++ NULL pointers, Python None and so on.
"""
def __init__(self, scope, parent, paren=False):
"""Constructor for null literals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
paren (bool): Whether the null literal is enclosed in parentheses.
"""
CodeLiteral.__init__(self, scope, parent, None, 'null', paren)
def _children(self):
"""Yield all the children of this object, that is no children.
This class inherits from CodeLiteral just for consistency with the
class hierarchy. It should have no children, thus an empty iterator
is returned.
"""
return iter(())
class Codecompositeliteral(CodeLiteral):
"""This class represents a composite literal.
A composite literal is any type of literal whose value is compound,
rather than simple. An example present in many programming languages
are list literals, often constructed as `[1, 2, 3]`.
A composite literal has a sequence of values that compose it
(`values`), a type (`result`), and it should indicate whether it is
enclosed in parentheses.
"""
def __init__(self, scope, parent, result, value=(), paren=False):
"""Constructor for a compound literal.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (iterable): The initial value sequence in this composition.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
try:
value = list(value)
except TypeError as te:
raise assertion_error(str(te))
CodeLiteral.__init__(self, scope, parent, value, result, paren)
@property
def values(self):
return tuple(self.value)
def _add_value(self, child):
"""Add a value to the sequence in this composition."""
self.value.append(child)
def _children(self):
"""Yield all direct children of this object."""
for value in self.value:
if isinstance(value, CodeEntity):
yield value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
values = '{{{}}}'.format(', '.join(map(pretty_str, self.value)))
if self.parenthesis:
return '{}({})'.format(indent, values)
return '{}{}'.format(indent, values)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {{{}}}'.format(self.result, ', '.join(map(repr, self.value)))
class Codereference(CodeExpression):
"""This class represents a reference expression (e.g. to a variable).
A reference typically has a name (of what it is referencing),
and a return type.
If the referenced entity is known, `reference` should be set.
If the reference is a field/attribute of an object, `field_of`
should be set to that object.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for references.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the reference in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the reference is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.field_of = None
self.reference = None
def _set_field(self, codeobj):
"""Set the object that contains the attribute this is a reference of."""
assert isinstance(codeobj, CodeExpression)
self.field_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.field_of:
yield self.field_of
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
name = '{}.{}'.format(self.field_of.pretty_str(), self.name) if self.field_of else self.name
return pretty.format(spaces, name)
def __str__(self):
"""Return a string representation of this object."""
return '#' + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.field_of:
return '[{}] ({}).{}'.format(self.result, self.field_of, self.name)
return '[{}] #{}'.format(self.result, self.name)
class Codeoperator(CodeExpression):
"""This class represents an operator expression (e.g. `a + b`).
Operators can be unary or binary, and often return numbers
or booleans. Some languages also support ternary operators.
Do note that assignments are often considered expressions,
and, as such, assignment operators are included here.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
_unary_tokens = ('+', '-')
_binary_tokens = ('+', '-', '*', '/', '%', '<', '>', '<=', '>=', '==', '!=', '&&', '||', '=')
def __init__(self, scope, parent, name, result, args=None, paren=False):
"""Constructor for operators.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the operator in the program.
result (str): The return type of the operator in the program.
Kwargs:
args (tuple): Initial tuple of arguments.
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.arguments = args or ()
@property
def is_unary(self):
"""Whether this is a unary operator."""
return len(self.arguments) == 1
@property
def is_binary(self):
"""Whether this is a binary operator."""
return len(self.arguments) == 2
@property
def is_ternary(self):
"""Whether this is a ternary operator."""
return len(self.arguments) == 3
@property
def is_assignment(self):
"""Whether this is an assignment operator."""
return self.name == '='
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
if self.is_unary:
operator = self.name + pretty_str(self.arguments[0])
else:
operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1]))
return pretty.format(indent, operator)
def __repr__(self):
"""Return a string representation of this object."""
if self.is_unary:
return '[{}] {}({})'.format(self.result, self.name, self.arguments[0])
if self.is_binary:
return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1])
return '[{}] {}'.format(self.result, self.name)
class Codefunctioncall(CodeExpression):
"""This class represents a function call.
A function call typically has a name (of the called function),
a return type, a tuple of its arguments and a reference to the
called function.
If a call references a class method, its `method_of` should be
set to the object on which a method is being called.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for function calls.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the function in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.full_name = name
self.arguments = ()
self.method_of = None
self.reference = None
@property
def is_constructor(self):
"""Whether the called function is a constructor."""
return self.result == self.name
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _set_method(self, codeobj):
"""Set the object on which a method is called."""
assert isinstance(codeobj, CodeExpression)
self.method_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.method_of:
yield self.method_of
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
args = ', '.join(map(pretty_str, self.arguments))
if self.method_of:
call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args)
elif self.is_constructor:
call = 'new {}({})'.format(self.name, args)
else:
call = '{}({})'.format(self.name, args)
return pretty.format(indent, call)
def __repr__(self):
"""Return a string representation of this object."""
args = ', '.join(map(str, self.arguments))
if self.is_constructor:
return '[{}] new {}({})'.format(self.result, self.name, args)
if self.method_of:
return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args)
return '[{}] {}({})'.format(self.result, self.name, args)
class Codedefaultargument(CodeExpression):
"""This class represents a default argument.
Some languages, such as C++, allow function parameters to have
default values when not explicitly provided by the programmer.
This class represents such omitted arguments.
A default argument has only a return type.
"""
def __init__(self, scope, parent, result):
"""Constructor for default arguments.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
result (str): The return type of the argument in the program.
"""
CodeExpression.__init__(self, scope, parent, '(default)', result)
class Codestatement(CodeEntity):
"""Base class for program statements.
Programming languages often define diverse types of statements
(e.g. return statements, control flow, etc.).
This class provides common functionality for such statements.
In many languages, statements must be contained within a function.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
def __init__(self, scope, parent):
"""Constructor for statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeEntity.__init__(self, scope, parent)
self._si = -1
@property
def function(self):
"""The function where this statement appears in."""
return self._lookup_parent(CodeFunction)
class Codejumpstatement(CodeStatement):
"""This class represents a jump statement (e.g. `return`, `break`).
A jump statement has a name. In some cases, it may also have an
associated value (e.g. `return 0`).
"""
def __init__(self, scope, parent, name):
"""Constructor for jump statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.value = None
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeExpression):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
if self.value is not None:
return '{}{} {}'.format(indent, self.name, pretty_str(self.value))
return indent + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.value is not None:
return '{} {}'.format(self.name, str(self.value))
return self.name
class Codeexpressionstatement(CodeStatement):
"""This class represents an expression statement. It is only a wrapper.
Many programming languages allow expressions to be statements
on their own. A common example is the assignment operator, which
can be a statement on its own, but also returns a value when
contained within a larger expression.
"""
def __init__(self, scope, parent, expression=None):
"""Constructor for expression statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
expression (CodeExpression): The expression of this statement.
"""
CodeStatement.__init__(self, scope, parent)
self.expression = expression
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.expression, CodeExpression):
yield self.expression
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return pretty_str(self.expression, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return repr(self.expression)
class Codeblock(CodeStatement, CodeStatementGroup):
"""This class represents a code block (e.g. `{}` in C, C++, Java, etc.).
Blocks are little more than collections of statements, while being
considered a statement themselves.
Some languages allow blocks to be implicit in some contexts, e.g.
an `if` statement omitting curly braces in C, C++, Java, etc.
This model assumes that control flow branches and functions always
have a block as their body.
"""
def __init__(self, scope, parent, explicit=True):
"""Constructor for code blocks.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
explicit (bool): Whether the block is explicit in the code.
"""
CodeStatement.__init__(self, scope, parent)
self.body = []
self.explicit = explicit
def statement(self, i):
"""Return the *i*-th statement of this block."""
return self.body[i]
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, CodeStatement)
codeobj._si = len(self.body)
self.body.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.body:
return '\n'.join((stmt.pretty_str(indent) for stmt in self.body))
else:
return ' ' * indent + '[empty]'
def __repr__(self):
"""Return a string representation of this object."""
return str(self.body)
class Codedeclaration(CodeStatement):
"""This class represents a declaration statement.
Some languages, such as C, C++ or Java, consider this special
kind of statement for declaring variables within a function,
for instance.
A declaration statement contains a list of all declared variables.
"""
def __init__(self, scope, parent):
"""Constructor for declaration statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.variables = []
def _add(self, codeobj):
"""Add a child (variable) to this object."""
assert isinstance(codeobj, CodeVariable)
self.variables.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.variables:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
return spaces + ', '.join((v.pretty_str() for v in self.variables))
def __repr__(self):
"""Return a string representation of this object."""
return str(self.variables)
class Codecontrolflow(CodeStatement, CodeStatementGroup):
"""Base class for control flow structures (e.g. `for` loops).
Control flow statements are assumed to have, at least, one branch
(a boolean condition and a `CodeBlock` that is executed when
the condition is met). Specific implementations may consider
more branches, or default branches (executed when no condition is met).
A control flow statement typically has a name.
"""
def __init__(self, scope, parent, name):
"""Constructor for control flow structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the control flow statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.condition = True
self.body = code_block(scope, self, explicit=False)
def get_branches(self):
"""Return a list of branches, where each branch is a pair of
condition and respective body."""
return [(self.condition, self.body)]
def _set_condition(self, condition):
"""Set the condition for this control flow structure."""
assert isinstance(condition, CodeExpression.TYPES)
self.condition = condition
def _set_body(self, body):
"""Set the main body for this control flow structure."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.body = body
else:
self.body._add(body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return '{} {}'.format(self.name, self.get_branches())
class Codeconditional(CodeControlFlow):
"""This class represents a conditional (`if`).
A conditional is allowed to have a default branch (the `else` branch),
besides its mandatory one.
"""
def __init__(self, scope, parent):
"""Constructor for conditionals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, 'if')
self.else_body = code_block(scope, self, explicit=False)
@property
def then_branch(self):
"""The branch associated with a condition."""
return (self.condition, self.body)
@property
def else_branch(self):
"""The default branch of the conditional."""
return (True, self.else_body)
def statement(self, i):
"""Return the *i*-th statement of this block.
Behaves as if the *then* and *else* branches were
concatenated, for indexing purposes.
"""
o = len(self.body)
n = o + len(self.else_body)
if i >= 0 and i < n:
if i < o:
return self.body.statement(i)
return self.else_body.statement(i - o)
elif i < 0 and i >= -n:
if i >= o - n:
return self.else_body.statement(i)
return self.body.statement(i - o + n)
raise index_error('statement index out of range')
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
k = i + 1
o = len(self.body)
n = o + len(self.else_body)
if k > 0:
if k < o:
return self.body.statement(k)
if k > o and k < n:
return self.else_body.statement(k)
if k < 0:
if k < o - n and k > -n:
return self.body.statement(k)
if k > o - n:
return self.else_body.statement(k)
return None
def get_branches(self):
"""Return a list with the conditional branch and the default branch."""
if self.else_branch:
return [self.then_branch, self.else_branch]
return [self.then_branch]
def _add_default_branch(self, body):
"""Add a default body for this conditional (the `else` branch)."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.else_body = body
else:
self.else_body._add(body)
def __len__(self):
"""Return the length of both branches combined."""
return len(self.body) + len(self.else_body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
for codeobj in self.else_body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}if ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
if self.else_body:
pretty += '\n{}else:\n'.format(spaces)
pretty += self.else_body.pretty_str(indent=indent + 2)
return pretty
class Codeloop(CodeControlFlow):
"""This class represents a loop (e.g. `while`, `for`).
Some languages allow loops to define local declarations, as well
as an increment statement.
A loop has only a single branch, its condition plus the body
that should be repeated while the condition holds.
"""
def __init__(self, scope, parent, name):
"""Constructor for loops.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the loop statement in the program.
"""
CodeControlFlow.__init__(self, scope, parent, name)
self.declarations = None
self.increment = None
def _set_declarations(self, declarations):
"""Set declarations local to this loop (e.g. `for` variables)."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_increment(self, statement):
"""Set the increment statement for this loop (e.g. in a `for`)."""
assert isinstance(statement, CodeStatement)
self.increment = statement
statement.scope = self.body
def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
v = self.declarations.pretty_str() if self.declarations else ''
i = self.increment.pretty_str(indent=1) if self.increment else ''
pretty = '{}for ({}; {}; {}):\n'.format(spaces, v, condition, i)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class Codeswitch(CodeControlFlow):
"""This class represents a switch statement.
A switch evaluates a value (its `condition`) and then declares
at least one branch (*cases*) that execute when the evaluated value
is equal to the branch value. It may also have a default branch.
Switches are often one of the most complex constructs of programming
languages, so this implementation might be lackluster.
"""
def __init__(self, scope, parent):
"""Constructor for switches.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, 'switch')
self.cases = []
self.default_case = None
def _add_branch(self, value, statement):
"""Add a branch/case (value and statement) to this switch."""
self.cases.append((value, statement))
def _add_default_branch(self, statement):
"""Add a default branch to this switch."""
self.default_case = statement
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}switch ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class Codetryblock(CodeStatement, CodeStatementGroup):
"""This class represents a try-catch block statement.
`try` blocks have a main body of statements, just like regular blocks.
Multiple `catch` blocks may be defined to handle specific types of
exceptions.
Some languages also allow a `finally` block that is executed after
the other blocks (either the `try` block, or a `catch` block, when
an exception is raised and handled).
"""
def __init__(self, scope, parent):
"""Constructor for try block structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.body = code_block(scope, self, explicit=True)
self.catches = []
self.finally_body = code_block(scope, self, explicit=True)
def _set_body(self, body):
"""Set the main body for try block structure."""
assert isinstance(body, CodeBlock)
self.body = body
def _add_catch(self, catch_block):
"""Add a catch block (exception variable declaration and block)
to this try block structure.
"""
assert isinstance(catch_block, self.CodeCatchBlock)
self.catches.append(catch_block)
def _set_finally_body(self, body):
"""Set the finally body for try block structure."""
assert isinstance(body, CodeBlock)
self.finally_body = body
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body._children():
yield codeobj
for catch_block in self.catches:
for codeobj in catch_block._children():
yield codeobj
for codeobj in self.finally_body._children():
yield codeobj
def __len__(self):
"""Return the length of all blocks combined."""
n = len(self.body) + len(self.catches) + len(self.finally_body)
n += sum(map(len, self.catches))
return n
def __repr__(self):
"""Return a string representation of this object."""
return 'try {} {} {}'.format(self.body, self.catches, self.finally_body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'try:\n'
pretty += self.body.pretty_str(indent=indent + 2)
for block in self.catches:
pretty += '\n' + block.pretty_str(indent)
if len(self.finally_body) > 0:
pretty += '\n{}finally:\n'.format(spaces)
pretty += self.finally_body.pretty_str(indent=indent + 2)
return pretty
class Codecatchblock(CodeStatement, CodeStatementGroup):
"""Helper class for catch statements within a try-catch block."""
def __init__(self, scope, parent):
"""Constructor for catch block structures."""
CodeStatement.__init__(self, scope, parent)
self.declarations = None
self.body = code_block(scope, self, explicit=True)
def _set_declarations(self, declarations):
"""Set declarations local to this catch block."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_body(self, body):
"""Set the main body of the catch block."""
assert isinstance(body, CodeBlock)
self.body = body
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.declarations, CodeStatement):
yield self.declarations
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return 'catch ({}) {}'.format(self.declarations, self.body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
decls = '...' if self.declarations is None else self.declarations.pretty_str()
body = self.body.pretty_str(indent=indent + 2)
pretty = '{}catch ({}):\n{}'.format(spaces, decls, body)
return pretty
def pretty_str(something, indent=0):
"""Return a human-readable string representation of an object.
Uses `pretty_str` if the given value is an instance of
`CodeEntity` and `repr` otherwise.
Args:
something: Some value to convert.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if isinstance(something, CodeEntity):
return something.pretty_str(indent=indent)
else:
return ' ' * indent + repr(something) |
def is_even(i: int) -> bool:
if i == 1:
return False
elif i == 2:
return True
elif i == 3:
return False
elif i == 4:
return True
elif i == 5:
...
# Never do that! Use one of these instead...
is_even = lambda i : i % 2 == 0
is_even = lambda i : not i & 1
is_odd = lambda i : not is_even(i) | def is_even(i: int) -> bool:
if i == 1:
return False
elif i == 2:
return True
elif i == 3:
return False
elif i == 4:
return True
elif i == 5:
...
is_even = lambda i: i % 2 == 0
is_even = lambda i: not i & 1
is_odd = lambda i: not is_even(i) |
"""
Contains the QuantumCircuit class
boom.
"""
class QuantumCircuit(object): # pylint: disable=useless-object-inheritance
""" Implements a quantum circuit.
- - - WRITE DOCUMENTATION HERE - - -
"""
def __init__(self):
""" Initialise a QuantumCircuit object """
pass
def add_gate(self, gate):
""" Add a gate to the circuit """
pass
def run_circuit(self, register):
""" Run the circuit on a given quantum register """
pass
def __call__(self, register):
""" Run the circuit on a given quantum register """
pass
| """
Contains the QuantumCircuit class
boom.
"""
class Quantumcircuit(object):
""" Implements a quantum circuit.
- - - WRITE DOCUMENTATION HERE - - -
"""
def __init__(self):
""" Initialise a QuantumCircuit object """
pass
def add_gate(self, gate):
""" Add a gate to the circuit """
pass
def run_circuit(self, register):
""" Run the circuit on a given quantum register """
pass
def __call__(self, register):
""" Run the circuit on a given quantum register """
pass |
"""
Module: 'ubinascii' on esp32 1.10.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32')
# Stubber: 1.2.0
def a2b_base64():
pass
def b2a_base64():
pass
def crc32():
pass
def hexlify():
pass
def unhexlify():
pass
| """
Module: 'ubinascii' on esp32 1.10.0
"""
def a2b_base64():
pass
def b2a_base64():
pass
def crc32():
pass
def hexlify():
pass
def unhexlify():
pass |
__title__ = 'har2case'
__description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.'
__url__ = 'https://github.com/HttpRunner/har2case'
__version__ = '0.2.0'
__author__ = 'debugtalk'
__author_email__ = 'mail@debugtalk.com'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright 2017 debugtalk' | __title__ = 'har2case'
__description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.'
__url__ = 'https://github.com/HttpRunner/har2case'
__version__ = '0.2.0'
__author__ = 'debugtalk'
__author_email__ = 'mail@debugtalk.com'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright 2017 debugtalk' |
def pictureInserter(og,address,list):
j=0
for i in og:
file1 = open(address+'/'+i, "a")
x="\ncover::https://image.tmdb.org/t/p/original/"+list[j]
file1.writelines(x)
file1.close()
j=j+1
| def picture_inserter(og, address, list):
j = 0
for i in og:
file1 = open(address + '/' + i, 'a')
x = '\ncover::https://image.tmdb.org/t/p/original/' + list[j]
file1.writelines(x)
file1.close()
j = j + 1 |
class Solution:
def removeOuterParentheses(self, s: str) -> str:
ans = []
ct = 0
for ch in s:
if ch == '(':
ct += 1
if ct != 1:
ans.append(ch)
else:
ct -= 1
if ct != 0:
ans.append(ch)
return ''.join(ans)
if __name__ == '__main__':
# s = '(()())(())'
# s = '(()())(())(()(()))'
s = '()()'
ret = Solution().removeOuterParentheses(s)
print(ret)
| class Solution:
def remove_outer_parentheses(self, s: str) -> str:
ans = []
ct = 0
for ch in s:
if ch == '(':
ct += 1
if ct != 1:
ans.append(ch)
else:
ct -= 1
if ct != 0:
ans.append(ch)
return ''.join(ans)
if __name__ == '__main__':
s = '()()'
ret = solution().removeOuterParentheses(s)
print(ret) |
#######################################################################################################################
# Given a string, find the length of the longest substring which has no repeating characters.
#
# Input: String="aabccbb"
# Output: 3
# Explanation: The longest substring without any repeating characters is "abc".
#
# Input: String="abbbb"
# Output: 2
# Explanation: The longest substring without any repeating characters is "ab".
#
# Input: String="abccde"
# Output: 3
# Explanation: Longest substrings without any repeating characters are "abc" & "cde".
#######################################################################################################################
def longest_substring_no_repeating_char(input_str: str) -> int:
window_start = 0
is_present = [None for i in range(26)]
max_window = 0
for i in range(len(input_str)):
char_ord = ord(input_str[i]) - 97
if is_present[char_ord] is not None:
window_start = max(window_start, is_present[char_ord] + 1)
is_present[char_ord] = i
max_window = max(max_window, i - window_start + 1)
return max_window
print(longest_substring_no_repeating_char('aabccbb'))
print(longest_substring_no_repeating_char('abbbb'))
print(longest_substring_no_repeating_char('abccde'))
print(longest_substring_no_repeating_char('abcabcbb'))
print(longest_substring_no_repeating_char('bbbbb'))
print(longest_substring_no_repeating_char('pwwkew'))
| def longest_substring_no_repeating_char(input_str: str) -> int:
window_start = 0
is_present = [None for i in range(26)]
max_window = 0
for i in range(len(input_str)):
char_ord = ord(input_str[i]) - 97
if is_present[char_ord] is not None:
window_start = max(window_start, is_present[char_ord] + 1)
is_present[char_ord] = i
max_window = max(max_window, i - window_start + 1)
return max_window
print(longest_substring_no_repeating_char('aabccbb'))
print(longest_substring_no_repeating_char('abbbb'))
print(longest_substring_no_repeating_char('abccde'))
print(longest_substring_no_repeating_char('abcabcbb'))
print(longest_substring_no_repeating_char('bbbbb'))
print(longest_substring_no_repeating_char('pwwkew')) |
# -*- coding: UTF-8 -*-
"""
This file is part of Pondus, a personal weight manager.
Copyright (C) 2011 Eike Nicklas <eike@ephys.de>
This program is free software licensed under the MIT license. For details
see LICENSE or http://www.opensource.org/licenses/mit-license.php
"""
__all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend',
'xml_backend_old']
| """
This file is part of Pondus, a personal weight manager.
Copyright (C) 2011 Eike Nicklas <eike@ephys.de>
This program is free software licensed under the MIT license. For details
see LICENSE or http://www.opensource.org/licenses/mit-license.php
"""
__all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend', 'xml_backend_old'] |
"""
The DataHandlers subpackage is designed to manipulate data, by allowing different data types to be opened,
created, saved and updated. The subpackage is further divided into modules grouped by a common theme. Classes for data
that are already on disk normally follows the following pattern:
`instance=ClassName(file_path,**options)`
For Example to
open a XML file that you don't know the model, use
`xml=pyMez.Code.DataHandlers.XMLModels.XMLBase('MyXML.xml')'
or
`xml=XMLBase('MyXML.xml')`
All data models normally have save(), str() and if appropriate show() methods.
Examples
--------
<a href="../../../Examples/How_To_Open_S2p.html"> How to open a s2p file </a>
Import Structure
----------------
DataHandlers typically import from Utils but __NOT__ from Analysis, InstrumentControl or FrontEnds
Help
-----
<a href="../index.html">`pyMez.Code`</a>
<div>
<a href="../../../pyMez_Documentation.html">Documentation Home</a> |
<a href="../../index.html">API Documentation Home</a> |
<a href="../../../Examples/html/Examples_Home.html">Examples</a> |
<a href="../../../Reference_Index.html">Index </a>
</div>
"""
| """
The DataHandlers subpackage is designed to manipulate data, by allowing different data types to be opened,
created, saved and updated. The subpackage is further divided into modules grouped by a common theme. Classes for data
that are already on disk normally follows the following pattern:
`instance=ClassName(file_path,**options)`
For Example to
open a XML file that you don't know the model, use
`xml=pyMez.Code.DataHandlers.XMLModels.XMLBase('MyXML.xml')'
or
`xml=XMLBase('MyXML.xml')`
All data models normally have save(), str() and if appropriate show() methods.
Examples
--------
<a href="../../../Examples/How_To_Open_S2p.html"> How to open a s2p file </a>
Import Structure
----------------
DataHandlers typically import from Utils but __NOT__ from Analysis, InstrumentControl or FrontEnds
Help
-----
<a href="../index.html">`pyMez.Code`</a>
<div>
<a href="../../../pyMez_Documentation.html">Documentation Home</a> |
<a href="../../index.html">API Documentation Home</a> |
<a href="../../../Examples/html/Examples_Home.html">Examples</a> |
<a href="../../../Reference_Index.html">Index </a>
</div>
""" |
class Solution(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
# Find max exponent
base = max(x, y) if x == 1 or y == 1 else min(x, y)
exponent = 1
if base != 1:
while base ** exponent <= bound:
exponent += 1
# Brute force all of the exponent trials
hashset = set()
for i in range(exponent):
for j in range(exponent):
z = x ** i + y ** j
if z <= bound:
hashset.add(z)
return list(hashset) | class Solution(object):
def powerful_integers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
base = max(x, y) if x == 1 or y == 1 else min(x, y)
exponent = 1
if base != 1:
while base ** exponent <= bound:
exponent += 1
hashset = set()
for i in range(exponent):
for j in range(exponent):
z = x ** i + y ** j
if z <= bound:
hashset.add(z)
return list(hashset) |
# ------------------------------
# Binary Tree Level Order Traversal
#
# Description:
# Given a binary tree, return the level order traversal of its nodes' values. (ie, from
# left to right, level by level).
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its level order traversal as:
# [
# [3],
# [9,20],
# [15,7]
# ]
#
# Version: 2.0
# 11/11/19 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
# BFS
res = []
queue = [root]
while queue:
temp = [] # values of this level of nodes
children = [] # next level of nodes
for node in queue:
temp.append(node.val)
if node.left:
children.append(node.left)
if node.right:
children.append(node.right)
res.append(temp[:]) # actually here can be res.append(temp), res will not change as temp changes
queue = children[:] # here must be children[:] otherwise queue will change as children changes
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Similar BFS solution but use a little more spaces.
# On 102.py, using list.pop(0) actually takes O(n) time because it needs to remap the index
# of values. Use collections.deque instead.
#
# O(N) time O(N) space | class Solution:
def level_order(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
queue = [root]
while queue:
temp = []
children = []
for node in queue:
temp.append(node.val)
if node.left:
children.append(node.left)
if node.right:
children.append(node.right)
res.append(temp[:])
queue = children[:]
return res
if __name__ == '__main__':
test = solution() |
def take_beer(fridge, number=1):
if "beer" not in fridge:
raise Exception("No beer at all:(")
if number > fridge["beer"]:
raise Exception("Not enough beer:(")
fridge["beer"] -= number
if __name__ == "__main__":
fridge = {
"beer": 2,
"milk": 1,
"meat": 3,
}
print("I wanna drink 1 bottle of beer...")
take_beer(fridge)
print("Oooh, great!")
print("I wanna drink 2 bottle of beer...")
try:
take_beer(fridge, 2)
except Exception as e:
print("Error: {}. Let's continue".format(e))
print("Fallback. Try to take 1 bottle of beer...")
take_beer(fridge, 1)
print("Oooh, awesome!")
| def take_beer(fridge, number=1):
if 'beer' not in fridge:
raise exception('No beer at all:(')
if number > fridge['beer']:
raise exception('Not enough beer:(')
fridge['beer'] -= number
if __name__ == '__main__':
fridge = {'beer': 2, 'milk': 1, 'meat': 3}
print('I wanna drink 1 bottle of beer...')
take_beer(fridge)
print('Oooh, great!')
print('I wanna drink 2 bottle of beer...')
try:
take_beer(fridge, 2)
except Exception as e:
print("Error: {}. Let's continue".format(e))
print('Fallback. Try to take 1 bottle of beer...')
take_beer(fridge, 1)
print('Oooh, awesome!') |
camera_width = 640
camera_height = 480
film_back_width = 1.417
film_back_height = 0.945
x_center = 320
y_center = 240
P_1 = (-0.023, -0.261, 2.376)
p_11 = P_1[0]
p_12 = P_1[1]
p_13 = P_1[2]
P_2 = (0.659, -0.071, 2.082)
p_21 = P_2[0]
p_22 = P_2[1]
p_23 = P_2[2]
p_1_prime = (52, 163)
x_1 = p_1_prime[0]
y_1 = p_1_prime[1]
p_2_prime = (218, 216)
x_2 = p_2_prime[0]
y_2 = p_2_prime[1]
f = 1.378
k_x = camera_width / film_back_width
k_y = camera_height / film_back_height
# f_k_x = f * k_x
f_k_x = f
# f_k_y = f * k_y
f_k_y = f
u_1_prime = (x_1 - x_center) / k_x
v_1_prime = (y_1 - y_center) / k_y
u_2_prime = (x_2 - x_center) / k_x
v_2_prime = (y_2 - y_center) / k_y
c_1_prime = (f_k_x * p_21 + (p_13 - p_23) * u_2_prime - u_2_prime/u_1_prime * f_k_x * p_11) / (f_k_x * (1 - u_2_prime/u_1_prime))
c_2_prime = (f_k_y * p_22 - (p_23 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_2_prime) / f_k_y
c_2_prime_alt = (f_k_y * p_12 - (p_13 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_1_prime) / f_k_y
c_3_prime = p_13 - (f_k_x / u_1_prime) * (p_11 - c_1_prime)
rho_1_prime = p_13 - c_3_prime
rho_2_prime = p_23 - c_3_prime
print(f"C' = ({c_1_prime}, {c_2_prime}, {c_3_prime})")
print(f"c_2_prime_alt = {c_2_prime_alt}")
print(f"rho_1_prime = {rho_1_prime}")
print(f"rho_2_prime = {rho_2_prime}")
print("------------------")
r_11 = f_k_x * (p_11 - c_1_prime)
r_12 = f_k_y * (p_12 - c_2_prime)
r_13 = 1 * (p_13 - c_3_prime)
l_11 = rho_1_prime * u_1_prime
l_12 = rho_1_prime * v_1_prime
l_13 = rho_1_prime * 1
print(f"L: ({l_11}, {l_12}, {l_13})")
print(f"R: ({r_11}, {r_12}, {r_13})")
print("------------------")
r_21 = f_k_x * (p_21 - c_1_prime)
r_22 = f_k_y * (p_22 - c_2_prime)
r_23 = 1 * (p_23 - c_3_prime)
l_21 = rho_2_prime * u_2_prime
l_22 = rho_2_prime * v_2_prime
l_23 = rho_2_prime * 1
print(f"L: ({l_11}, {l_12}, {l_13})")
print(f"R: ({r_11}, {r_12}, {r_13})") | camera_width = 640
camera_height = 480
film_back_width = 1.417
film_back_height = 0.945
x_center = 320
y_center = 240
p_1 = (-0.023, -0.261, 2.376)
p_11 = P_1[0]
p_12 = P_1[1]
p_13 = P_1[2]
p_2 = (0.659, -0.071, 2.082)
p_21 = P_2[0]
p_22 = P_2[1]
p_23 = P_2[2]
p_1_prime = (52, 163)
x_1 = p_1_prime[0]
y_1 = p_1_prime[1]
p_2_prime = (218, 216)
x_2 = p_2_prime[0]
y_2 = p_2_prime[1]
f = 1.378
k_x = camera_width / film_back_width
k_y = camera_height / film_back_height
f_k_x = f
f_k_y = f
u_1_prime = (x_1 - x_center) / k_x
v_1_prime = (y_1 - y_center) / k_y
u_2_prime = (x_2 - x_center) / k_x
v_2_prime = (y_2 - y_center) / k_y
c_1_prime = (f_k_x * p_21 + (p_13 - p_23) * u_2_prime - u_2_prime / u_1_prime * f_k_x * p_11) / (f_k_x * (1 - u_2_prime / u_1_prime))
c_2_prime = (f_k_y * p_22 - (p_23 - (p_13 * u_1_prime - f_k_x * (p_11 - c_1_prime)) / u_1_prime) * v_2_prime) / f_k_y
c_2_prime_alt = (f_k_y * p_12 - (p_13 - (p_13 * u_1_prime - f_k_x * (p_11 - c_1_prime)) / u_1_prime) * v_1_prime) / f_k_y
c_3_prime = p_13 - f_k_x / u_1_prime * (p_11 - c_1_prime)
rho_1_prime = p_13 - c_3_prime
rho_2_prime = p_23 - c_3_prime
print(f"C' = ({c_1_prime}, {c_2_prime}, {c_3_prime})")
print(f'c_2_prime_alt = {c_2_prime_alt}')
print(f'rho_1_prime = {rho_1_prime}')
print(f'rho_2_prime = {rho_2_prime}')
print('------------------')
r_11 = f_k_x * (p_11 - c_1_prime)
r_12 = f_k_y * (p_12 - c_2_prime)
r_13 = 1 * (p_13 - c_3_prime)
l_11 = rho_1_prime * u_1_prime
l_12 = rho_1_prime * v_1_prime
l_13 = rho_1_prime * 1
print(f'L: ({l_11}, {l_12}, {l_13})')
print(f'R: ({r_11}, {r_12}, {r_13})')
print('------------------')
r_21 = f_k_x * (p_21 - c_1_prime)
r_22 = f_k_y * (p_22 - c_2_prime)
r_23 = 1 * (p_23 - c_3_prime)
l_21 = rho_2_prime * u_2_prime
l_22 = rho_2_prime * v_2_prime
l_23 = rho_2_prime * 1
print(f'L: ({l_11}, {l_12}, {l_13})')
print(f'R: ({r_11}, {r_12}, {r_13})') |
def main():
val=int(input("input a num"))
if val<10:
print("A")
elif val<20:
print("B")
elif val<30:
print("C")
else:
print("D")
main()
| def main():
val = int(input('input a num'))
if val < 10:
print('A')
elif val < 20:
print('B')
elif val < 30:
print('C')
else:
print('D')
main() |
__all__ = ['cross_validation',
'metrics',
'datasets',
'recommender']
| __all__ = ['cross_validation', 'metrics', 'datasets', 'recommender'] |
def is_leap(year):
leap=False
if year%400==0:
leap=True
elif year%4==0 and year%100!=0:
leap=True
else:
leap=False
return leap
year = int(input())
| def is_leap(year):
leap = False
if year % 400 == 0:
leap = True
elif year % 4 == 0 and year % 100 != 0:
leap = True
else:
leap = False
return leap
year = int(input()) |
"""Contains utility functions."""
BIN_MODE_ARGS = {'mode', 'buffering', }
TEXT_MODE_ARGS = {'mode', 'buffering', 'encoding', 'errors', 'newline'}
def split_args(args):
"""Splits args into two groups: open args and other args.
Open args are used by ``open`` function. Other args are used by
``load``/``dump`` functions.
Args:
args: Keyword args to split.
Returns:
open_args: Arguments for ``open``.
other_args: Arguments for ``load``/``dump``.
"""
mode_args = BIN_MODE_ARGS if 'b' in args['mode'] else TEXT_MODE_ARGS
open_args = {}
other_args = {}
for arg, value in args.items():
if arg in mode_args:
open_args[arg] = value
else:
other_args[arg] = value
return open_args, other_args
def read_wrapper(load, **base_kwargs):
"""Wraps ``load`` function to avoid context manager boilerplate.
Args:
load: Function that takes the return of ``open``.
**base_kwargs: Base arguments that ``open``/``load`` take.
Returns:
Wrapper for ``load``.
"""
def wrapped(file, **kwargs):
open_args, load_args = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
return load(f, **load_args)
return wrapped
def write_wrapper(dump, **base_kwargs):
"""Wraps ``dump`` function to avoid context manager boilerplate.
Args:
dump: Function that takes the return of ``open`` and data to dump.
**base_kwargs: Base arguments that ``open``/``dump`` take.
Returns:
Wrapper for ``dump``.
"""
def wrapped(file, obj, **kwargs):
open_args, dump_args = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
dump(obj, f, **dump_args)
return wrapped
| """Contains utility functions."""
bin_mode_args = {'mode', 'buffering'}
text_mode_args = {'mode', 'buffering', 'encoding', 'errors', 'newline'}
def split_args(args):
"""Splits args into two groups: open args and other args.
Open args are used by ``open`` function. Other args are used by
``load``/``dump`` functions.
Args:
args: Keyword args to split.
Returns:
open_args: Arguments for ``open``.
other_args: Arguments for ``load``/``dump``.
"""
mode_args = BIN_MODE_ARGS if 'b' in args['mode'] else TEXT_MODE_ARGS
open_args = {}
other_args = {}
for (arg, value) in args.items():
if arg in mode_args:
open_args[arg] = value
else:
other_args[arg] = value
return (open_args, other_args)
def read_wrapper(load, **base_kwargs):
"""Wraps ``load`` function to avoid context manager boilerplate.
Args:
load: Function that takes the return of ``open``.
**base_kwargs: Base arguments that ``open``/``load`` take.
Returns:
Wrapper for ``load``.
"""
def wrapped(file, **kwargs):
(open_args, load_args) = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
return load(f, **load_args)
return wrapped
def write_wrapper(dump, **base_kwargs):
"""Wraps ``dump`` function to avoid context manager boilerplate.
Args:
dump: Function that takes the return of ``open`` and data to dump.
**base_kwargs: Base arguments that ``open``/``dump`` take.
Returns:
Wrapper for ``dump``.
"""
def wrapped(file, obj, **kwargs):
(open_args, dump_args) = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
dump(obj, f, **dump_args)
return wrapped |
print("Press q to quit")
quit = False
while quit is False:
in_val = input("Please enter a positive integer.\n > ")
if in_val is 'q':
quit = True
elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0:
print("FizzBuzz")
elif int(in_val) % 5 == 0:
print("Buzz")
elif int(in_val) % 3 == 0:
print("Fizz")
else:
pass
| print('Press q to quit')
quit = False
while quit is False:
in_val = input('Please enter a positive integer.\n > ')
if in_val is 'q':
quit = True
elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0:
print('FizzBuzz')
elif int(in_val) % 5 == 0:
print('Buzz')
elif int(in_val) % 3 == 0:
print('Fizz')
else:
pass |