content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
load("//bazel/macros:toolchains.bzl", "parse_toolchain_file")
def _archive_rule(provider):
additional = ""
if provider.archive_opts != None:
additional = "\n strip_prefix = \"%s\"," % (provider.archive_opts)
return """
http_archive(
name = "{name}",
url = "{url}",
sha256 = "{sha256}",
build_file_content = OPEN_FILE_ARCHIVE, {kwargs}
)""".format(
name = provider.archive,
url = provider.urls[0],
sha256 = provider.sha256,
kwargs = additional,
)
def _toolchain_rules(provider):
return """toolchain(
name = "{name}",
exec_compatible_with = {exec_compatible_with},
target_compatible_with = {target_compatible_with},
toolchain = ":{info}",
toolchain_type = ":toolchain_type",
)
externally_managed_toolchain(
name = "{info}",
tool = "{tool}",
)
""".format(
name = provider.toolchain,
exec_compatible_with = provider.exec_compatible_with,
target_compatible_with = provider.target_compatible_with,
info = "{}info".format(provider.toolchain),
tool = provider.tool,
)
def _register_external_toolchain_impl(repository_ctx):
toolchain_path = repository_ctx.path(repository_ctx.attr.toolchain)
tool = parse_toolchain_file(repository_ctx, toolchain_path)
providers = tool.toolchains
toolchain_rules = []
tool_archive_rules = []
for provider in providers:
toolchain_rule = _toolchain_rules(provider)
toolchain_rules.append(toolchain_rule)
tool_archive_rule = _archive_rule(provider)
tool_archive_rules.append(tool_archive_rule)
repository_ctx.file(
"BUILD.bazel",
"""load("@bazel-external-toolchain-rules//bazel/macros:http_toolchain.bzl", "externally_managed_toolchain")
package(default_visibility = ["//visibility:public"])
toolchain_type(name = "toolchain_type")
{rules}
""".format(rules = "\n".join(toolchain_rules)),
)
repository_ctx.file(
"deps.bzl",
"""load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
OPEN_FILE_ARCHIVE = \"\"\"
package(default_visibility = ["//visibility:public"])
filegroup(
name = "files",
srcs = glob(["*","**/*"]),
)
\"\"\"
def install_toolchain():
native.register_toolchains(
{toolchains}
)
{rules}
""".format(
rules = "\n".join(tool_archive_rules),
toolchains = ",\n ".join([
'"@{}//:{}"'.format(repository_ctx.name, toolchain.toolchain)
for toolchain in providers
]),
),
)
register_external_toolchain = repository_rule(
_register_external_toolchain_impl,
attrs = {
"toolchain": attr.label(
mandatory = True,
allow_single_file = True,
),
},
)
ExternallyManagedToolExecutableInfo = provider(
doc = "Externally managed toolchain through use of file.",
fields = {"tool": ""},
)
def _externally_managed_toolchain_impl(ctx):
toolchain_info = platform_common.ToolchainInfo(
toolinfo = ExternallyManagedToolExecutableInfo(
tool = ctx.file.tool,
),
)
return [toolchain_info]
externally_managed_toolchain = rule(
implementation = _externally_managed_toolchain_impl,
attrs = {
"tool": attr.label(
executable = True,
allow_single_file = True,
mandatory = True,
cfg = "host",
),
},
)
|
load('//bazel/macros:toolchains.bzl', 'parse_toolchain_file')
def _archive_rule(provider):
additional = ''
if provider.archive_opts != None:
additional = '\n strip_prefix = "%s",' % provider.archive_opts
return '\n http_archive(\n name = "{name}",\n url = "{url}",\n sha256 = "{sha256}",\n build_file_content = OPEN_FILE_ARCHIVE, {kwargs}\n )'.format(name=provider.archive, url=provider.urls[0], sha256=provider.sha256, kwargs=additional)
def _toolchain_rules(provider):
return 'toolchain(\n name = "{name}",\n exec_compatible_with = {exec_compatible_with},\n target_compatible_with = {target_compatible_with},\n toolchain = ":{info}",\n toolchain_type = ":toolchain_type",\n)\n\nexternally_managed_toolchain(\n name = "{info}",\n tool = "{tool}",\n)\n'.format(name=provider.toolchain, exec_compatible_with=provider.exec_compatible_with, target_compatible_with=provider.target_compatible_with, info='{}info'.format(provider.toolchain), tool=provider.tool)
def _register_external_toolchain_impl(repository_ctx):
toolchain_path = repository_ctx.path(repository_ctx.attr.toolchain)
tool = parse_toolchain_file(repository_ctx, toolchain_path)
providers = tool.toolchains
toolchain_rules = []
tool_archive_rules = []
for provider in providers:
toolchain_rule = _toolchain_rules(provider)
toolchain_rules.append(toolchain_rule)
tool_archive_rule = _archive_rule(provider)
tool_archive_rules.append(tool_archive_rule)
repository_ctx.file('BUILD.bazel', 'load("@bazel-external-toolchain-rules//bazel/macros:http_toolchain.bzl", "externally_managed_toolchain")\n\npackage(default_visibility = ["//visibility:public"])\n\ntoolchain_type(name = "toolchain_type")\n\n{rules}\n'.format(rules='\n'.join(toolchain_rules)))
repository_ctx.file('deps.bzl', 'load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")\n\nOPEN_FILE_ARCHIVE = """\npackage(default_visibility = ["//visibility:public"])\nfilegroup(\n name = "files",\n srcs = glob(["*","**/*"]),\n)\n"""\n\ndef install_toolchain():\n native.register_toolchains(\n {toolchains}\n )\n{rules}\n'.format(rules='\n'.join(tool_archive_rules), toolchains=',\n '.join(['"@{}//:{}"'.format(repository_ctx.name, toolchain.toolchain) for toolchain in providers])))
register_external_toolchain = repository_rule(_register_external_toolchain_impl, attrs={'toolchain': attr.label(mandatory=True, allow_single_file=True)})
externally_managed_tool_executable_info = provider(doc='Externally managed toolchain through use of file.', fields={'tool': ''})
def _externally_managed_toolchain_impl(ctx):
toolchain_info = platform_common.ToolchainInfo(toolinfo=externally_managed_tool_executable_info(tool=ctx.file.tool))
return [toolchain_info]
externally_managed_toolchain = rule(implementation=_externally_managed_toolchain_impl, attrs={'tool': attr.label(executable=True, allow_single_file=True, mandatory=True, cfg='host')})
|
print('Hello my dear') #comments are essential but I am always to lazy
print ('what is your name?')
myName = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print ('what is your age?')
myAge = input ()
print('you will be ' + str(int(myAge) +1) +' in a year')
|
print('Hello my dear')
print('what is your name?')
my_name = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print('what is your age?')
my_age = input()
print('you will be ' + str(int(myAge) + 1) + ' in a year')
|
#encoding:utf-8
subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100)
|
subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100)
|
# exc. 7.1.4
def squared_numbers(start, stop):
while start <= stop:
print(start**2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == "__main__":
main()
|
def squared_numbers(start, stop):
while start <= stop:
print(start ** 2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == '__main__':
main()
|
lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
# Fazer o somatorio porposto pelo exercicio
for x in range(-50,51):
atual = numero + x
for j in range (0,atual):
area_2 += lado * (altura/(atual))
modulo_dif = abs(area_1 - area_2)
# Pegar o maior erro maximo
if erro_max < modulo_dif:
erro_max = modulo_dif
num = atual
# resetar o somatorio
area_2 = 0
print("n_max = {0:d}\nerro_maximo = {1:.14f}".format(num,erro_max))
|
lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
for x in range(-50, 51):
atual = numero + x
for j in range(0, atual):
area_2 += lado * (altura / atual)
modulo_dif = abs(area_1 - area_2)
if erro_max < modulo_dif:
erro_max = modulo_dif
num = atual
area_2 = 0
print('n_max = {0:d}\nerro_maximo = {1:.14f}'.format(num, erro_max))
|
# Important class
class ImportantClass:
def __init__(self, var):
# Instance variable
self.var = var
# Important function
def importantFunction(self, old_var, new_var):
return old_var + new_var
# Make users happy
def makeUsersHappy(self, users):
print("Success!")
|
class Importantclass:
def __init__(self, var):
self.var = var
def important_function(self, old_var, new_var):
return old_var + new_var
def make_users_happy(self, users):
print('Success!')
|
def en_even(r):
return r[0] == "en" and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == "en" and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0],r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtranspose)
nres = nxxt.reduce(np.add)
nxy = train.map(xy_scale)
nres2 = nxy.reduce(np.add)
nweights = np.dot(np.linalg.inv(nres), nres2.T)
# Make predictions on test with our train weights
pred = test.map(predict(nweights))
# Because we already filtered by code "en"
pred = pred.filter(lambda r: r[1] == "yahoo")
|
def en_even(r):
return r[0] == 'en' and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == 'en' and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0], r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtranspose)
nres = nxxt.reduce(np.add)
nxy = train.map(xy_scale)
nres2 = nxy.reduce(np.add)
nweights = np.dot(np.linalg.inv(nres), nres2.T)
pred = test.map(predict(nweights))
pred = pred.filter(lambda r: r[1] == 'yahoo')
|
rsa_key_data = [
"9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e27dd9e4d00d60910249db8d8559dd85f7ca59659ef400c8f6318700f4e97f0c6f4165de80641490433c88da8682befe68eb311f54af2b07d97ac74edb5399cf054764211694fbb8d1d333f3269f235abe025067f811ff83a2224826219b309ea3e6c968f42b3e52f245dc9",
"010001",
"b5ab7b159220b18e363258f61ebde08bae83d6ce2dbfe4adc143628c527887acde9de09bf9b49f438019004d71855f30c2d69b6c29bb9882ab641b3387409fe9199464a7faa4b5230c56d9e17cd9ed074bc00180ebed62bae3af28e6ff2ac2654ad968834c5d5c88f8d9d3cc5e167b10453b049d4e454a5761fb0ac717185907",
"dd2fffa9814296156a6926cd17b65564187e424dcadce9b032246ad7e46448bb0f9e0ff3c64f987424b1a40bc694e2e9ac4fb1930d163582d7acf20653a1c44b97846c1c5fd8a7b19bb225fb39c30e25410483deaf8c2538d222b748c4d8103b11cec04f666a5c0dbcbf5d5f625f158f65746c3fafe6418145f7cffa5fadeeaf"
]
|
rsa_key_data = ['9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e27dd9e4d00d60910249db8d8559dd85f7ca59659ef400c8f6318700f4e97f0c6f4165de80641490433c88da8682befe68eb311f54af2b07d97ac74edb5399cf054764211694fbb8d1d333f3269f235abe025067f811ff83a2224826219b309ea3e6c968f42b3e52f245dc9', '010001', 'b5ab7b159220b18e363258f61ebde08bae83d6ce2dbfe4adc143628c527887acde9de09bf9b49f438019004d71855f30c2d69b6c29bb9882ab641b3387409fe9199464a7faa4b5230c56d9e17cd9ed074bc00180ebed62bae3af28e6ff2ac2654ad968834c5d5c88f8d9d3cc5e167b10453b049d4e454a5761fb0ac717185907', 'dd2fffa9814296156a6926cd17b65564187e424dcadce9b032246ad7e46448bb0f9e0ff3c64f987424b1a40bc694e2e9ac4fb1930d163582d7acf20653a1c44b97846c1c5fd8a7b19bb225fb39c30e25410483deaf8c2538d222b748c4d8103b11cec04f666a5c0dbcbf5d5f625f158f65746c3fafe6418145f7cffa5fadeeaf']
|
def main():
data = open("day3/input.txt", "r")
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % (len(line))
if line[x] == "#":
tree_counter += 1
x += 3
print(tree_counter)
if __name__ == "__main__":
main()
|
def main():
data = open('day3/input.txt', 'r')
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % len(line)
if line[x] == '#':
tree_counter += 1
x += 3
print(tree_counter)
if __name__ == '__main__':
main()
|
iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1]
|
iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1]
|
# -*- coding: utf-8 -*-
"""
converters package.
"""
|
"""
converters package.
"""
|
{
'variables': { 'target_arch%': 'ia32', 'naclversion': '0.4.5' },
'targets': [
{
'target_name': 'sodium',
'sources': [
'sodium.cc',
],
"dependencies": [
"<(module_root_dir)/deps/libsodium.gyp:libsodium"
],
'include_dirs': [
'./deps/libsodium-<(naclversion)/src/libsodium/include'
],
'cflags!': [ '-fno-exceptions' ],
}
]
}
|
{'variables': {'target_arch%': 'ia32', 'naclversion': '0.4.5'}, 'targets': [{'target_name': 'sodium', 'sources': ['sodium.cc'], 'dependencies': ['<(module_root_dir)/deps/libsodium.gyp:libsodium'], 'include_dirs': ['./deps/libsodium-<(naclversion)/src/libsodium/include'], 'cflags!': ['-fno-exceptions']}]}
|
l, r = int(input()), int(input()) / 100
count = 1
result = 0
while True:
l = int(l*r)
if l <= 5:
break
result += (2**count)*l
count += 1
print(result)
|
(l, r) = (int(input()), int(input()) / 100)
count = 1
result = 0
while True:
l = int(l * r)
if l <= 5:
break
result += 2 ** count * l
count += 1
print(result)
|
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permuteUnique(self, nums):
if not nums:
return nums
res = {(nums[0],)}
for i in range(1, len(nums)):
tmp = set()
while res:
base = res.pop()
for j in range(len(base)+ 1):
tmp.add(tuple(base[:j]) + (nums[i],) + tuple(base[j:]))
res = tmp
return [ list(t) for t in res ]
# dic = {str([nums[0]]):1}
# res = [[nums[0]]]
# for i in range(1, len(nums)):
# for j in range(len(res)):
# base = res.pop(0)
# dic.pop(str(base))
# for k in range(len(base)+ 1):
# tmp = base[:k] + [nums[i]] + base[k:]
# if str(tmp) not in dic:
# res.append(base[:k] + [nums[i]] + base[k:])
# dic[str(tmp)] = 1
# return res
|
class Solution:
def permute_unique(self, nums):
if not nums:
return nums
res = {(nums[0],)}
for i in range(1, len(nums)):
tmp = set()
while res:
base = res.pop()
for j in range(len(base) + 1):
tmp.add(tuple(base[:j]) + (nums[i],) + tuple(base[j:]))
res = tmp
return [list(t) for t in res]
|
class Person:
'''
This class represents a person
'''
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return "University ID Number: " + self.id + "\nName: " + self.firstname + " " + self.lastname
def __repr__(self):
return self.firstname + " " + self.lastname
def get_salary(self):
return 0
class Student(Person):
'''
This class represents a Student
'''
def __init__(self, id, firstname, lastname, dob, start_year):
self.start_year = start_year
self.courses = []
# invoking the __init__ of the parent class
# Person.__init__(self, firstname, lastname, dob)
# or better call super()
super().__init__(id, firstname, lastname, dob)
def add_course(self, course_id):
self.courses.append(course_id)
def get_courses():
return self.courses
def __str__(self):
return super().__str__() + ". This student has the following courses on records: " + str(list(self.courses))
# A student has no salary.
def get_salary(self):
return 0
class Professor(Person):
'''
This class represents a Professor in the university system.
'''
def __init__(self, id, firstname, lastname, dob, hiring_year, salary):
self.hiring_year = hiring_year
self.salary = salary
self.courses = set()
self.research_projects = set()
super().__init__(id, firstname, lastname, dob)
def __str__(self):
return super().__str__() + ". This Professor is the instructor of record of following courses : " + str(
list(self.courses))
def add_course(self, course_id):
self.courses.add(course_id)
def add_courses(self, courses):
for course in courses:
self.courses.add(course)
def get_courses():
return self.courses
def get_salary(self):
return self.salary
class Staff(Person):
'''
This class represents a staff member.
'''
def __init__(self, id, firstname, lastname, dob, hiring_year, salary):
self.hiring_year = hiring_year
self.salary = salary
super().__init__(id, firstname, lastname, dob)
def __str__(self):
return super().__str__() + ". This Staff memeber has a salary of " + str(self.salary)
def get_salary(self):
return self.salary
class Teaching_Assistant(Staff, Student):
'''
A Teaching Assistant is a student and is a staff member.
'''
def __init__(self, id, firstname, lastname, dob, start_year, hiring_year, salary):
Student.__init__(self, id, firstname, lastname, dob, start_year)
self.hiring_year = hiring_year
self.salary = salary
# Staff().__init__(self, id, firstname, lastname, dob, hiring_year, salary)
def __str__(self):
return Student.__str__(self) + Staff.__str__(self)
|
class Person:
"""
This class represents a person
"""
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return 'University ID Number: ' + self.id + '\nName: ' + self.firstname + ' ' + self.lastname
def __repr__(self):
return self.firstname + ' ' + self.lastname
def get_salary(self):
return 0
class Student(Person):
"""
This class represents a Student
"""
def __init__(self, id, firstname, lastname, dob, start_year):
self.start_year = start_year
self.courses = []
super().__init__(id, firstname, lastname, dob)
def add_course(self, course_id):
self.courses.append(course_id)
def get_courses():
return self.courses
def __str__(self):
return super().__str__() + '. This student has the following courses on records: ' + str(list(self.courses))
def get_salary(self):
return 0
class Professor(Person):
"""
This class represents a Professor in the university system.
"""
def __init__(self, id, firstname, lastname, dob, hiring_year, salary):
self.hiring_year = hiring_year
self.salary = salary
self.courses = set()
self.research_projects = set()
super().__init__(id, firstname, lastname, dob)
def __str__(self):
return super().__str__() + '. This Professor is the instructor of record of following courses : ' + str(list(self.courses))
def add_course(self, course_id):
self.courses.add(course_id)
def add_courses(self, courses):
for course in courses:
self.courses.add(course)
def get_courses():
return self.courses
def get_salary(self):
return self.salary
class Staff(Person):
"""
This class represents a staff member.
"""
def __init__(self, id, firstname, lastname, dob, hiring_year, salary):
self.hiring_year = hiring_year
self.salary = salary
super().__init__(id, firstname, lastname, dob)
def __str__(self):
return super().__str__() + '. This Staff memeber has a salary of ' + str(self.salary)
def get_salary(self):
return self.salary
class Teaching_Assistant(Staff, Student):
"""
A Teaching Assistant is a student and is a staff member.
"""
def __init__(self, id, firstname, lastname, dob, start_year, hiring_year, salary):
Student.__init__(self, id, firstname, lastname, dob, start_year)
self.hiring_year = hiring_year
self.salary = salary
def __str__(self):
return Student.__str__(self) + Staff.__str__(self)
|
## CamelCase Method
## 6 kyu
## https://www.codewars.com//kata/587731fda577b3d1b0001196
def camel_case(string):
return ''.join([word.title() for word in string.split()])
|
def camel_case(string):
return ''.join([word.title() for word in string.split()])
|
#
# PySNMP MIB module Juniper-E2-Registry (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-E2-Registry
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
juniAdmin, = mibBuilder.importSymbols("Juniper-Registry", "juniAdmin")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Integer32, Unsigned32, ModuleIdentity, Bits, MibIdentifier, TimeTicks, ObjectIdentity, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Counter32, Counter64, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Integer32", "Unsigned32", "ModuleIdentity", "Bits", "MibIdentifier", "TimeTicks", "ObjectIdentity", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Counter32", "Counter64", "Gauge32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
juniE2Registry = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3))
juniE2Registry.setRevisions(('2004-05-19 17:42', '2003-08-18 20:27',))
if mibBuilder.loadTexts: juniE2Registry.setLastUpdated('200405191742Z')
if mibBuilder.loadTexts: juniE2Registry.setOrganization('Juniper Networks, Inc.')
juniE2EntPhysicalType = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1))
e2Chassis = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 1))
if mibBuilder.loadTexts: e2Chassis.setStatus('current')
e320Chassis = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 1, 1))
if mibBuilder.loadTexts: e320Chassis.setStatus('current')
e2FanAssembly = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2))
if mibBuilder.loadTexts: e2FanAssembly.setStatus('current')
e320PrimaryFanAssembly = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2, 1))
if mibBuilder.loadTexts: e320PrimaryFanAssembly.setStatus('current')
e320AuxiliaryFanAssembly = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2, 2))
if mibBuilder.loadTexts: e320AuxiliaryFanAssembly.setStatus('current')
e2PowerInput = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 3))
if mibBuilder.loadTexts: e2PowerInput.setStatus('current')
e320PowerDistributionModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 3, 1))
if mibBuilder.loadTexts: e320PowerDistributionModule.setStatus('current')
e2Midplane = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 4))
if mibBuilder.loadTexts: e2Midplane.setStatus('current')
e320Midplane = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 4, 1))
if mibBuilder.loadTexts: e320Midplane.setStatus('current')
e2SrpModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5))
if mibBuilder.loadTexts: e2SrpModule.setStatus('current')
e320Srp100Module = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5, 1))
if mibBuilder.loadTexts: e320Srp100Module.setStatus('current')
e320Srp320Module = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5, 99))
if mibBuilder.loadTexts: e320Srp320Module.setStatus('current')
e2SwitchFabricModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6))
if mibBuilder.loadTexts: e2SwitchFabricModule.setStatus('current')
e320FabricSlice100Module = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6, 1))
if mibBuilder.loadTexts: e320FabricSlice100Module.setStatus('current')
e320FabricSlice320Module = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6, 99))
if mibBuilder.loadTexts: e320FabricSlice320Module.setStatus('current')
e2SrpIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 7))
if mibBuilder.loadTexts: e2SrpIoa.setStatus('current')
e320SrpIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 7, 1))
if mibBuilder.loadTexts: e320SrpIoa.setStatus('current')
e2ForwardingModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8))
if mibBuilder.loadTexts: e2ForwardingModule.setStatus('current')
e3204gLeModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 1))
if mibBuilder.loadTexts: e3204gLeModule.setStatus('current')
e320Ge4PortModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 2))
if mibBuilder.loadTexts: e320Ge4PortModule.setStatus('current')
e320Oc48Pos1PortModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 3))
if mibBuilder.loadTexts: e320Oc48Pos1PortModule.setStatus('current')
e320Oc48RPos1PortModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 4))
if mibBuilder.loadTexts: e320Oc48RPos1PortModule.setStatus('current')
e320OcXModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 5))
if mibBuilder.loadTexts: e320OcXModule.setStatus('current')
e320MfgSerdesTestModule = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 99))
if mibBuilder.loadTexts: e320MfgSerdesTestModule.setStatus('current')
e2ForwardingIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9))
if mibBuilder.loadTexts: e2ForwardingIoa.setStatus('current')
e3204GeIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 1))
if mibBuilder.loadTexts: e3204GeIoa.setStatus('current')
e320Oc48PosIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 2))
if mibBuilder.loadTexts: e320Oc48PosIoa.setStatus('current')
e320Oc48RPosIoa = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 3))
if mibBuilder.loadTexts: e320Oc48RPosIoa.setStatus('current')
mibBuilder.exportSymbols("Juniper-E2-Registry", e320PrimaryFanAssembly=e320PrimaryFanAssembly, e320FabricSlice320Module=e320FabricSlice320Module, juniE2Registry=juniE2Registry, e320Midplane=e320Midplane, e2SrpIoa=e2SrpIoa, e320Srp100Module=e320Srp100Module, e2PowerInput=e2PowerInput, e3204GeIoa=e3204GeIoa, e2SwitchFabricModule=e2SwitchFabricModule, e320Oc48Pos1PortModule=e320Oc48Pos1PortModule, e320Srp320Module=e320Srp320Module, e320FabricSlice100Module=e320FabricSlice100Module, e320OcXModule=e320OcXModule, e320SrpIoa=e320SrpIoa, e320AuxiliaryFanAssembly=e320AuxiliaryFanAssembly, PYSNMP_MODULE_ID=juniE2Registry, e320PowerDistributionModule=e320PowerDistributionModule, e2FanAssembly=e2FanAssembly, e320Oc48RPosIoa=e320Oc48RPosIoa, e320Chassis=e320Chassis, e2Chassis=e2Chassis, e320Oc48RPos1PortModule=e320Oc48RPos1PortModule, e2ForwardingModule=e2ForwardingModule, e320MfgSerdesTestModule=e320MfgSerdesTestModule, e2SrpModule=e2SrpModule, e2ForwardingIoa=e2ForwardingIoa, e320Ge4PortModule=e320Ge4PortModule, juniE2EntPhysicalType=juniE2EntPhysicalType, e3204gLeModule=e3204gLeModule, e320Oc48PosIoa=e320Oc48PosIoa, e2Midplane=e2Midplane)
|
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint')
(juni_admin,) = mibBuilder.importSymbols('Juniper-Registry', 'juniAdmin')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, integer32, unsigned32, module_identity, bits, mib_identifier, time_ticks, object_identity, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, counter32, counter64, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Integer32', 'Unsigned32', 'ModuleIdentity', 'Bits', 'MibIdentifier', 'TimeTicks', 'ObjectIdentity', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Counter32', 'Counter64', 'Gauge32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
juni_e2_registry = module_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3))
juniE2Registry.setRevisions(('2004-05-19 17:42', '2003-08-18 20:27'))
if mibBuilder.loadTexts:
juniE2Registry.setLastUpdated('200405191742Z')
if mibBuilder.loadTexts:
juniE2Registry.setOrganization('Juniper Networks, Inc.')
juni_e2_ent_physical_type = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1))
e2_chassis = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 1))
if mibBuilder.loadTexts:
e2Chassis.setStatus('current')
e320_chassis = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 1, 1))
if mibBuilder.loadTexts:
e320Chassis.setStatus('current')
e2_fan_assembly = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2))
if mibBuilder.loadTexts:
e2FanAssembly.setStatus('current')
e320_primary_fan_assembly = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2, 1))
if mibBuilder.loadTexts:
e320PrimaryFanAssembly.setStatus('current')
e320_auxiliary_fan_assembly = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 2, 2))
if mibBuilder.loadTexts:
e320AuxiliaryFanAssembly.setStatus('current')
e2_power_input = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 3))
if mibBuilder.loadTexts:
e2PowerInput.setStatus('current')
e320_power_distribution_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 3, 1))
if mibBuilder.loadTexts:
e320PowerDistributionModule.setStatus('current')
e2_midplane = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 4))
if mibBuilder.loadTexts:
e2Midplane.setStatus('current')
e320_midplane = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 4, 1))
if mibBuilder.loadTexts:
e320Midplane.setStatus('current')
e2_srp_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5))
if mibBuilder.loadTexts:
e2SrpModule.setStatus('current')
e320_srp100_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5, 1))
if mibBuilder.loadTexts:
e320Srp100Module.setStatus('current')
e320_srp320_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 5, 99))
if mibBuilder.loadTexts:
e320Srp320Module.setStatus('current')
e2_switch_fabric_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6))
if mibBuilder.loadTexts:
e2SwitchFabricModule.setStatus('current')
e320_fabric_slice100_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6, 1))
if mibBuilder.loadTexts:
e320FabricSlice100Module.setStatus('current')
e320_fabric_slice320_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 6, 99))
if mibBuilder.loadTexts:
e320FabricSlice320Module.setStatus('current')
e2_srp_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 7))
if mibBuilder.loadTexts:
e2SrpIoa.setStatus('current')
e320_srp_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 7, 1))
if mibBuilder.loadTexts:
e320SrpIoa.setStatus('current')
e2_forwarding_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8))
if mibBuilder.loadTexts:
e2ForwardingModule.setStatus('current')
e3204g_le_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 1))
if mibBuilder.loadTexts:
e3204gLeModule.setStatus('current')
e320_ge4_port_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 2))
if mibBuilder.loadTexts:
e320Ge4PortModule.setStatus('current')
e320_oc48_pos1_port_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 3))
if mibBuilder.loadTexts:
e320Oc48Pos1PortModule.setStatus('current')
e320_oc48_r_pos1_port_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 4))
if mibBuilder.loadTexts:
e320Oc48RPos1PortModule.setStatus('current')
e320_oc_x_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 5))
if mibBuilder.loadTexts:
e320OcXModule.setStatus('current')
e320_mfg_serdes_test_module = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 8, 99))
if mibBuilder.loadTexts:
e320MfgSerdesTestModule.setStatus('current')
e2_forwarding_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9))
if mibBuilder.loadTexts:
e2ForwardingIoa.setStatus('current')
e3204_ge_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 1))
if mibBuilder.loadTexts:
e3204GeIoa.setStatus('current')
e320_oc48_pos_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 2))
if mibBuilder.loadTexts:
e320Oc48PosIoa.setStatus('current')
e320_oc48_r_pos_ioa = object_identity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3, 1, 9, 3))
if mibBuilder.loadTexts:
e320Oc48RPosIoa.setStatus('current')
mibBuilder.exportSymbols('Juniper-E2-Registry', e320PrimaryFanAssembly=e320PrimaryFanAssembly, e320FabricSlice320Module=e320FabricSlice320Module, juniE2Registry=juniE2Registry, e320Midplane=e320Midplane, e2SrpIoa=e2SrpIoa, e320Srp100Module=e320Srp100Module, e2PowerInput=e2PowerInput, e3204GeIoa=e3204GeIoa, e2SwitchFabricModule=e2SwitchFabricModule, e320Oc48Pos1PortModule=e320Oc48Pos1PortModule, e320Srp320Module=e320Srp320Module, e320FabricSlice100Module=e320FabricSlice100Module, e320OcXModule=e320OcXModule, e320SrpIoa=e320SrpIoa, e320AuxiliaryFanAssembly=e320AuxiliaryFanAssembly, PYSNMP_MODULE_ID=juniE2Registry, e320PowerDistributionModule=e320PowerDistributionModule, e2FanAssembly=e2FanAssembly, e320Oc48RPosIoa=e320Oc48RPosIoa, e320Chassis=e320Chassis, e2Chassis=e2Chassis, e320Oc48RPos1PortModule=e320Oc48RPos1PortModule, e2ForwardingModule=e2ForwardingModule, e320MfgSerdesTestModule=e320MfgSerdesTestModule, e2SrpModule=e2SrpModule, e2ForwardingIoa=e2ForwardingIoa, e320Ge4PortModule=e320Ge4PortModule, juniE2EntPhysicalType=juniE2EntPhysicalType, e3204gLeModule=e3204gLeModule, e320Oc48PosIoa=e320Oc48PosIoa, e2Midplane=e2Midplane)
|
#https://leetcode.com/problems/time-needed-to-inform-all-employees/
#Source: https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/532560/JavaC%2B%2BPython-DFS
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
children = [[] for i in range(n)]
for i, m in enumerate(manager):
if m >= 0: children[m].append(i)
def dfs(value):
"""
We have use "or [0]" to avoid ValueError: max() arg is an empty sequence return max( ) error for leaf nodes with no adjacent elements.
"""
return max( [dfs(i) for i in children[value]] or [0] )+informTime[value]
return dfs(headID)
|
class Solution:
def num_of_minutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
children = [[] for i in range(n)]
for (i, m) in enumerate(manager):
if m >= 0:
children[m].append(i)
def dfs(value):
"""
We have use "or [0]" to avoid ValueError: max() arg is an empty sequence return max( ) error for leaf nodes with no adjacent elements.
"""
return max([dfs(i) for i in children[value]] or [0]) + informTime[value]
return dfs(headID)
|
#validation of fields that are required
def validate_required(row, variable, metadata, formater,pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return:
"""
errors=[]
for fun in pre_checks:
if fun(row,variable,metadata)==False:
return errors
if metadata.get_is_required(variable) is True:
if row[variable] is None:
errors.append(formater(row, variable, error_type="Required", message="'{}' is required".format(metadata.get_label(variable))))
return errors
# validation of fields that are not required but have no entries
def validate_no_entry(row,variable,metadata,formater,pre_checks=[]):
errors=[]
for fun in pre_checks:
if fun(row,variable,metadata)==False:
return errors
if metadata.get_is_required(variable) is None:
if row[variable] == '':
errors.append(formater(row, variable, error_type="No entry", message="'{}' has no data!".format(metadata.get_label(variable))))
return errors
# validation of range
def validate_range(row, variable, metadata,formater,pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return: whether or not a value falls into the required range
"""
errors = []
for fun in pre_checks:
if fun(row,variable,metadata)==False:
return errors
l = row[variable]
if l is None:
return errors
if metadata.get_valid_range(variable) is not None:
min, max = metadata.get_valid_range(variable)
if(min is not None):
if (l<min): errors.append(formater(row, variable, error_type="is_below_minimum", message="'{}' is below minimum.".format(metadata.get_label(variable))))
if (max is not None):
if (l> max):errors.append(formater(row, variable, error_type="is_above_maximum", message="'{}' is above maximum.".format(metadata.get_label(variable))))
return errors
|
def validate_required(row, variable, metadata, formater, pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return:
"""
errors = []
for fun in pre_checks:
if fun(row, variable, metadata) == False:
return errors
if metadata.get_is_required(variable) is True:
if row[variable] is None:
errors.append(formater(row, variable, error_type='Required', message="'{}' is required".format(metadata.get_label(variable))))
return errors
def validate_no_entry(row, variable, metadata, formater, pre_checks=[]):
errors = []
for fun in pre_checks:
if fun(row, variable, metadata) == False:
return errors
if metadata.get_is_required(variable) is None:
if row[variable] == '':
errors.append(formater(row, variable, error_type='No entry', message="'{}' has no data!".format(metadata.get_label(variable))))
return errors
def validate_range(row, variable, metadata, formater, pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return: whether or not a value falls into the required range
"""
errors = []
for fun in pre_checks:
if fun(row, variable, metadata) == False:
return errors
l = row[variable]
if l is None:
return errors
if metadata.get_valid_range(variable) is not None:
(min, max) = metadata.get_valid_range(variable)
if min is not None:
if l < min:
errors.append(formater(row, variable, error_type='is_below_minimum', message="'{}' is below minimum.".format(metadata.get_label(variable))))
if max is not None:
if l > max:
errors.append(formater(row, variable, error_type='is_above_maximum', message="'{}' is above maximum.".format(metadata.get_label(variable))))
return errors
|
load("@bazel_skylib//lib:dicts.bzl", _dicts = "dicts")
load(
"//rules/scala_proto:private/core.bzl",
_scala_proto_library_implementation = "scala_proto_library_implementation",
_scala_proto_library_private_attributes = "scala_proto_library_private_attributes",
)
scala_proto_library = rule(
attrs = _dicts.add(
_scala_proto_library_private_attributes,
{
"deps": attr.label_list(
doc = "The proto_library targets you wish to generate Scala from",
providers = [ProtoInfo],
),
"_zipper": attr.label(cfg = "host", default = "@bazel_tools//tools/zip:zipper", executable = True),
},
),
doc = """
Generates Scala code from proto sources. The output is a `.srcjar` that can be passed into other rules for compilation.
See example use in [/tests/proto/BUILD](/tests/proto/BUILD)
""",
toolchains = [
"@rules_scala_annex//rules/scala_proto:compiler_toolchain_type",
],
outputs = {
"srcjar": "%{name}.srcjar",
},
implementation = _scala_proto_library_implementation,
)
def _scala_proto_toolchain_implementation(ctx):
return [platform_common.ToolchainInfo(
compiler = ctx.attr.compiler,
compiler_supports_workers = ctx.attr.compiler_supports_workers,
)]
scala_proto_toolchain = rule(
attrs = {
"compiler": attr.label(
doc = "The compiler to use to generate Scala form proto sources",
allow_files = True,
executable = True,
cfg = "host",
),
"compiler_supports_workers": attr.bool(default = False),
},
doc = """
Specifies a toolchain of the `@rules_scala_annex//rules/scala_proto:compiler_toolchain_type` toolchain type.
This rule should be used with an accompanying `toolchain` that binds it and specifies constraints
(See the official documentation for more info on [Bazel Toolchains](https://docs.bazel.build/versions/master/toolchains.html))
For example:
```python
scala_proto_toolchain(
name = "scalapb_toolchain_example",
compiler = ":worker",
compiler_supports_workers = True,
visibility = ["//visibility:public"],
)
toolchain(
name = "scalapb_toolchain_example_linux",
toolchain = ":scalapb_toolchain_example",
toolchain_type = "@rules_scala_annex//rules/scala_proto:compiler_toolchain_type",
exec_compatible_with = [
"@bazel_tools//platforms:linux",
"@bazel_tools//platforms:x86_64",
],
target_compatible_with = [
"@bazel_tools//platforms:linux",
"@bazel_tools//platforms:x86_64",
],
visibility = ["//visibility:public"],
)
```
""",
implementation = _scala_proto_toolchain_implementation,
)
|
load('@bazel_skylib//lib:dicts.bzl', _dicts='dicts')
load('//rules/scala_proto:private/core.bzl', _scala_proto_library_implementation='scala_proto_library_implementation', _scala_proto_library_private_attributes='scala_proto_library_private_attributes')
scala_proto_library = rule(attrs=_dicts.add(_scala_proto_library_private_attributes, {'deps': attr.label_list(doc='The proto_library targets you wish to generate Scala from', providers=[ProtoInfo]), '_zipper': attr.label(cfg='host', default='@bazel_tools//tools/zip:zipper', executable=True)}), doc='\nGenerates Scala code from proto sources. The output is a `.srcjar` that can be passed into other rules for compilation.\n\nSee example use in [/tests/proto/BUILD](/tests/proto/BUILD)\n', toolchains=['@rules_scala_annex//rules/scala_proto:compiler_toolchain_type'], outputs={'srcjar': '%{name}.srcjar'}, implementation=_scala_proto_library_implementation)
def _scala_proto_toolchain_implementation(ctx):
return [platform_common.ToolchainInfo(compiler=ctx.attr.compiler, compiler_supports_workers=ctx.attr.compiler_supports_workers)]
scala_proto_toolchain = rule(attrs={'compiler': attr.label(doc='The compiler to use to generate Scala form proto sources', allow_files=True, executable=True, cfg='host'), 'compiler_supports_workers': attr.bool(default=False)}, doc='\nSpecifies a toolchain of the `@rules_scala_annex//rules/scala_proto:compiler_toolchain_type` toolchain type.\n\nThis rule should be used with an accompanying `toolchain` that binds it and specifies constraints\n(See the official documentation for more info on [Bazel Toolchains](https://docs.bazel.build/versions/master/toolchains.html))\n\nFor example:\n\n```python\nscala_proto_toolchain(\n name = "scalapb_toolchain_example",\n compiler = ":worker",\n compiler_supports_workers = True,\n visibility = ["//visibility:public"],\n)\n\ntoolchain(\n name = "scalapb_toolchain_example_linux",\n toolchain = ":scalapb_toolchain_example",\n toolchain_type = "@rules_scala_annex//rules/scala_proto:compiler_toolchain_type",\n exec_compatible_with = [\n "@bazel_tools//platforms:linux",\n "@bazel_tools//platforms:x86_64",\n ],\n target_compatible_with = [\n "@bazel_tools//platforms:linux",\n "@bazel_tools//platforms:x86_64",\n ],\n visibility = ["//visibility:public"],\n)\n```\n', implementation=_scala_proto_toolchain_implementation)
|
# -*- coding: utf-8 -*-
class Scope(object):
"""
A base scope.
This indicates a permission access.
The `identifier` should be unique.
"""
identifier = None
def __init__(self, identifier):
self.identifier = identifier
def get_description(self):
return None
def __str__(self):
return "Base scope: {}".format(self.identifier)
|
class Scope(object):
"""
A base scope.
This indicates a permission access.
The `identifier` should be unique.
"""
identifier = None
def __init__(self, identifier):
self.identifier = identifier
def get_description(self):
return None
def __str__(self):
return 'Base scope: {}'.format(self.identifier)
|
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidSpecies(Error):
"""Species out of bounds of legitimate species"""
pass
class InvalidForm(Error):
"""Form is invalid"""
pass
class APIError(Error):
"""Something wrong with the API"""
pass
|
class Error(Exception):
"""Base class for other exceptions"""
pass
class Invalidspecies(Error):
"""Species out of bounds of legitimate species"""
pass
class Invalidform(Error):
"""Form is invalid"""
pass
class Apierror(Error):
"""Something wrong with the API"""
pass
|
class Solution:
def XXX(self, height: List[int]) -> int:
left = 0
right = len(height)-1
temp = 0
while left<right:
temp = max(temp,min(height[left],height[right])*(right-left))
if height[left] < height[right]:
left+=1
else:
right-=1
return temp
|
class Solution:
def xxx(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
temp = 0
while left < right:
temp = max(temp, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return temp
|
'''
core exception module
'''
class ConversionUnitNotImplemented(Exception):
'''
raises when tring can not convert a TemperatureUnit
'''
def __init__(self, unit_name: str):
super().__init__('Conversion unit %s not implemented' % unit_name)
|
"""
core exception module
"""
class Conversionunitnotimplemented(Exception):
"""
raises when tring can not convert a TemperatureUnit
"""
def __init__(self, unit_name: str):
super().__init__('Conversion unit %s not implemented' % unit_name)
|
line, k = input(), int(input())
iterator = line.__iter__()
iterators = zip(*([iterator] * k))
for word in iterators:
d = dict()
result = ''.join([d.setdefault(letter, letter) for letter in word if letter not in d])
print(result)
|
(line, k) = (input(), int(input()))
iterator = line.__iter__()
iterators = zip(*[iterator] * k)
for word in iterators:
d = dict()
result = ''.join([d.setdefault(letter, letter) for letter in word if letter not in d])
print(result)
|
e_h,K = map(int,input().split())
h,m,s,e_m,e_s,ans = 0,0,0,59,59,0
while e_h != h or e_m != m or e_s != s:
z = "%02d%02d%02d" % (h,m,s)
if z.count(str(K)) >0:
# print(z)
ans+=1
s+=1
if s==60:
m+=1
s=0
if m==60:
h+=1
m=0
z = "%02d%02d%02d" % (h,m,s)
if z.count(str(K)) >0:
ans+=1
print(ans)
|
(e_h, k) = map(int, input().split())
(h, m, s, e_m, e_s, ans) = (0, 0, 0, 59, 59, 0)
while e_h != h or e_m != m or e_s != s:
z = '%02d%02d%02d' % (h, m, s)
if z.count(str(K)) > 0:
ans += 1
s += 1
if s == 60:
m += 1
s = 0
if m == 60:
h += 1
m = 0
z = '%02d%02d%02d' % (h, m, s)
if z.count(str(K)) > 0:
ans += 1
print(ans)
|
"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
data = [2,4,5,6]
for i in data:
assert i%2 == 0, "{} is not an even number".format(i)
"""
"""
Please write a program which accepts basic mathematic expression from console and print the evaluation result.
Example: If the following n is given as input to the program:
35 + 3
Then, the output of the program should be:
38
expression = input()
ans = eval(expression)
print(ans)
"""
"""
Please write a binary search function which searches an item in a sorted list.
The function should return the index of element to be searched in the list.
def binary_search(lst, item):
low = 0
high = len(lst) - 1
while low <= high:
mid = round((low + high) / 2)
if lst[mid] == item:
return mid
elif lst[mid] > item:
high = mid - 1
else:
low = mid + 1
return None
lst = [1,3,5,7,]
print(binary_search(lst, 5))
"""
"""
Please generate a random float where the value is between 10 and 100 using Python module.
import random
print(random.random(10,100))
"""
"""
Please generate a random float where the value is between 5 and 95 using Python module.
import random
print(random.uniform(5,95))
"""
|
"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
data = [2,4,5,6]
for i in data:
assert i%2 == 0, "{} is not an even number".format(i)
"""
'\n\nPlease write a program which accepts basic mathematic expression from console and print the evaluation result.\n\nExample: If the following n is given as input to the program:\n\n 35 + 3\n\nThen, the output of the program should be:\n\n 38\n\nexpression = input()\nans = eval(expression)\nprint(ans)\n\n'
'\n\nPlease write a binary search function which searches an item in a sorted list.\nThe function should return the index of element to be searched in the list.\n\ndef binary_search(lst, item):\n low = 0\n high = len(lst) - 1\n\n while low <= high:\n mid = round((low + high) / 2)\n\n if lst[mid] == item:\n return mid\n elif lst[mid] > item:\n high = mid - 1\n else:\n low = mid + 1\n return None\n\nlst = [1,3,5,7,]\nprint(binary_search(lst, 5))\n\n'
'\n\nPlease generate a random float where the value is between 10 and 100 using Python module.\n\nimport random\n\nprint(random.random(10,100))\n\n'
'\n\nPlease generate a random float where the value is between 5 and 95 using Python module.\n\nimport random\n\nprint(random.uniform(5,95))\n\n'
|
# # 9608/22/PRE/O/N/2020
# The code below declares the variables and arrays that are supposed to be pre-populated.
ItemCode = ["1001", "6056", "5557", "2568", "4458"]
ItemDescription = ["Pencil", "Pen", "Notebook", "Ruler", "Compass"]
Price = [1.0, 10.0, 100.0, 20.0, 30.0]
NumberInStock = [100, 100, 50, 20, 20]
n = len(ItemCode)
# ## TASK 1.4
# Write program code to produce a report displaying all the information stored about each item for which the number in stock is below a given level. The planning and identifier table are in the pasudocode file and the markdown respectively.
ThresholdLevel = int(input("Enter the minumum stock level: "))
for Counter in range(n):
if NumberInStock[Counter] < ThresholdLevel:
print("\nItem Code:", ItemCode[Counter])
print("Item Description:", ItemDescription[Counter])
print("Price:", Price[Counter])
print("Number in stock:", NumberInStock[Counter])
# ## TASK 2.2
# Design an algorithm to input the four pieces of data about a stock item, form a string according to your format design, and write the string to the text file. <br> First draw a program flowchart, then write the equivalent pseudocode.
RecordsFile = "Item Records.txt"
FileObject = open(RecordsFile, "a+")
WriteString = ""
NewItemCode = int(input("\nEnter item code: "))
WriteString = ':' + str(NewItemCode)
NewItemDescription = input("Enter item description: ")
WriteString += ':' + NewItemDescription
NewPrice = float(input("Enter new price: "))
WriteString += ':' + str(NewPrice)
NewNumberInStock = int(input("Enter the number of items in stock: "))
WriteString += ':' + str(NewNumberInStock) + '\n'
FileObject.write(WriteString)
FileObject.close()
# ## TASK 2.4
# The code below defines the sub-routines which will be used by more than of the tasks.
def GetItemCode():
TestItemCode = int(input("Enter the code of the item: "))
while not (TestItemCode > 1000 and TestItemCode < 9999):
TestItemCode = int(input("Re-enter the code of the item: "))
return TestItemCode
def GetNumberInStock():
TestNumberInStock = int(input("Enter the number of the item in stock: "))
while not (TestNumberInStock >= 0):
TestNumberInStock = int(input("Re-enter the number of the item in stock: "))
return TestNumberInStock
def GetPrice():
TestPrice = float(input("Enter the price of the item: "))
while not (TestPrice >= 0):
TestPrice = float(input("Re-enter the price of the item: "))
return TestPrice
def ExtractDetails(RecordString, Details):
Position = 0
SearchString = RecordString.strip() + ':'
if RecordString != "":
for Counter in range(4):
Position += 1
CurrentCharacter = SearchString[Position : Position + 1]
while CurrentCharacter != ':':
Details[Counter] += CurrentCharacter
Position += 1
CurrentCharacter = SearchString[Position : Position + 1]
print ("")
# ## TASK 2.4 (1)
# Add a new stock item to the text file. Include validation of the different pieces of information as appropriate. For example item code data may be a fixed format.
WriteString = ""
WriteString = ':' + str(GetItemCode())
NewItemDescription = input("Enter item description: ")
WriteString += ':' + NewItemDescription
WriteString += ':' + str(GetPrice())
WriteString += ':' + str(GetNumberInStock()) + '\n'
FileObject = open(RecordsFile, "a+")
FileObject.write(WriteString)
FileObject.close()
# ## TASK 2.4 (2)
# Search for a stock item with a specific item code. Output the other pieces of data together with suitable supporting text.
Found = False
CurrentRecord = ""
print("\nEnter the code of the item you want to search for.")
DesiredItemCode = GetItemCode()
FileObject = open(RecordsFile, "r+")
FileData = FileObject.readlines()
FileObject.close()
for record in FileData:
CurrentRecord = record
if CurrentRecord[1:5] == str(DesiredItemCode):
Found = True
break
if Found:
DetailsOfRecord = ["" for i in range(4)]
ExtractDetails(CurrentRecord, DetailsOfRecord)
print("\nItem Code: " + str(DetailsOfRecord[0]))
print("Item Description: " + DetailsOfRecord[1])
print("Price of item: " + str(DetailsOfRecord[2]))
print("Number of the item in stock: " + str(DetailsOfRecord[3]))
else:
print("Item not found.")
# ## TASK 2.4 (3)
# Search for all stock items with a specific item description, with output as for task 2.
DesiredItemDescription = input("\nEnter the description of the item you want to search for: ")
FileObject = open(RecordsFile, "r+")
FileData = FileObject.readlines()
FileObject.close()
for record in FileData:
DetailsOfRecord = ["" for i in range(4)]
ExtractDetails(record, DetailsOfRecord)
if DetailsOfRecord[1] == DesiredItemDescription:
print("\nItem Code: " + str(DetailsOfRecord[0]))
print("Item Description: " + DetailsOfRecord[1])
print("Price of item: " + str(DetailsOfRecord[2]))
print("Number of the item in stock: " + str(DetailsOfRecord[3]))
# ## TASK 2.4 (4)
# Output a list of all stock items with a price greater than a given amount.
print ("\nEnter the maximum threshold price.")
ThresholdPrice = GetPrice()
FileObject = open(RecordsFile, "r+")
FileData = FileObject.readlines()
FileObject.close()
30
for record in FileData:
DetailsOfRecord = ["" for i in range(4)]
ExtractDetails(record, DetailsOfRecord)
if float(DetailsOfRecord[2]) < ThresholdPrice:
print("\nItem Code: " + str(DetailsOfRecord[0]))
print("Item Description: " + DetailsOfRecord[1])
print("Price of item: " + str(DetailsOfRecord[2]))
print("Number of the item in stock: " + str(DetailsOfRecord[3]))
|
item_code = ['1001', '6056', '5557', '2568', '4458']
item_description = ['Pencil', 'Pen', 'Notebook', 'Ruler', 'Compass']
price = [1.0, 10.0, 100.0, 20.0, 30.0]
number_in_stock = [100, 100, 50, 20, 20]
n = len(ItemCode)
threshold_level = int(input('Enter the minumum stock level: '))
for counter in range(n):
if NumberInStock[Counter] < ThresholdLevel:
print('\nItem Code:', ItemCode[Counter])
print('Item Description:', ItemDescription[Counter])
print('Price:', Price[Counter])
print('Number in stock:', NumberInStock[Counter])
records_file = 'Item Records.txt'
file_object = open(RecordsFile, 'a+')
write_string = ''
new_item_code = int(input('\nEnter item code: '))
write_string = ':' + str(NewItemCode)
new_item_description = input('Enter item description: ')
write_string += ':' + NewItemDescription
new_price = float(input('Enter new price: '))
write_string += ':' + str(NewPrice)
new_number_in_stock = int(input('Enter the number of items in stock: '))
write_string += ':' + str(NewNumberInStock) + '\n'
FileObject.write(WriteString)
FileObject.close()
def get_item_code():
test_item_code = int(input('Enter the code of the item: '))
while not (TestItemCode > 1000 and TestItemCode < 9999):
test_item_code = int(input('Re-enter the code of the item: '))
return TestItemCode
def get_number_in_stock():
test_number_in_stock = int(input('Enter the number of the item in stock: '))
while not TestNumberInStock >= 0:
test_number_in_stock = int(input('Re-enter the number of the item in stock: '))
return TestNumberInStock
def get_price():
test_price = float(input('Enter the price of the item: '))
while not TestPrice >= 0:
test_price = float(input('Re-enter the price of the item: '))
return TestPrice
def extract_details(RecordString, Details):
position = 0
search_string = RecordString.strip() + ':'
if RecordString != '':
for counter in range(4):
position += 1
current_character = SearchString[Position:Position + 1]
while CurrentCharacter != ':':
Details[Counter] += CurrentCharacter
position += 1
current_character = SearchString[Position:Position + 1]
print('')
write_string = ''
write_string = ':' + str(get_item_code())
new_item_description = input('Enter item description: ')
write_string += ':' + NewItemDescription
write_string += ':' + str(get_price())
write_string += ':' + str(get_number_in_stock()) + '\n'
file_object = open(RecordsFile, 'a+')
FileObject.write(WriteString)
FileObject.close()
found = False
current_record = ''
print('\nEnter the code of the item you want to search for.')
desired_item_code = get_item_code()
file_object = open(RecordsFile, 'r+')
file_data = FileObject.readlines()
FileObject.close()
for record in FileData:
current_record = record
if CurrentRecord[1:5] == str(DesiredItemCode):
found = True
break
if Found:
details_of_record = ['' for i in range(4)]
extract_details(CurrentRecord, DetailsOfRecord)
print('\nItem Code: ' + str(DetailsOfRecord[0]))
print('Item Description: ' + DetailsOfRecord[1])
print('Price of item: ' + str(DetailsOfRecord[2]))
print('Number of the item in stock: ' + str(DetailsOfRecord[3]))
else:
print('Item not found.')
desired_item_description = input('\nEnter the description of the item you want to search for: ')
file_object = open(RecordsFile, 'r+')
file_data = FileObject.readlines()
FileObject.close()
for record in FileData:
details_of_record = ['' for i in range(4)]
extract_details(record, DetailsOfRecord)
if DetailsOfRecord[1] == DesiredItemDescription:
print('\nItem Code: ' + str(DetailsOfRecord[0]))
print('Item Description: ' + DetailsOfRecord[1])
print('Price of item: ' + str(DetailsOfRecord[2]))
print('Number of the item in stock: ' + str(DetailsOfRecord[3]))
print('\nEnter the maximum threshold price.')
threshold_price = get_price()
file_object = open(RecordsFile, 'r+')
file_data = FileObject.readlines()
FileObject.close()
30
for record in FileData:
details_of_record = ['' for i in range(4)]
extract_details(record, DetailsOfRecord)
if float(DetailsOfRecord[2]) < ThresholdPrice:
print('\nItem Code: ' + str(DetailsOfRecord[0]))
print('Item Description: ' + DetailsOfRecord[1])
print('Price of item: ' + str(DetailsOfRecord[2]))
print('Number of the item in stock: ' + str(DetailsOfRecord[3]))
|
def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return fields
for comp in comps:
if isinstance(comp, str):
fields.append(comp)
else:
fields.extend(discover_fields(comp))
return fields
|
def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return fields
for comp in comps:
if isinstance(comp, str):
fields.append(comp)
else:
fields.extend(discover_fields(comp))
return fields
|
# 4.04 Lists
# Purpose: learning how to use lists
#
# Author@ Shawn Velsor
# Date: 1/8/2021
electronics = ["computer", "cellphone", "laptop", "headphones"]
mutualItem = False
print("Hello, these are the items I like:")
count = 1
for i in electronics:
print(str(count) + ".", i)
count += 1
print()
def main():
item = input("What type of electronic device do you like? ").lower()
for i in electronics:
if(item == i):
print("Same, I like " + item + " also.")
mutualItem = True
if(mutualItem == False):
print("Oh, that's something I don't like...")
while True:
main()
|
electronics = ['computer', 'cellphone', 'laptop', 'headphones']
mutual_item = False
print('Hello, these are the items I like:')
count = 1
for i in electronics:
print(str(count) + '.', i)
count += 1
print()
def main():
item = input('What type of electronic device do you like? ').lower()
for i in electronics:
if item == i:
print('Same, I like ' + item + ' also.')
mutual_item = True
if mutualItem == False:
print("Oh, that's something I don't like...")
while True:
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Peter Mounce <public@neverrunwithscissors.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_webpicmd
version_added: "2.0"
short_description: Installs packages using Web Platform Installer command-line
description:
- Installs packages using Web Platform Installer command-line (http://www.iis.net/learn/install/web-platform-installer/web-platform-installer-v4-command-line-webpicmdexe-rtw-release).
- Must be installed and present in PATH (see win_chocolatey module; 'webpicmd' is the package name, and you must install 'lessmsi' first too)
- Install IIS first (see win_feature module)
notes:
- accepts EULAs and suppresses reboot - you will need to check manage reboots yourself (see win_reboot module)
options:
name:
description:
- Name of the package to be installed
required: true
author: Peter Mounce
'''
EXAMPLES = r'''
# Install URLRewrite2.
win_webpicmd:
name: URLRewrite2
'''
|
ansible_metadata = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'}
documentation = '\n---\nmodule: win_webpicmd\nversion_added: "2.0"\nshort_description: Installs packages using Web Platform Installer command-line\ndescription:\n - Installs packages using Web Platform Installer command-line (http://www.iis.net/learn/install/web-platform-installer/web-platform-installer-v4-command-line-webpicmdexe-rtw-release).\n - Must be installed and present in PATH (see win_chocolatey module; \'webpicmd\' is the package name, and you must install \'lessmsi\' first too)\n - Install IIS first (see win_feature module)\nnotes:\n - accepts EULAs and suppresses reboot - you will need to check manage reboots yourself (see win_reboot module)\noptions:\n name:\n description:\n - Name of the package to be installed\n required: true\nauthor: Peter Mounce\n'
examples = '\n # Install URLRewrite2.\n win_webpicmd:\n name: URLRewrite2\n'
|
# ==== PATHS ===================
PATH_TO_DATASET = "houseprice.csv"
OUTPUT_SCALER_PATH = 'scaler.pkl'
OUTPUT_MODEL_PATH = 'lasso_regression.pkl'
# ======= PARAMETERS ===============
# imputation parameters
LOTFRONTAGE_MODE = 60
# encoding parameters
FREQUENT_LABELS = {
'MSZoning': ['FV', 'RH', 'RL', 'RM'],
'Neighborhood': ['Blmngtn', 'BrDale', 'BrkSide', 'ClearCr', 'CollgCr',
'Crawfor', 'Edwards', 'Gilbert', 'IDOTRR', 'MeadowV',
'Mitchel', 'NAmes', 'NWAmes', 'NoRidge', 'NridgHt',
'OldTown', 'SWISU', 'Sawyer', 'SawyerW', 'Somerst',
'StoneBr', 'Timber'],
'RoofStyle': ['Gable', 'Hip'],
'MasVnrType': ['BrkFace', 'None', 'Stone'],
'BsmtQual': ['Ex', 'Fa', 'Gd', 'Missing', 'TA'],
'BsmtExposure': ['Av', 'Gd', 'Missing', 'Mn', 'No'],
'HeatingQC': ['Ex', 'Fa', 'Gd', 'TA'],
'CentralAir': ['N', 'Y'],
'KitchenQual': ['Ex', 'Fa', 'Gd', 'TA'],
'FireplaceQu': ['Ex', 'Fa', 'Gd', 'Missing', 'Po', 'TA'],
'GarageType': ['Attchd', 'Basment', 'BuiltIn', 'Detchd', 'Missing'],
'GarageFinish': ['Fin', 'Missing', 'RFn', 'Unf'],
'PavedDrive': ['N', 'P', 'Y']}
ENCODING_MAPPINGS = {'MSZoning': {'Rare': 0, 'RM': 1, 'RH': 2, 'RL': 3, 'FV': 4},
'Neighborhood': {'IDOTRR': 0, 'MeadowV': 1, 'BrDale': 2, 'Edwards': 3,
'BrkSide': 4, 'OldTown': 5, 'Sawyer': 6, 'SWISU': 7, 'NAmes': 8,
'Mitchel': 9, 'SawyerW': 10, 'Rare': 11, 'NWAmes': 12, 'Gilbert': 13,
'Blmngtn': 14, 'CollgCr': 15, 'Crawfor': 16, 'ClearCr': 17, 'Somerst': 18,
'Timber': 19, 'StoneBr': 20, 'NridgHt': 21, 'NoRidge': 22},
'RoofStyle': {'Gable': 0, 'Rare': 1, 'Hip': 2},
'MasVnrType': {'None': 0, 'Rare': 1, 'BrkFace': 2, 'Stone': 3},
'BsmtQual': {'Missing': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4},
'BsmtExposure': {'Missing': 0, 'No': 1, 'Mn': 2, 'Av': 3, 'Gd': 4},
'HeatingQC': {'Rare': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4},
'CentralAir': {'N': 0, 'Y': 1},
'KitchenQual': {'Fa': 0, 'TA': 1, 'Gd': 2, 'Ex': 3},
'FireplaceQu': {'Po': 0, 'Missing': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5},
'GarageType': {'Missing': 0, 'Rare': 1, 'Detchd': 2, 'Basment': 3, 'Attchd': 4, 'BuiltIn': 5},
'GarageFinish': {'Missing': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3},
'PavedDrive': {'N': 0, 'P': 1, 'Y': 2}}
# ======= FEATURE GROUPS =============
# variable groups for engineering steps
TARGET = 'SalePrice'
CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure',
'FireplaceQu', 'GarageType', 'GarageFinish']
NUMERICAL_TO_IMPUTE = 'LotFrontage'
YEAR_VARIABLE = 'YearRemodAdd'
# variables to transofmr
NUMERICAL_LOG = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']
# variables to encode
CATEGORICAL_ENCODE = ['MSZoning', 'Neighborhood', 'RoofStyle',
'MasVnrType', 'BsmtQual', 'BsmtExposure',
'HeatingQC', 'CentralAir', 'KitchenQual',
'FireplaceQu', 'GarageType', 'GarageFinish',
'PavedDrive']
# selected features for training
FEATURES = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual',
'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType',
'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir',
'1stFlrSF', 'GrLivArea', 'BsmtFullBath', 'KitchenQual',
'Fireplaces', 'FireplaceQu', 'GarageType', 'GarageFinish',
'GarageCars', 'PavedDrive', 'LotFrontage']
|
path_to_dataset = 'houseprice.csv'
output_scaler_path = 'scaler.pkl'
output_model_path = 'lasso_regression.pkl'
lotfrontage_mode = 60
frequent_labels = {'MSZoning': ['FV', 'RH', 'RL', 'RM'], 'Neighborhood': ['Blmngtn', 'BrDale', 'BrkSide', 'ClearCr', 'CollgCr', 'Crawfor', 'Edwards', 'Gilbert', 'IDOTRR', 'MeadowV', 'Mitchel', 'NAmes', 'NWAmes', 'NoRidge', 'NridgHt', 'OldTown', 'SWISU', 'Sawyer', 'SawyerW', 'Somerst', 'StoneBr', 'Timber'], 'RoofStyle': ['Gable', 'Hip'], 'MasVnrType': ['BrkFace', 'None', 'Stone'], 'BsmtQual': ['Ex', 'Fa', 'Gd', 'Missing', 'TA'], 'BsmtExposure': ['Av', 'Gd', 'Missing', 'Mn', 'No'], 'HeatingQC': ['Ex', 'Fa', 'Gd', 'TA'], 'CentralAir': ['N', 'Y'], 'KitchenQual': ['Ex', 'Fa', 'Gd', 'TA'], 'FireplaceQu': ['Ex', 'Fa', 'Gd', 'Missing', 'Po', 'TA'], 'GarageType': ['Attchd', 'Basment', 'BuiltIn', 'Detchd', 'Missing'], 'GarageFinish': ['Fin', 'Missing', 'RFn', 'Unf'], 'PavedDrive': ['N', 'P', 'Y']}
encoding_mappings = {'MSZoning': {'Rare': 0, 'RM': 1, 'RH': 2, 'RL': 3, 'FV': 4}, 'Neighborhood': {'IDOTRR': 0, 'MeadowV': 1, 'BrDale': 2, 'Edwards': 3, 'BrkSide': 4, 'OldTown': 5, 'Sawyer': 6, 'SWISU': 7, 'NAmes': 8, 'Mitchel': 9, 'SawyerW': 10, 'Rare': 11, 'NWAmes': 12, 'Gilbert': 13, 'Blmngtn': 14, 'CollgCr': 15, 'Crawfor': 16, 'ClearCr': 17, 'Somerst': 18, 'Timber': 19, 'StoneBr': 20, 'NridgHt': 21, 'NoRidge': 22}, 'RoofStyle': {'Gable': 0, 'Rare': 1, 'Hip': 2}, 'MasVnrType': {'None': 0, 'Rare': 1, 'BrkFace': 2, 'Stone': 3}, 'BsmtQual': {'Missing': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, 'BsmtExposure': {'Missing': 0, 'No': 1, 'Mn': 2, 'Av': 3, 'Gd': 4}, 'HeatingQC': {'Rare': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, 'CentralAir': {'N': 0, 'Y': 1}, 'KitchenQual': {'Fa': 0, 'TA': 1, 'Gd': 2, 'Ex': 3}, 'FireplaceQu': {'Po': 0, 'Missing': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, 'GarageType': {'Missing': 0, 'Rare': 1, 'Detchd': 2, 'Basment': 3, 'Attchd': 4, 'BuiltIn': 5}, 'GarageFinish': {'Missing': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3}, 'PavedDrive': {'N': 0, 'P': 1, 'Y': 2}}
target = 'SalePrice'
categorical_to_impute = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish']
numerical_to_impute = 'LotFrontage'
year_variable = 'YearRemodAdd'
numerical_log = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']
categorical_encode = ['MSZoning', 'Neighborhood', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', 'KitchenQual', 'FireplaceQu', 'GarageType', 'GarageFinish', 'PavedDrive']
features = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual', 'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', '1stFlrSF', 'GrLivArea', 'BsmtFullBath', 'KitchenQual', 'Fireplaces', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageCars', 'PavedDrive', 'LotFrontage']
|
__title__ = 'plinn'
__description__ = "Partition Like It's 1999"
__url__ = 'https://github.com/giannitedesco/plinn'
__author__ = 'Gianni Tedesco'
__author_email__ = 'gianni@scaramanga.co.uk'
__copyright__ = 'Copyright 2020 Gianni Tedesco'
__license__ = 'Apache 2.0'
__version__ = '0.0.2'
|
__title__ = 'plinn'
__description__ = "Partition Like It's 1999"
__url__ = 'https://github.com/giannitedesco/plinn'
__author__ = 'Gianni Tedesco'
__author_email__ = 'gianni@scaramanga.co.uk'
__copyright__ = 'Copyright 2020 Gianni Tedesco'
__license__ = 'Apache 2.0'
__version__ = '0.0.2'
|
# 2. Write Python code to find the cost of the minimum-energy seam in a list of lists.
energies = [[24, 22, 30, 15, 18, 19],
[12, 23, 15, 23, 10, 15],
[11, 13, 22, 13, 21, 14],
[13, 15, 17, 28, 19, 21],
[17, 17, 7, 27, 20, 19]]
energies2 = [[24, 22, 30, 15, 18, 19],
[12, 23, 15, 23, 10, 15],
[11, 13, 22, 13, 21, 14],
[13, 15, 17, 28, 19, 21],
[17, 17, 29, 27, 20, 19]]
# The correct output for the given energies data is 15+10+13+17+7 = 62.
def min_energy(energies):
cost = []
for i in range(len(energies)):
cost.append([0]*len(energies[0]))
for i in range(len(energies[0])):
cost[0][i] = energies[0][i]
for i in range(1, len(energies)):
for j in range(len(energies[0])):
if j == 0:
cost[i][j] = energies[i][j] + min(cost[i-1][j], cost[i-1][j+1])
elif j == len(energies[0]) - 1:
cost[i][j] = energies[i][j] + min(cost[i-1][j], cost[i-1][j-1])
else:
cost[i][j] = energies[i][j] + min(cost[i-1][j-1], cost[i-1][j], cost[i-1][j+1])
for i in range(len(cost)):
print(cost[i])
return min(cost[-1])
min_energy(energies)
|
energies = [[24, 22, 30, 15, 18, 19], [12, 23, 15, 23, 10, 15], [11, 13, 22, 13, 21, 14], [13, 15, 17, 28, 19, 21], [17, 17, 7, 27, 20, 19]]
energies2 = [[24, 22, 30, 15, 18, 19], [12, 23, 15, 23, 10, 15], [11, 13, 22, 13, 21, 14], [13, 15, 17, 28, 19, 21], [17, 17, 29, 27, 20, 19]]
def min_energy(energies):
cost = []
for i in range(len(energies)):
cost.append([0] * len(energies[0]))
for i in range(len(energies[0])):
cost[0][i] = energies[0][i]
for i in range(1, len(energies)):
for j in range(len(energies[0])):
if j == 0:
cost[i][j] = energies[i][j] + min(cost[i - 1][j], cost[i - 1][j + 1])
elif j == len(energies[0]) - 1:
cost[i][j] = energies[i][j] + min(cost[i - 1][j], cost[i - 1][j - 1])
else:
cost[i][j] = energies[i][j] + min(cost[i - 1][j - 1], cost[i - 1][j], cost[i - 1][j + 1])
for i in range(len(cost)):
print(cost[i])
return min(cost[-1])
min_energy(energies)
|
mqtt_host = "IP_OR_DOMAIN"
mqtt_port = 1883
mqtt_topic = "screen/rpi"
mqtt_username = "USERNAME"
mqtt_password = "PASSWORD"
# Raspberry Pi
power_on_command = "vcgencmd display_power 1"
power_off_command = "vcgencmd display_power 0"
# Other HDMI linux devices
# power_on_command = "xset -display :0 dpms force on"
# power_off_command = "xset -display :0 dpms force off"
|
mqtt_host = 'IP_OR_DOMAIN'
mqtt_port = 1883
mqtt_topic = 'screen/rpi'
mqtt_username = 'USERNAME'
mqtt_password = 'PASSWORD'
power_on_command = 'vcgencmd display_power 1'
power_off_command = 'vcgencmd display_power 0'
|
"""
Implements mainly the Vector class. See its documentation.
"""
class VectorError(Exception):
"""
An exception to use with Vector
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.value)
class Vector(tuple):
"""
A vector.
"""
def __init__(self,seq):
tuple.__init__(seq)
def __add__(self, other):
if not(isinstance(other,Vector)):
raise VectorError("right hand side is not a Vector")
return Vector(map(lambda x,y: x+y, self, other))
def __neg__(self):
return Vector(map(lambda x: -x, self))
def __pos__(self):
return self
def __sub__(self, other):
return Vector(map(lambda x,y: x-y, self, other))
def __mul__(self, other):
if not(isinstance(other,int) or isinstance(other,float)):
raise VectorError("right hand side is illegal")
return Vector(map(lambda x: x*other, self))
def __rmul__(self, other):
return (self*other)
def __div__(self, other):
if not(isinstance(other,int) or isinstance(other,float)):
raise VectorError("right hand side is illegal")
return Vector(map(lambda x: x/other, self))
def __rdiv__(self, other):
raise VectorError("you sick pervert! you tried to divide something by a vector!")
def __and__(self,other):
"""
this is a dot product, done like this: a&b
must use () around it because of fucked up operator precedence.
"""
if not(isinstance(other,Vector)):
raise VectorError("trying to do dot product of Vector with non-Vector")
"""
if self.dim()!=other.dim():
raise("trying to do dot product of Vectors of unequal dimension!")
"""
d=self.dim()
s=0.
for i in range(d):
s+=self[i]*other[i]
return s
def __rand__(self,other):
return self&other
def __or__(self,other):
"""
cross product, defined only for 3D Vectors. goes like this: a|b
don't try this on non-3d Vectors. must use () around it because of fucked up operator precedence.
"""
a=self
b=other
return Vector([a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]])
def __ror__(self,other):
return -(self|other)
def __abs__(self):
s=0.
for x in self:
s+=x**2
return s**(1.0/2)
def __iadd__(self,other):
self=self+other
return self
def __isub__(self,other):
self=self-other
return self
def __imul__(self,other):
self=self*other
return self
def __idiv__(self,other):
self=self/other
return self
def __iand__(self,other):
raise VectorError("please don't do &= with my Vectors, it confuses me")
def __ior__(self,other):
self=self|other
return self
def __repr__(self):
return "Vector("+tuple.__repr__(self)+")"
def norm(self):
"""
gives the Vector, normalized
"""
return self/abs(self)
def dim(self):
return len(self)
def copy(self):
return Vector(self)
################################################################################################
def zeros(n):
"""
Returns a zero Vector of length n.
"""
return Vector(map(lambda x: 0., range(n)))
def ones(n):
"""
Returns a Vector of length n with all ones.
"""
return Vector(map(lambda x: 1., range(n)))
|
"""
Implements mainly the Vector class. See its documentation.
"""
class Vectorerror(Exception):
"""
An exception to use with Vector
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.value)
class Vector(tuple):
"""
A vector.
"""
def __init__(self, seq):
tuple.__init__(seq)
def __add__(self, other):
if not isinstance(other, Vector):
raise vector_error('right hand side is not a Vector')
return vector(map(lambda x, y: x + y, self, other))
def __neg__(self):
return vector(map(lambda x: -x, self))
def __pos__(self):
return self
def __sub__(self, other):
return vector(map(lambda x, y: x - y, self, other))
def __mul__(self, other):
if not (isinstance(other, int) or isinstance(other, float)):
raise vector_error('right hand side is illegal')
return vector(map(lambda x: x * other, self))
def __rmul__(self, other):
return self * other
def __div__(self, other):
if not (isinstance(other, int) or isinstance(other, float)):
raise vector_error('right hand side is illegal')
return vector(map(lambda x: x / other, self))
def __rdiv__(self, other):
raise vector_error('you sick pervert! you tried to divide something by a vector!')
def __and__(self, other):
"""
this is a dot product, done like this: a&b
must use () around it because of fucked up operator precedence.
"""
if not isinstance(other, Vector):
raise vector_error('trying to do dot product of Vector with non-Vector')
'\n if self.dim()!=other.dim():\n raise("trying to do dot product of Vectors of unequal dimension!")\n '
d = self.dim()
s = 0.0
for i in range(d):
s += self[i] * other[i]
return s
def __rand__(self, other):
return self & other
def __or__(self, other):
"""
cross product, defined only for 3D Vectors. goes like this: a|b
don't try this on non-3d Vectors. must use () around it because of fucked up operator precedence.
"""
a = self
b = other
return vector([a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]])
def __ror__(self, other):
return -(self | other)
def __abs__(self):
s = 0.0
for x in self:
s += x ** 2
return s ** (1.0 / 2)
def __iadd__(self, other):
self = self + other
return self
def __isub__(self, other):
self = self - other
return self
def __imul__(self, other):
self = self * other
return self
def __idiv__(self, other):
self = self / other
return self
def __iand__(self, other):
raise vector_error("please don't do &= with my Vectors, it confuses me")
def __ior__(self, other):
self = self | other
return self
def __repr__(self):
return 'Vector(' + tuple.__repr__(self) + ')'
def norm(self):
"""
gives the Vector, normalized
"""
return self / abs(self)
def dim(self):
return len(self)
def copy(self):
return vector(self)
def zeros(n):
"""
Returns a zero Vector of length n.
"""
return vector(map(lambda x: 0.0, range(n)))
def ones(n):
"""
Returns a Vector of length n with all ones.
"""
return vector(map(lambda x: 1.0, range(n)))
|
# Child Prime is such a prime number which can be obtained by summing up the square of the digit of its parent prime number.
# For example, 23 is a prime. If we calculate 2^2+3^2 = 4+9 = 13, which is also a prime no. then we call 13 as a child prime of 23.
ul = int(input("Enter Upper Limit: "))
gt = int(input("Generation Thresold :"))
def is_prime(m):
q = len(factors(m))
if q == 2:
return True
else:
return False
def sep(num):
res = list(map(int, str(num)))
return res
def factors(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist.append(i)
return flist
def primesum(num):
if is_prime(num):
a = sep(num)
sum = 0
for i in range(len(a)):
sum = sum + a[i]**2
return sum
def generation(num):
gen = [num]
g = num
q = 1
while q > 0:
if is_prime(primesum(g)):
g = primesum(g)
gen.append(g)
else:
q = q*(-1)
return gen
for i in range(ul):
if is_prime(i):
pg = generation(i)
gn = len(pg)
if gn >= gt:
print(pg)
|
ul = int(input('Enter Upper Limit: '))
gt = int(input('Generation Thresold :'))
def is_prime(m):
q = len(factors(m))
if q == 2:
return True
else:
return False
def sep(num):
res = list(map(int, str(num)))
return res
def factors(n):
flist = []
for i in range(1, n + 1):
if n % i == 0:
flist.append(i)
return flist
def primesum(num):
if is_prime(num):
a = sep(num)
sum = 0
for i in range(len(a)):
sum = sum + a[i] ** 2
return sum
def generation(num):
gen = [num]
g = num
q = 1
while q > 0:
if is_prime(primesum(g)):
g = primesum(g)
gen.append(g)
else:
q = q * -1
return gen
for i in range(ul):
if is_prime(i):
pg = generation(i)
gn = len(pg)
if gn >= gt:
print(pg)
|
class MissingVariableError(Exception):
def __init__(self, name):
self.name = name
self.message = f'The required variable "{self.name}" is missing'
super().__init__(self.message)
class ReservedVariableError(Exception):
def __init__(self, name):
self.name = name
self.message = (
f'The variable"{self.name}" is reserved and should only be set by combine'
)
super().__init__(self.message)
|
class Missingvariableerror(Exception):
def __init__(self, name):
self.name = name
self.message = f'The required variable "{self.name}" is missing'
super().__init__(self.message)
class Reservedvariableerror(Exception):
def __init__(self, name):
self.name = name
self.message = f'The variable"{self.name}" is reserved and should only be set by combine'
super().__init__(self.message)
|
def main():
# input
a, b, c = map(int, input().split())
# compute
cnt = 0
for i in range(a, b+1):
if c%i == 0:
cnt += 1
# output
print(cnt)
if __name__ == "__main__":
main()
|
def main():
(a, b, c) = map(int, input().split())
cnt = 0
for i in range(a, b + 1):
if c % i == 0:
cnt += 1
print(cnt)
if __name__ == '__main__':
main()
|
"""
Merge Sort
1. Divide the unsorted list into n sublists, each containing one element (a
list of one element is considered sorted).
2. Repeatedly merge sublists to
produce new sorted sublists until there is only one sublist remaining. This
will be the sorted list.
"""
def merge_sort(arr):
"""
merge sort
Time: O(nlog(n))
Space: O(n)
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
# Merge the sorted lists into a new one
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# Checking if any element was left
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
|
"""
Merge Sort
1. Divide the unsorted list into n sublists, each containing one element (a
list of one element is considered sorted).
2. Repeatedly merge sublists to
produce new sorted sublists until there is only one sublist remaining. This
will be the sorted list.
"""
def merge_sort(arr):
"""
merge sort
Time: O(nlog(n))
Space: O(n)
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
|
class IndexingError(Exception):
"""Exception raised for errors in the indexing flow.
Attributes:
type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists'
blocknumber -- block number of error
blockhash -- block hash of error
txhash -- transaction hash of error
message -- error message
"""
def __init__(self, type, blocknumber, blockhash, txhash, message):
super().__init__(message)
self.type = type
self.blocknumber = blocknumber
self.blockhash = blockhash
self.txhash = txhash
self.message = message
|
class Indexingerror(Exception):
"""Exception raised for errors in the indexing flow.
Attributes:
type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists'
blocknumber -- block number of error
blockhash -- block hash of error
txhash -- transaction hash of error
message -- error message
"""
def __init__(self, type, blocknumber, blockhash, txhash, message):
super().__init__(message)
self.type = type
self.blocknumber = blocknumber
self.blockhash = blockhash
self.txhash = txhash
self.message = message
|
"""
Entradas:
lista-->list-->lista
elemento->str-->elemento
Salidas
lista-->lista
"""
frutas = open('frutas.txt', 'r')
lista_frutas = []
for i in frutas:
lista_frutas.append(i)
def eliminar_un_caracter(lista: list, elemento: str):
auxilar = []
for i in lista:
a = i.replace(elemento, "")
auxilar.append(a)
return auxilar
if __name__ == "__main__":
nueva = eliminar_un_caracter(lista_frutas, ("a"))
print(nueva)
|
"""
Entradas:
lista-->list-->lista
elemento->str-->elemento
Salidas
lista-->lista
"""
frutas = open('frutas.txt', 'r')
lista_frutas = []
for i in frutas:
lista_frutas.append(i)
def eliminar_un_caracter(lista: list, elemento: str):
auxilar = []
for i in lista:
a = i.replace(elemento, '')
auxilar.append(a)
return auxilar
if __name__ == '__main__':
nueva = eliminar_un_caracter(lista_frutas, 'a')
print(nueva)
|
##########################################################################################
# district data structure
##########################################################################################
class DistrictData:
def __init__(self):
self.data = ""
self.stato = ""
self.codice_regione = ""
self.denominazione_regione = ""
self.codice_provincia = ""
self.denominazione_provincia = ""
self.sigla_provincia = ""
self.lat = ""
self.long = ""
self.totale_casi = 0
self.note = ""
self.codice_nuts_1 = ""
self.codice_nuts_2 = ""
self.codice_nuts_3 = ""
#data calclulated from the other
self.nuovi_casi = 0
def fillData(self,item_today, j_yesterday, index):
##########################################################################################
#fill the object class attributes
# 1. it fill up with the corrispective key into the JSON dataset, attributes and key that
# are called the same will automatically valued.
# 2. for the attributes that need some king of work you have to handle separately
##########################################################################################
for key in item_today:
if hasattr(self, key):
setattr(self,key,item_today[key])
if item_today["codice_provincia"] == j_yesterday[index]["codice_provincia"]: #check if the two json refer to the same regione code
n_positivi = item_today["totale_casi"]-j_yesterday[index]["totale_casi"]
setattr(self,"nuovi_casi",n_positivi)
else:
print("Provincia non corrispondente")
|
class Districtdata:
def __init__(self):
self.data = ''
self.stato = ''
self.codice_regione = ''
self.denominazione_regione = ''
self.codice_provincia = ''
self.denominazione_provincia = ''
self.sigla_provincia = ''
self.lat = ''
self.long = ''
self.totale_casi = 0
self.note = ''
self.codice_nuts_1 = ''
self.codice_nuts_2 = ''
self.codice_nuts_3 = ''
self.nuovi_casi = 0
def fill_data(self, item_today, j_yesterday, index):
for key in item_today:
if hasattr(self, key):
setattr(self, key, item_today[key])
if item_today['codice_provincia'] == j_yesterday[index]['codice_provincia']:
n_positivi = item_today['totale_casi'] - j_yesterday[index]['totale_casi']
setattr(self, 'nuovi_casi', n_positivi)
else:
print('Provincia non corrispondente')
|
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while (i >= 0 and nums[i+1] <= nums[i]):
i -= 1
# not the first
if i >= 0:
j = len(nums) - 1
while nums[i] >= nums[j]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# reverse
j = len(nums)-1
i += 1
while( i < j ):
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
|
class Solution:
def next_permutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while i >= 0 and nums[i + 1] <= nums[i]:
i -= 1
if i >= 0:
j = len(nums) - 1
while nums[i] >= nums[j]:
j -= 1
(nums[i], nums[j]) = (nums[j], nums[i])
j = len(nums) - 1
i += 1
while i < j:
(nums[i], nums[j]) = (nums[j], nums[i])
i += 1
j -= 1
|
# -*- coding: utf-8 -*-
while True:
try:
hm = list(map(float, input().split()))
h = int((hm[0] / 360) * 12)
m = int((hm[1] / 360) * 60)
if m == 60:
m = 0
print("{:02d}:{:02d}".format(h, m))
except (EOFError, IndexError):
break
|
while True:
try:
hm = list(map(float, input().split()))
h = int(hm[0] / 360 * 12)
m = int(hm[1] / 360 * 60)
if m == 60:
m = 0
print('{:02d}:{:02d}'.format(h, m))
except (EOFError, IndexError):
break
|
# -*- coding: utf-8 -*-
__about__ = """
This project comes fully-featured, with everything that Pinax provides enabled
by default. It provides all tabs available, etc. From here you can remove
applications that you do not want to use, and add your own applications as well.
"""
|
__about__ = '\nThis project comes fully-featured, with everything that Pinax provides enabled\nby default. It provides all tabs available, etc. From here you can remove\napplications that you do not want to use, and add your own applications as well.\n'
|
class Solution:
def rob(self, root):
def f(n):
if not n:
return [0, 0]
l, r = f(n.left), f(n.right)
return [l[1] + r[1], max(l[1] + r[1], n.val + l[0] + r[0])]
return max(f(root))
|
class Solution:
def rob(self, root):
def f(n):
if not n:
return [0, 0]
(l, r) = (f(n.left), f(n.right))
return [l[1] + r[1], max(l[1] + r[1], n.val + l[0] + r[0])]
return max(f(root))
|
# -*- coding: utf-8 -*-
def create_3dskullstrip_arg_string(shrink_fac, var_shrink_fac,
shrink_fac_bot_lim, avoid_vent, niter,
pushout, touchup, fill_hole, avoid_eyes,
use_edge, exp_frac, smooth_final,
push_to_edge, use_skull, perc_int,
max_inter_iter, blur_fwhm, fac):
"""
Method to return option string for 3dSkullStrip
Parameters
----------
shrink_fac : float
Parameter controlling the brain vs non-brain intensity threshold (tb)
var_shrink_fac : boolean
Vary the shrink factor with the number of iterations
shrink_fac_bot_lim : float
Do not allow the varying SF to go below SFBL
avoid_vent : boolean
Avoid ventricles
niter : float
Number of iterations
pushout : boolean
Consider values above each node in addition to values below the node when deciding on expansion
touchup : boolean
Perform touchup operations at end to include areas not covered by surface expansion
fill_hole : float
Fill small holes that can result from small surface intersections caused by the touchup operation
avoid_eyes : boolean
Avoid eyes
use_edge : boolean
Use edge detection to reduce leakage into meninges and eyes
exp_frac : float
Speed of expansion
smooth_final : float
Perform final surface smoothing after all iterations
push_to_edge : boolean
Perform aggressive push to edge at the end
use_skull : boolean
Use outer skull to limit expansion of surface into the skull due to very strong shading artifacts
perc_int : float
Percentage of segments allowed to intersect surface
max_inter_iter : float
Number of iteration to remove intersection problems
blur_fwhm : float
Blur dset after spatial normalization
fac : float
Multiply input dataset by FAC if range of values is too small
Returns
-------
opt_str : string
Command args
"""
expr = ''
defaults = dict(
fill_hole=10 if touchup else 0,
shrink_fac=0.6,
shrink_fac_bot_lim=0.4 if use_edge else 0.65,
niter=250,
exp_frac=0.1,
smooth_final=20,
perc_int=0,
max_inter_iter=4,
blur_fwhm=0,
fac=1.0
)
if float(shrink_fac) != defaults['shrink_fac']:
expr += ' -shrink_fac {0}'.format(shrink_fac)
if not var_shrink_fac:
expr += ' -no_var_shrink_fac'
if float(shrink_fac_bot_lim) != defaults['shrink_fac_bot_lim']:
expr += ' -shrink_fac_bot_lim {0}'.format(shrink_fac_bot_lim)
if not use_edge:
expr += ' -no_use_edge'
if not avoid_vent:
expr += ' -no_avoid_vent'
if int(niter) != defaults['niter']:
expr += ' -niter {0}'.format(niter)
if not pushout:
expr += ' -no_pushout'
if not touchup:
expr += ' -no_touchup'
if int(fill_hole) != defaults['fill_hole']:
expr += ' -fill_hole {0}'.format(fill_hole)
if not avoid_eyes:
expr += ' -no_avoid_eyes'
if float(exp_frac) != defaults['exp_frac']:
expr += ' -exp_frac {0}'.format(exp_frac)
if int(smooth_final) != defaults['smooth_final']:
expr += ' -smooth_final {0}'.format(smooth_final)
if push_to_edge:
expr += ' -push_to_edge'
if use_skull:
expr += ' -use_skull'
if float(perc_int) != defaults['perc_int']:
expr += ' -perc_int {0}'.format(perc_int)
if int(max_inter_iter) != defaults['max_inter_iter']:
expr += ' -max_inter_iter {0}'.format(max_inter_iter)
if float(blur_fwhm) != defaults['blur_fwhm']:
expr += ' -blur_fwhm {0}'.format(blur_fwhm)
if float(fac) != defaults['fac']:
expr += ' -fac {0}'.format(fac)
return expr
|
def create_3dskullstrip_arg_string(shrink_fac, var_shrink_fac, shrink_fac_bot_lim, avoid_vent, niter, pushout, touchup, fill_hole, avoid_eyes, use_edge, exp_frac, smooth_final, push_to_edge, use_skull, perc_int, max_inter_iter, blur_fwhm, fac):
"""
Method to return option string for 3dSkullStrip
Parameters
----------
shrink_fac : float
Parameter controlling the brain vs non-brain intensity threshold (tb)
var_shrink_fac : boolean
Vary the shrink factor with the number of iterations
shrink_fac_bot_lim : float
Do not allow the varying SF to go below SFBL
avoid_vent : boolean
Avoid ventricles
niter : float
Number of iterations
pushout : boolean
Consider values above each node in addition to values below the node when deciding on expansion
touchup : boolean
Perform touchup operations at end to include areas not covered by surface expansion
fill_hole : float
Fill small holes that can result from small surface intersections caused by the touchup operation
avoid_eyes : boolean
Avoid eyes
use_edge : boolean
Use edge detection to reduce leakage into meninges and eyes
exp_frac : float
Speed of expansion
smooth_final : float
Perform final surface smoothing after all iterations
push_to_edge : boolean
Perform aggressive push to edge at the end
use_skull : boolean
Use outer skull to limit expansion of surface into the skull due to very strong shading artifacts
perc_int : float
Percentage of segments allowed to intersect surface
max_inter_iter : float
Number of iteration to remove intersection problems
blur_fwhm : float
Blur dset after spatial normalization
fac : float
Multiply input dataset by FAC if range of values is too small
Returns
-------
opt_str : string
Command args
"""
expr = ''
defaults = dict(fill_hole=10 if touchup else 0, shrink_fac=0.6, shrink_fac_bot_lim=0.4 if use_edge else 0.65, niter=250, exp_frac=0.1, smooth_final=20, perc_int=0, max_inter_iter=4, blur_fwhm=0, fac=1.0)
if float(shrink_fac) != defaults['shrink_fac']:
expr += ' -shrink_fac {0}'.format(shrink_fac)
if not var_shrink_fac:
expr += ' -no_var_shrink_fac'
if float(shrink_fac_bot_lim) != defaults['shrink_fac_bot_lim']:
expr += ' -shrink_fac_bot_lim {0}'.format(shrink_fac_bot_lim)
if not use_edge:
expr += ' -no_use_edge'
if not avoid_vent:
expr += ' -no_avoid_vent'
if int(niter) != defaults['niter']:
expr += ' -niter {0}'.format(niter)
if not pushout:
expr += ' -no_pushout'
if not touchup:
expr += ' -no_touchup'
if int(fill_hole) != defaults['fill_hole']:
expr += ' -fill_hole {0}'.format(fill_hole)
if not avoid_eyes:
expr += ' -no_avoid_eyes'
if float(exp_frac) != defaults['exp_frac']:
expr += ' -exp_frac {0}'.format(exp_frac)
if int(smooth_final) != defaults['smooth_final']:
expr += ' -smooth_final {0}'.format(smooth_final)
if push_to_edge:
expr += ' -push_to_edge'
if use_skull:
expr += ' -use_skull'
if float(perc_int) != defaults['perc_int']:
expr += ' -perc_int {0}'.format(perc_int)
if int(max_inter_iter) != defaults['max_inter_iter']:
expr += ' -max_inter_iter {0}'.format(max_inter_iter)
if float(blur_fwhm) != defaults['blur_fwhm']:
expr += ' -blur_fwhm {0}'.format(blur_fwhm)
if float(fac) != defaults['fac']:
expr += ' -fac {0}'.format(fac)
return expr
|
#!/usr/bin/env python3.7
class Proposal:
"""
Sequence proposed by the player while trying to guess the secret
The problem will add hint information, by setting the value of whites and reds
"""
"""proposed secret sequence"""
sequence = str
"""number of right colours in a wrong position"""
whites = int
"""number of right colours in the correct position"""
reds = int
def __init__(self, sequence):
"""
Create a proposal
:param sequence: secret sequence proposed by the player
"""
self.sequence = sequence
|
class Proposal:
"""
Sequence proposed by the player while trying to guess the secret
The problem will add hint information, by setting the value of whites and reds
"""
'proposed secret sequence'
sequence = str
'number of right colours in a wrong position'
whites = int
'number of right colours in the correct position'
reds = int
def __init__(self, sequence):
"""
Create a proposal
:param sequence: secret sequence proposed by the player
"""
self.sequence = sequence
|
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# 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.
class OperationResult(object):
def __init__(self,
result_status,
result_reason=None,
result_message=None):
self.result_status = result_status
if result_reason is not None:
self.result_reason = result_reason
else:
self.result_reason = None
if result_message is not None:
self.result_message = result_message
else:
self.result_message = None
class CreateResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
object_type=None,
uuid=None,
template_attribute=None):
super(CreateResult, self).__init__(
result_status, result_reason, result_message)
if object_type is not None:
self.object_type = object_type
else:
self.object_type = None
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if template_attribute is not None:
self.template_attribute = template_attribute
else:
self.template_attribute = None
class CreateKeyPairResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
private_key_uuid=None,
public_key_uuid=None,
private_key_template_attribute=None,
public_key_template_attribute=None):
super(CreateKeyPairResult, self).__init__(
result_status, result_reason, result_message)
self.private_key_uuid = private_key_uuid
self.public_key_uuid = public_key_uuid
self.private_key_template_attribute = private_key_template_attribute
self.public_key_template_attribute = public_key_template_attribute
class ActivateResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
uuid=None):
super(ActivateResult, self).__init__(
result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
class RegisterResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
uuid=None,
template_attribute=None):
super(RegisterResult, self).__init__(
result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if template_attribute is not None:
self.template_attribute = template_attribute
else:
self.template_attribute = None
class RekeyKeyPairResult(CreateKeyPairResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
private_key_uuid=None,
public_key_uuid=None,
private_key_template_attribute=None,
public_key_template_attribute=None):
super(RekeyKeyPairResult, self).__init__(
result_status, result_reason, result_message, private_key_uuid,
public_key_uuid, private_key_template_attribute,
public_key_template_attribute)
class GetResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
object_type=None,
uuid=None,
secret=None):
super(GetResult, self).__init__(
result_status, result_reason, result_message)
if object_type is not None:
self.object_type = object_type
else:
self.object_type = None
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if secret is not None:
self.secret = secret
else:
self.secret = None
class GetAttributesResult(OperationResult):
def __init__(
self,
result_status,
result_reason=None,
result_message=None,
uuid=None,
attributes=None
):
super(GetAttributesResult, self).__init__(
result_status,
result_reason,
result_message
)
self.uuid = uuid
self.attributes = attributes
class GetAttributeListResult(OperationResult):
def __init__(
self,
result_status,
result_reason=None,
result_message=None,
uid=None,
names=None):
super(GetAttributeListResult, self).__init__(
result_status, result_reason, result_message)
self.uid = uid
self.names = names
class DestroyResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
uuid=None):
super(DestroyResult, self).__init__(
result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
class LocateResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
uuids=None):
super(LocateResult, self).__init__(
result_status, result_reason, result_message)
self.uuids = uuids
class QueryResult(OperationResult):
"""
A container for the results of a Query operation.
Attributes:
result_status: The status of the Query operation (e.g., success or
failure).
result_reason: The reason for the operation status.
result_message: Extra information pertaining to the status reason.
operations: A list of Operations supported by the server.
object_types: A list of Object Types supported by the server.
vendor_identification:
server_information:
application_namespaces: A list of namespaces supported by the server.
extension_information: A list of extensions supported by the server.
"""
def __init__(self,
result_status,
result_reason=None,
result_message=None,
operations=None,
object_types=None,
vendor_identification=None,
server_information=None,
application_namespaces=None,
extension_information=None):
super(QueryResult, self).__init__(
result_status, result_reason, result_message)
if operations is None:
self.operations = list()
else:
self.operations = operations
if object_types is None:
self.object_types = list()
else:
self.object_types = object_types
self.vendor_identification = vendor_identification
self.server_information = server_information
if application_namespaces is None:
self.application_namespaces = list()
else:
self.application_namespaces = application_namespaces
if extension_information is None:
self.extension_information = list()
else:
self.extension_information = extension_information
class DiscoverVersionsResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
protocol_versions=None):
super(DiscoverVersionsResult, self).__init__(
result_status, result_reason, result_message)
self.protocol_versions = protocol_versions
class RevokeResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
unique_identifier=None):
super(RevokeResult, self).__init__(
result_status, result_reason, result_message)
self.unique_identifier = unique_identifier
class MACResult(OperationResult):
def __init__(self,
result_status,
result_reason=None,
result_message=None,
uuid=None,
mac_data=None):
super(MACResult, self).__init__(
result_status,
result_reason,
result_message
)
self.uuid = uuid
self.mac_data = mac_data
|
class Operationresult(object):
def __init__(self, result_status, result_reason=None, result_message=None):
self.result_status = result_status
if result_reason is not None:
self.result_reason = result_reason
else:
self.result_reason = None
if result_message is not None:
self.result_message = result_message
else:
self.result_message = None
class Createresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, object_type=None, uuid=None, template_attribute=None):
super(CreateResult, self).__init__(result_status, result_reason, result_message)
if object_type is not None:
self.object_type = object_type
else:
self.object_type = None
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if template_attribute is not None:
self.template_attribute = template_attribute
else:
self.template_attribute = None
class Createkeypairresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, private_key_uuid=None, public_key_uuid=None, private_key_template_attribute=None, public_key_template_attribute=None):
super(CreateKeyPairResult, self).__init__(result_status, result_reason, result_message)
self.private_key_uuid = private_key_uuid
self.public_key_uuid = public_key_uuid
self.private_key_template_attribute = private_key_template_attribute
self.public_key_template_attribute = public_key_template_attribute
class Activateresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuid=None):
super(ActivateResult, self).__init__(result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
class Registerresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuid=None, template_attribute=None):
super(RegisterResult, self).__init__(result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if template_attribute is not None:
self.template_attribute = template_attribute
else:
self.template_attribute = None
class Rekeykeypairresult(CreateKeyPairResult):
def __init__(self, result_status, result_reason=None, result_message=None, private_key_uuid=None, public_key_uuid=None, private_key_template_attribute=None, public_key_template_attribute=None):
super(RekeyKeyPairResult, self).__init__(result_status, result_reason, result_message, private_key_uuid, public_key_uuid, private_key_template_attribute, public_key_template_attribute)
class Getresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, object_type=None, uuid=None, secret=None):
super(GetResult, self).__init__(result_status, result_reason, result_message)
if object_type is not None:
self.object_type = object_type
else:
self.object_type = None
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
if secret is not None:
self.secret = secret
else:
self.secret = None
class Getattributesresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuid=None, attributes=None):
super(GetAttributesResult, self).__init__(result_status, result_reason, result_message)
self.uuid = uuid
self.attributes = attributes
class Getattributelistresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uid=None, names=None):
super(GetAttributeListResult, self).__init__(result_status, result_reason, result_message)
self.uid = uid
self.names = names
class Destroyresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuid=None):
super(DestroyResult, self).__init__(result_status, result_reason, result_message)
if uuid is not None:
self.uuid = uuid
else:
self.uuid = None
class Locateresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuids=None):
super(LocateResult, self).__init__(result_status, result_reason, result_message)
self.uuids = uuids
class Queryresult(OperationResult):
"""
A container for the results of a Query operation.
Attributes:
result_status: The status of the Query operation (e.g., success or
failure).
result_reason: The reason for the operation status.
result_message: Extra information pertaining to the status reason.
operations: A list of Operations supported by the server.
object_types: A list of Object Types supported by the server.
vendor_identification:
server_information:
application_namespaces: A list of namespaces supported by the server.
extension_information: A list of extensions supported by the server.
"""
def __init__(self, result_status, result_reason=None, result_message=None, operations=None, object_types=None, vendor_identification=None, server_information=None, application_namespaces=None, extension_information=None):
super(QueryResult, self).__init__(result_status, result_reason, result_message)
if operations is None:
self.operations = list()
else:
self.operations = operations
if object_types is None:
self.object_types = list()
else:
self.object_types = object_types
self.vendor_identification = vendor_identification
self.server_information = server_information
if application_namespaces is None:
self.application_namespaces = list()
else:
self.application_namespaces = application_namespaces
if extension_information is None:
self.extension_information = list()
else:
self.extension_information = extension_information
class Discoverversionsresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, protocol_versions=None):
super(DiscoverVersionsResult, self).__init__(result_status, result_reason, result_message)
self.protocol_versions = protocol_versions
class Revokeresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, unique_identifier=None):
super(RevokeResult, self).__init__(result_status, result_reason, result_message)
self.unique_identifier = unique_identifier
class Macresult(OperationResult):
def __init__(self, result_status, result_reason=None, result_message=None, uuid=None, mac_data=None):
super(MACResult, self).__init__(result_status, result_reason, result_message)
self.uuid = uuid
self.mac_data = mac_data
|
'''
If the parameter to the make payment method of the CreditCard class
were a negative number, that would have the effect of raising the balance
on the account. Revise the implementation so that it raises a ValueError if
a negative value is sent.
'''
def make_payment(self,amount):
if amount < 0:
raise ValueError("Payment amount can not be negative")
else:
try:
self._balance -= amount
msg = '$' + str(amount) +' Payment received' + 'New balance is '+'$'+str(self._balance)
return msg
except (ValueError,NameError,SyntaxError) as e:
print('Please input correct number')
print(e)
|
"""
If the parameter to the make payment method of the CreditCard class
were a negative number, that would have the effect of raising the balance
on the account. Revise the implementation so that it raises a ValueError if
a negative value is sent.
"""
def make_payment(self, amount):
if amount < 0:
raise value_error('Payment amount can not be negative')
else:
try:
self._balance -= amount
msg = '$' + str(amount) + ' Payment received' + 'New balance is ' + '$' + str(self._balance)
return msg
except (ValueError, NameError, SyntaxError) as e:
print('Please input correct number')
print(e)
|
x = 3
def foo():
y = "String"
return y
foo()
|
x = 3
def foo():
y = 'String'
return y
foo()
|
n = int(input())
for i in range(n):
r,e,c = map(int, input().split())
if((e-c) > r):
print('advertise')
elif((e-c) == r):
print('does not matter')
else:
print('do not advertise')
|
n = int(input())
for i in range(n):
(r, e, c) = map(int, input().split())
if e - c > r:
print('advertise')
elif e - c == r:
print('does not matter')
else:
print('do not advertise')
|
def sum(*args):
total = 0
for arg in args:
total+= arg
return total
a = sum(1200, 300, 500)
print(a)
|
def sum(*args):
total = 0
for arg in args:
total += arg
return total
a = sum(1200, 300, 500)
print(a)
|
#1)
def isnegative(n):
if n < 0:
return True
else:
return False
isnegative(-6)
#1)
list1 = [1,2,3]
def count_evens(list1):
even_count = 0
for num in list1:
if num % 2 == 0:
even_count += 1
print(even_count)
#1)
def increment_odds(n):
nums = []
for n in range(1, 2*n, 2):
nums.append(n)
return nums
increment_odds(3)
#1)
def average(l):
for n in l:
return round(len(l)/n, 2)
average([1,2,3])
#1)
name_to_dict = dict()
name_to_dict["frist_name"] = "Ada"
name_to_dict["last_name"] = "Lovelace"
name_to_dict
#1)
def capitalize_names(name):
for n in name[0]:
return(f"{name}".capitalize())
capitalize_names("")
#1)
def count_vowels(value):
value = value.lower()
vowel = ['a','e','i','o','u']
count = 0
for a in value:
if a in vowel:
count += 1
return count
count_vowels('abcde')
#1)
def analyze_word(word):
vowels = ['a','e','i','o','u']
og_word = {}
num_of_vowels = {}
num_of_char = {}
for c in word:
if c in num_of_char:
num_of_char[word] += 1
else:
num_of_char[word] = 1
return len(word)
for c in word:
if c in vowels:
num_of_char[word] += 1
else:
num_of_char[word] = 1
return(c)
analyze_word('word')
|
def isnegative(n):
if n < 0:
return True
else:
return False
isnegative(-6)
list1 = [1, 2, 3]
def count_evens(list1):
even_count = 0
for num in list1:
if num % 2 == 0:
even_count += 1
print(even_count)
def increment_odds(n):
nums = []
for n in range(1, 2 * n, 2):
nums.append(n)
return nums
increment_odds(3)
def average(l):
for n in l:
return round(len(l) / n, 2)
average([1, 2, 3])
name_to_dict = dict()
name_to_dict['frist_name'] = 'Ada'
name_to_dict['last_name'] = 'Lovelace'
name_to_dict
def capitalize_names(name):
for n in name[0]:
return f'{name}'.capitalize()
capitalize_names('')
def count_vowels(value):
value = value.lower()
vowel = ['a', 'e', 'i', 'o', 'u']
count = 0
for a in value:
if a in vowel:
count += 1
return count
count_vowels('abcde')
def analyze_word(word):
vowels = ['a', 'e', 'i', 'o', 'u']
og_word = {}
num_of_vowels = {}
num_of_char = {}
for c in word:
if c in num_of_char:
num_of_char[word] += 1
else:
num_of_char[word] = 1
return len(word)
for c in word:
if c in vowels:
num_of_char[word] += 1
else:
num_of_char[word] = 1
return c
analyze_word('word')
|
N = int(input())
while N > 0:
texto = input().lower().replace(' ', '')
alfabeto = 'abcdefghijklmnopqrstuvwxyz'
contador = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
result = ''
a, i, count, maior = 0, 0, 0, 0
break_ = True
while count < 52:
if break_ == True:
contador[i] = texto.count(alfabeto[i])
if contador[i] > maior:
maior = contador[i]
i += 1
if i == 26:
break_ = False
else:
if maior == texto.count(alfabeto[a]):
result += alfabeto[a]
a += 1
count += 1
print(result)
N -= 1
|
n = int(input())
while N > 0:
texto = input().lower().replace(' ', '')
alfabeto = 'abcdefghijklmnopqrstuvwxyz'
contador = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
result = ''
(a, i, count, maior) = (0, 0, 0, 0)
break_ = True
while count < 52:
if break_ == True:
contador[i] = texto.count(alfabeto[i])
if contador[i] > maior:
maior = contador[i]
i += 1
if i == 26:
break_ = False
else:
if maior == texto.count(alfabeto[a]):
result += alfabeto[a]
a += 1
count += 1
print(result)
n -= 1
|
"""
Singleton objects that serve as placeholders in pyll graphs.
These are used by e.g. ./nips2011.py
"""
class train_task(object):
"""`train` argument to skdata.LearningAlgo's best_model method
"""
class valid_task(object):
"""`valid` argument to skdata.LearningAlgo's best_model method
"""
class ctrl(object):
"""Hyperopt Ctrl object passed to worker eval_fn.
"""
|
"""
Singleton objects that serve as placeholders in pyll graphs.
These are used by e.g. ./nips2011.py
"""
class Train_Task(object):
"""`train` argument to skdata.LearningAlgo's best_model method
"""
class Valid_Task(object):
"""`valid` argument to skdata.LearningAlgo's best_model method
"""
class Ctrl(object):
"""Hyperopt Ctrl object passed to worker eval_fn.
"""
|
# Schema used for pre-2013-2014 TAPR data
SCHEMA = {
'staff-and-student-information': {
'all_students_count': 'PETALLC',
'african_american_count': 'PETBLAC',
'african_american_percent': 'PETBLAP',
'american_indian_count': 'PETINDC',
'american_indian_percent': 'PETINDP',
'asian_count': 'PETASIC',
'asian_percent': 'PETASIP',
'hispanic_count': 'PETHISC',
'hispanic_percent': 'PETHISP',
'pacific_islander_count': 'PETPCIC',
'pacific_islander_percent': 'PETPCIP',
'two_or_more_races_count': 'PETTWOC',
'two_or_more_races_percent': 'PETTWOP',
'white_count': 'PETWHIC',
'white_percent': 'PETWHIP',
'early_childhood_education_count': 'PETGEEC',
'early_childhood_education_percent': 'PETGEEP',
'prek_count': 'PETGPKC',
'prek_percent': 'PETGPKP',
'kindergarten_count': 'PETGKNC',
'kindergarten_percent': 'PETGKNP',
'first_count': 'PETG01C',
'first_percent': 'PETG01P',
'second_count': 'PETG02C',
'second_percent': 'PETG02P',
'third_count': 'PETG03C',
'third_percent': 'PETG03P',
'fourth_count': 'PETG04C',
'fourth_percent': 'PETG04P',
'fifth_count': 'PETG05C',
'fifth_percent': 'PETG05P',
'sixth_count': 'PETG06C',
'sixth_percent': 'PETG06P',
'seventh_count': 'PETG07C',
'seventh_percent': 'PETG07P',
'eighth_count': 'PETG08C',
'eighth_percent': 'PETG08P',
'ninth_count': 'PETG09C',
'ninth_percent': 'PETG09P',
'tenth_count': 'PETG10C',
'tenth_percent': 'PETG10P',
'eleventh_count': 'PETG11C',
'eleventh_percent': 'PETG11P',
'twelfth_count': 'PETG12C',
'twelfth_percent': 'PETG12P',
'at_risk_count': 'PETRSKC',
'at_risk_percent': 'PETRSKP',
'economically_disadvantaged_count': 'PETECOC',
'economically_disadvantaged_percent': 'PETECOP',
'limited_english_proficient_count': 'PETLEPC',
'limited_english_proficient_percent': 'PETLEPP',
'bilingual_esl_count': 'PETBILC',
'bilingual_esl_percent': 'PETBILP',
'career_technical_education_count': 'PETVOCC',
'career_technical_education_percent': 'PETVOCP',
'gifted_and_talented_count': 'PETGIFC',
'gifted_and_talented_percent': 'PETGIFP',
'special_education_count': 'PETSPEC',
'special_education_percent': 'PETSPEP',
'class_size_avg_kindergarten': 'PCTGKGA',
'class_size_avg_first': 'PCTG01A',
'class_size_avg_second': 'PCTG02A',
'class_size_avg_third': 'PCTG03A',
'class_size_avg_fourth': 'PCTG04A',
'class_size_avg_fifth': 'PCTG05A',
'class_size_avg_sixth': 'PCTG06A',
'class_size_avg_mixed_elementary': 'PCTGMEA',
'class_size_avg_secondary_english': 'PCTENGA',
'class_size_avg_secondary_foreign_language': 'PCTFLAA',
'class_size_avg_secondary_math': 'PCTMATA',
'class_size_avg_secondary_science': 'PCTSCIA',
'class_size_avg_secondary_social_studies': 'PCTSOCA',
'students_per_teacher': 'PSTKIDR',
# teacher_avg_tenure is Average Years Experience of Teachers with District
'teacher_avg_tenure': 'PSTTENA',
# teacher_avg_experience is Average Years Experience of Teachers
'teacher_avg_experience': 'PSTEXPA',
'teacher_avg_base_salary': 'PSTTOSA',
'teacher_avg_beginning_salary': 'PST00SA',
'teacher_avg_1_to_5_year_salary': 'PST01SA',
'teacher_avg_6_to_10_year_salary': 'PST06SA',
'teacher_avg_11_to_20_year_salary': 'PST11SA',
'teacher_avg_20_plus_year_salary': 'PST20SA',
'teacher_total_fte_count': 'PSTTOFC',
'teacher_african_american_fte_count': 'PSTBLFC',
'teacher_american_indian_fte_count': 'PSTINFC',
'teacher_asian_fte_count': 'PSTASFC',
'teacher_hispanic_fte_count': 'PSTHIFC',
'teacher_pacific_islander_fte_count': 'PSTPIFC',
'teacher_two_or_more_races_fte_count': 'PSTTWFC',
'teacher_white_fte_count': 'PSTWHFC',
'teacher_total_fte_percent': 'PSTTOFC',
'teacher_african_american_fte_percent': 'PSTBLFP',
'teacher_american_indian_fte_percent': 'PSTINFP',
'teacher_asian_fte_percent': 'PSTASFP',
'teacher_hispanic_fte_percent': 'PSTHIFP',
'teacher_pacific_islander_fte_percent': 'PSTPIFP',
'teacher_two_or_more_races_fte_percent': 'PSTTWFP',
'teacher_white_fte_percent': 'PSTWHFP',
# 'teacher_no_degree_count': 'PSTNOFC',
# 'teacher_bachelors_count': 'PSTBAFC',
# 'teacher_masters_count': 'PSTMSFC',
# 'teacher_doctorate_count': 'PSTPHFC',
# 'teacher_no_degree_percent': 'PSTNOFP',
# 'teacher_bachelors_percent': 'PSTBAFP',
# 'teacher_masters_percent': 'PSTMSFP',
# 'teacher_doctorate_percent': 'PSTPHFP',
},
'postsecondary-readiness-and-non-staar-performance-indicators': {
# 'college_ready_graduates_english_all_students_count': 'ACRR',
'college_ready_graduates_english_all_students_percent': 'ACRR',
# 'college_ready_graduates_english_african_american_count': 'BCRR',
'college_ready_graduates_english_african_american_percent': 'BCRR',
# 'college_ready_graduates_english_american_indian_count': 'ICRR',
'college_ready_graduates_english_american_indian_percent': 'ICRR',
# 'college_ready_graduates_english_asian_count': '3CRR',
'college_ready_graduates_english_asian_percent': '3CRR',
# 'college_ready_graduates_english_hispanic_count': 'HCRR',
'college_ready_graduates_english_hispanic_percent': 'HCRR',
# 'college_ready_graduates_english_pacific_islander_count': '4CRR',
'college_ready_graduates_english_pacific_islander_percent': '4CRR',
# 'college_ready_graduates_english_two_or_more_races_count': '2CRR',
'college_ready_graduates_english_two_or_more_races_percent': '2CRR',
# 'college_ready_graduates_english_white_count': 'WCRR',
'college_ready_graduates_english_white_percent': 'WCRR',
# 'college_ready_graduates_english_economically_disadvantaged_count': 'ECRR',
'college_ready_graduates_english_economically_disadvantaged_percent': 'ECRR',
# 'college_ready_graduates_english_limited_english_proficient_count': 'LCRR',
'college_ready_graduates_english_limited_english_proficient_percent': 'LCRR',
# 'college_ready_graduates_english_at_risk_count': 'RCRR',
'college_ready_graduates_english_at_risk_percent': 'RCRR',
# 'college_ready_graduates_math_all_students_count': 'ACRM',
'college_ready_graduates_math_all_students_percent': 'ACRM',
# 'college_ready_graduates_math_african_american_count': 'BCRM',
'college_ready_graduates_math_african_american_percent': 'BCRM',
# 'college_ready_graduates_math_american_indian_count': 'ICRM',
'college_ready_graduates_math_american_indian_percent': 'ICRM',
# 'college_ready_graduates_math_asian_count': '3CRM',
'college_ready_graduates_math_asian_percent': '3CRM',
# 'college_ready_graduates_math_hispanic_count': 'HCRM',
'college_ready_graduates_math_hispanic_percent': 'HCRM',
# 'college_ready_graduates_math_pacific_islander_count': '4CRM',
'college_ready_graduates_math_pacific_islander_percent': '4CRM',
# 'college_ready_graduates_math_two_or_more_races_count': '2CRM',
'college_ready_graduates_math_two_or_more_races_percent': '2CRM',
# 'college_ready_graduates_math_white_count': 'WCRM',
'college_ready_graduates_math_white_percent': 'WCRM',
# 'college_ready_graduates_math_economically_disadvantaged_count': 'ECRM',
'college_ready_graduates_math_economically_disadvantaged_percent': 'ECRM',
# 'college_ready_graduates_math_limited_english_proficient_count': 'LCRM',
'college_ready_graduates_math_limited_english_proficient_percent': 'LCRM',
# 'college_ready_graduates_math_at_risk_count': 'RCRM',
'college_ready_graduates_math_at_risk_percent': 'RCRM',
# 'college_ready_graduates_both_all_students_count': 'ACRB',
'college_ready_graduates_both_all_students_percent': 'ACRB',
# 'college_ready_graduates_both_african_american_count': 'BCRB',
'college_ready_graduates_both_african_american_percent': 'BCRB',
# 'college_ready_graduates_both_asian_count': '3CRB',
'college_ready_graduates_both_asian_percent': '3CRB',
# 'college_ready_graduates_both_hispanic_count': 'HCRB',
'college_ready_graduates_both_hispanic_percent': 'HCRB',
# 'college_ready_graduates_both_american_indian_count': 'ICRB',
'college_ready_graduates_both_american_indian_percent': 'ICRB',
# 'college_ready_graduates_both_pacific_islander_count': '4CRB',
'college_ready_graduates_both_pacific_islander_percent': '4CRB',
# 'college_ready_graduates_both_two_or_more_races_count': '2CRB',
'college_ready_graduates_both_two_or_more_races_percent': '2CRB',
# 'college_ready_graduates_both_white_count': 'WCRB',
'college_ready_graduates_both_white_percent': 'WCRB',
# 'college_ready_graduates_both_economically_disadvantaged_count': 'ECRB',
'college_ready_graduates_both_economically_disadvantaged_percent': 'ECRB',
# 'college_ready_graduates_both_limited_english_proficient_count': 'LCRB',
'college_ready_graduates_both_limited_english_proficient_percent': 'LCRB',
# 'college_ready_graduates_both_at_risk_count': 'RCRB',
'college_ready_graduates_both_at_risk_percent': 'RCRB',
'avg_sat_score_all_students': 'A0CSA',
'avg_sat_score_african_american': 'B0CSA',
'avg_sat_score_american_indian': 'I0CSA',
'avg_sat_score_asian': '30CSA',
'avg_sat_score_hispanic': 'H0CSA',
'avg_sat_score_pacific_islander': '40CSA',
'avg_sat_score_two_or_more_races': '20CSA',
'avg_sat_score_white': 'W0CSA',
'avg_sat_score_economically_disadvantaged': 'E0CSA',
'avg_act_score_all_students': 'A0CAA',
'avg_act_score_african_american': 'B0CAA',
'avg_act_score_american_indian': 'I0CAA',
'avg_act_score_asian': '30CAA',
'avg_act_score_hispanic': 'H0CAA',
'avg_act_score_pacific_islander': '40CAA',
'avg_act_score_two_or_more_races': '20CAA',
'avg_act_score_white': 'W0CAA',
'avg_act_score_economically_disadvantaged': 'E0CAA',
# 'ap_ib_all_students_count_above_criterion': 'A0BKA',
'ap_ib_all_students_percent_above_criterion': 'A0BKA',
# 'ap_ib_african_american_count_above_criterion': 'B0BKA',
'ap_ib_african_american_percent_above_criterion': 'B0BKA',
# 'ap_ib_asian_count_above_criterion': '30BKA',
'ap_ib_asian_percent_above_criterion': '30BKA',
# 'ap_ib_hispanic_count_above_criterion': 'H0BKA',
'ap_ib_hispanic_percent_above_criterion': 'H0BKA',
# 'ap_ib_american_indian_count_above_criterion': 'I0BKA',
'ap_ib_american_indian_percent_above_criterion': 'I0BKA',
# 'ap_ib_pacific_islander_count_above_criterion': '40BKA',
'ap_ib_pacific_islander_percent_above_criterion': '40BKA',
# 'ap_ib_two_or_more_races_count_above_criterion': '20BKA',
'ap_ib_two_or_more_races_percent_above_criterion': '20BKA',
# 'ap_ib_white_count_above_criterion': 'W0BKA',
'ap_ib_white_percent_above_criterion': 'W0BKA',
# 'ap_ib_economically_disadvantaged_count_above_criterion': 'E0BKA',
'ap_ib_economically_disadvantaged_percent_above_criterion': 'E0BKA',
'ap_ib_all_students_percent_taking': 'A0BTA',
'ap_ib_african_american_percent_taking': 'B0BTA',
'ap_ib_asian_percent_taking': '30BTA',
'ap_ib_hispanic_percent_taking': 'H0BTA',
'ap_ib_american_indian_percent_taking': 'I0BTA',
'ap_ib_pacific_islander_percent_taking': '40BTA',
'ap_ib_two_or_more_races_percent_taking': '20BTA',
'ap_ib_white_percent_taking': 'W0BTA',
'ap_ib_economically_disadvantaged_percent_taking': 'E0BTA',
# 'dropout_all_students_count': 'A0912DR',
'dropout_all_students_percent': 'A0912DR',
# 'dropout_african_american_count': 'B0912DR',
'dropout_african_american_percent': 'B0912DR',
# 'dropout_asian_count': '30912DR',
'dropout_asian_percent': '30912DR',
# 'dropout_hispanic_count': 'H0912DR',
'dropout_hispanic_percent': 'H0912DR',
# 'dropout_american_indian_count': 'I0912DR',
'dropout_american_indian_percent': 'I0912DR',
# 'dropout_pacific_islander_count': '40912DR',
'dropout_pacific_islander_percent': '40912DR',
# 'dropout_two_or_more_races_count': '20912DR',
'dropout_two_or_more_races_percent': '20912DR',
# 'dropout_white_count': 'W0912DR',
'dropout_white_percent': 'W0912DR',
# 'dropout_at_risk_count': 'R0912DR',
'dropout_at_risk_percent': 'R0912DR',
# 'dropout_economically_disadvantaged_count': 'E0912DR',
'dropout_economically_disadvantaged_percent': 'E0912DR',
# 'dropout_limited_english_proficient_count': 'E0912DR',
'dropout_limited_english_proficient_percent': 'E0912DR',
# 'four_year_graduate_all_students_count': 'AGC4X',
'four_year_graduate_all_students_percent': 'AGC4X',
# 'four_year_graduate_african_american_count': 'BGC4X',
'four_year_graduate_african_american_percent': 'BGC4X',
# 'four_year_graduate_american_indian_count': 'IGC4X',
'four_year_graduate_american_indian_percent': 'IGC4X',
# 'four_year_graduate_asian_count': '3GC4X',
'four_year_graduate_asian_percent': '3GC4X',
# 'four_year_graduate_hispanic_count': 'HGC4X',
'four_year_graduate_hispanic_percent': 'HGC4X',
# 'four_year_graduate_pacific_islander_count': '4GC4X',
'four_year_graduate_pacific_islander_percent': '4GC4X',
# 'four_year_graduate_two_or_more_races_count': '2GC4X',
'four_year_graduate_two_or_more_races_percent': '2GC4X',
# 'four_year_graduate_white_count': 'WGC4X',
'four_year_graduate_white_percent': 'WGC4X',
# 'four_year_graduate_at_risk_count': 'RGC4X',
'four_year_graduate_at_risk_percent': 'RGC4X',
# 'four_year_graduate_economically_disadvantaged_count': 'EGC4X',
'four_year_graduate_economically_disadvantaged_percent': 'EGC4X',
# 'four_year_graduate_limited_english_proficient_count': 'L3C4X',
'four_year_graduate_limited_english_proficient_percent': 'L3C4X',
'attendance_rate': 'A0AT',
},
'reference': {
'accountability_rating': '_RATING',
},
}
|
schema = {'staff-and-student-information': {'all_students_count': 'PETALLC', 'african_american_count': 'PETBLAC', 'african_american_percent': 'PETBLAP', 'american_indian_count': 'PETINDC', 'american_indian_percent': 'PETINDP', 'asian_count': 'PETASIC', 'asian_percent': 'PETASIP', 'hispanic_count': 'PETHISC', 'hispanic_percent': 'PETHISP', 'pacific_islander_count': 'PETPCIC', 'pacific_islander_percent': 'PETPCIP', 'two_or_more_races_count': 'PETTWOC', 'two_or_more_races_percent': 'PETTWOP', 'white_count': 'PETWHIC', 'white_percent': 'PETWHIP', 'early_childhood_education_count': 'PETGEEC', 'early_childhood_education_percent': 'PETGEEP', 'prek_count': 'PETGPKC', 'prek_percent': 'PETGPKP', 'kindergarten_count': 'PETGKNC', 'kindergarten_percent': 'PETGKNP', 'first_count': 'PETG01C', 'first_percent': 'PETG01P', 'second_count': 'PETG02C', 'second_percent': 'PETG02P', 'third_count': 'PETG03C', 'third_percent': 'PETG03P', 'fourth_count': 'PETG04C', 'fourth_percent': 'PETG04P', 'fifth_count': 'PETG05C', 'fifth_percent': 'PETG05P', 'sixth_count': 'PETG06C', 'sixth_percent': 'PETG06P', 'seventh_count': 'PETG07C', 'seventh_percent': 'PETG07P', 'eighth_count': 'PETG08C', 'eighth_percent': 'PETG08P', 'ninth_count': 'PETG09C', 'ninth_percent': 'PETG09P', 'tenth_count': 'PETG10C', 'tenth_percent': 'PETG10P', 'eleventh_count': 'PETG11C', 'eleventh_percent': 'PETG11P', 'twelfth_count': 'PETG12C', 'twelfth_percent': 'PETG12P', 'at_risk_count': 'PETRSKC', 'at_risk_percent': 'PETRSKP', 'economically_disadvantaged_count': 'PETECOC', 'economically_disadvantaged_percent': 'PETECOP', 'limited_english_proficient_count': 'PETLEPC', 'limited_english_proficient_percent': 'PETLEPP', 'bilingual_esl_count': 'PETBILC', 'bilingual_esl_percent': 'PETBILP', 'career_technical_education_count': 'PETVOCC', 'career_technical_education_percent': 'PETVOCP', 'gifted_and_talented_count': 'PETGIFC', 'gifted_and_talented_percent': 'PETGIFP', 'special_education_count': 'PETSPEC', 'special_education_percent': 'PETSPEP', 'class_size_avg_kindergarten': 'PCTGKGA', 'class_size_avg_first': 'PCTG01A', 'class_size_avg_second': 'PCTG02A', 'class_size_avg_third': 'PCTG03A', 'class_size_avg_fourth': 'PCTG04A', 'class_size_avg_fifth': 'PCTG05A', 'class_size_avg_sixth': 'PCTG06A', 'class_size_avg_mixed_elementary': 'PCTGMEA', 'class_size_avg_secondary_english': 'PCTENGA', 'class_size_avg_secondary_foreign_language': 'PCTFLAA', 'class_size_avg_secondary_math': 'PCTMATA', 'class_size_avg_secondary_science': 'PCTSCIA', 'class_size_avg_secondary_social_studies': 'PCTSOCA', 'students_per_teacher': 'PSTKIDR', 'teacher_avg_tenure': 'PSTTENA', 'teacher_avg_experience': 'PSTEXPA', 'teacher_avg_base_salary': 'PSTTOSA', 'teacher_avg_beginning_salary': 'PST00SA', 'teacher_avg_1_to_5_year_salary': 'PST01SA', 'teacher_avg_6_to_10_year_salary': 'PST06SA', 'teacher_avg_11_to_20_year_salary': 'PST11SA', 'teacher_avg_20_plus_year_salary': 'PST20SA', 'teacher_total_fte_count': 'PSTTOFC', 'teacher_african_american_fte_count': 'PSTBLFC', 'teacher_american_indian_fte_count': 'PSTINFC', 'teacher_asian_fte_count': 'PSTASFC', 'teacher_hispanic_fte_count': 'PSTHIFC', 'teacher_pacific_islander_fte_count': 'PSTPIFC', 'teacher_two_or_more_races_fte_count': 'PSTTWFC', 'teacher_white_fte_count': 'PSTWHFC', 'teacher_total_fte_percent': 'PSTTOFC', 'teacher_african_american_fte_percent': 'PSTBLFP', 'teacher_american_indian_fte_percent': 'PSTINFP', 'teacher_asian_fte_percent': 'PSTASFP', 'teacher_hispanic_fte_percent': 'PSTHIFP', 'teacher_pacific_islander_fte_percent': 'PSTPIFP', 'teacher_two_or_more_races_fte_percent': 'PSTTWFP', 'teacher_white_fte_percent': 'PSTWHFP'}, 'postsecondary-readiness-and-non-staar-performance-indicators': {'college_ready_graduates_english_all_students_percent': 'ACRR', 'college_ready_graduates_english_african_american_percent': 'BCRR', 'college_ready_graduates_english_american_indian_percent': 'ICRR', 'college_ready_graduates_english_asian_percent': '3CRR', 'college_ready_graduates_english_hispanic_percent': 'HCRR', 'college_ready_graduates_english_pacific_islander_percent': '4CRR', 'college_ready_graduates_english_two_or_more_races_percent': '2CRR', 'college_ready_graduates_english_white_percent': 'WCRR', 'college_ready_graduates_english_economically_disadvantaged_percent': 'ECRR', 'college_ready_graduates_english_limited_english_proficient_percent': 'LCRR', 'college_ready_graduates_english_at_risk_percent': 'RCRR', 'college_ready_graduates_math_all_students_percent': 'ACRM', 'college_ready_graduates_math_african_american_percent': 'BCRM', 'college_ready_graduates_math_american_indian_percent': 'ICRM', 'college_ready_graduates_math_asian_percent': '3CRM', 'college_ready_graduates_math_hispanic_percent': 'HCRM', 'college_ready_graduates_math_pacific_islander_percent': '4CRM', 'college_ready_graduates_math_two_or_more_races_percent': '2CRM', 'college_ready_graduates_math_white_percent': 'WCRM', 'college_ready_graduates_math_economically_disadvantaged_percent': 'ECRM', 'college_ready_graduates_math_limited_english_proficient_percent': 'LCRM', 'college_ready_graduates_math_at_risk_percent': 'RCRM', 'college_ready_graduates_both_all_students_percent': 'ACRB', 'college_ready_graduates_both_african_american_percent': 'BCRB', 'college_ready_graduates_both_asian_percent': '3CRB', 'college_ready_graduates_both_hispanic_percent': 'HCRB', 'college_ready_graduates_both_american_indian_percent': 'ICRB', 'college_ready_graduates_both_pacific_islander_percent': '4CRB', 'college_ready_graduates_both_two_or_more_races_percent': '2CRB', 'college_ready_graduates_both_white_percent': 'WCRB', 'college_ready_graduates_both_economically_disadvantaged_percent': 'ECRB', 'college_ready_graduates_both_limited_english_proficient_percent': 'LCRB', 'college_ready_graduates_both_at_risk_percent': 'RCRB', 'avg_sat_score_all_students': 'A0CSA', 'avg_sat_score_african_american': 'B0CSA', 'avg_sat_score_american_indian': 'I0CSA', 'avg_sat_score_asian': '30CSA', 'avg_sat_score_hispanic': 'H0CSA', 'avg_sat_score_pacific_islander': '40CSA', 'avg_sat_score_two_or_more_races': '20CSA', 'avg_sat_score_white': 'W0CSA', 'avg_sat_score_economically_disadvantaged': 'E0CSA', 'avg_act_score_all_students': 'A0CAA', 'avg_act_score_african_american': 'B0CAA', 'avg_act_score_american_indian': 'I0CAA', 'avg_act_score_asian': '30CAA', 'avg_act_score_hispanic': 'H0CAA', 'avg_act_score_pacific_islander': '40CAA', 'avg_act_score_two_or_more_races': '20CAA', 'avg_act_score_white': 'W0CAA', 'avg_act_score_economically_disadvantaged': 'E0CAA', 'ap_ib_all_students_percent_above_criterion': 'A0BKA', 'ap_ib_african_american_percent_above_criterion': 'B0BKA', 'ap_ib_asian_percent_above_criterion': '30BKA', 'ap_ib_hispanic_percent_above_criterion': 'H0BKA', 'ap_ib_american_indian_percent_above_criterion': 'I0BKA', 'ap_ib_pacific_islander_percent_above_criterion': '40BKA', 'ap_ib_two_or_more_races_percent_above_criterion': '20BKA', 'ap_ib_white_percent_above_criterion': 'W0BKA', 'ap_ib_economically_disadvantaged_percent_above_criterion': 'E0BKA', 'ap_ib_all_students_percent_taking': 'A0BTA', 'ap_ib_african_american_percent_taking': 'B0BTA', 'ap_ib_asian_percent_taking': '30BTA', 'ap_ib_hispanic_percent_taking': 'H0BTA', 'ap_ib_american_indian_percent_taking': 'I0BTA', 'ap_ib_pacific_islander_percent_taking': '40BTA', 'ap_ib_two_or_more_races_percent_taking': '20BTA', 'ap_ib_white_percent_taking': 'W0BTA', 'ap_ib_economically_disadvantaged_percent_taking': 'E0BTA', 'dropout_all_students_percent': 'A0912DR', 'dropout_african_american_percent': 'B0912DR', 'dropout_asian_percent': '30912DR', 'dropout_hispanic_percent': 'H0912DR', 'dropout_american_indian_percent': 'I0912DR', 'dropout_pacific_islander_percent': '40912DR', 'dropout_two_or_more_races_percent': '20912DR', 'dropout_white_percent': 'W0912DR', 'dropout_at_risk_percent': 'R0912DR', 'dropout_economically_disadvantaged_percent': 'E0912DR', 'dropout_limited_english_proficient_percent': 'E0912DR', 'four_year_graduate_all_students_percent': 'AGC4X', 'four_year_graduate_african_american_percent': 'BGC4X', 'four_year_graduate_american_indian_percent': 'IGC4X', 'four_year_graduate_asian_percent': '3GC4X', 'four_year_graduate_hispanic_percent': 'HGC4X', 'four_year_graduate_pacific_islander_percent': '4GC4X', 'four_year_graduate_two_or_more_races_percent': '2GC4X', 'four_year_graduate_white_percent': 'WGC4X', 'four_year_graduate_at_risk_percent': 'RGC4X', 'four_year_graduate_economically_disadvantaged_percent': 'EGC4X', 'four_year_graduate_limited_english_proficient_percent': 'L3C4X', 'attendance_rate': 'A0AT'}, 'reference': {'accountability_rating': '_RATING'}}
|
class ClientError(Exception):
"""Common base class for all client errors."""
class NotFoundError(ClientError):
"""URL was not found."""
class InvalidRequestError(ClientError):
"""The API request was invalid."""
class TimeoutError(ClientError): # pylint: disable=redefined-builtin
"""The API server did not respond before the timeout expired."""
|
class Clienterror(Exception):
"""Common base class for all client errors."""
class Notfounderror(ClientError):
"""URL was not found."""
class Invalidrequesterror(ClientError):
"""The API request was invalid."""
class Timeouterror(ClientError):
"""The API server did not respond before the timeout expired."""
|
# Leo colorizer control file for bbj mode.
# This file is in the public domain.
# Properties for bbj mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"wordBreakChars": ",+-=<>/?^&*",
}
# Attributes dict for bbj_main ruleset.
bbj_main_attributes_dict = {
"default": "null",
"digit_re": "",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "true",
"no_word_sep": "",
}
# Dictionary of attributes dictionaries for bbj mode.
attributesDictDict = {
"bbj_main": bbj_main_attributes_dict,
}
# Keywords dict for bbj_main ruleset.
bbj_main_keywords_dict = {
"abs": "keyword1",
"addr": "keyword3",
"adjn": "keyword1",
"all": "keyword3",
"argc": "keyword1",
"argv": "keyword1",
"asc": "keyword1",
"ath": "keyword1",
"atn": "keyword1",
"auto": "keyword3",
"background": "keyword1",
"begin": "keyword3",
"bin": "keyword1",
"break": "keyword3",
"bsz": "keyword1",
"call": "keyword3",
"callback": "keyword1",
"case": "keyword3",
"chanopt": "keyword1",
"chdir": "keyword2",
"chn": "keyword3",
"chr": "keyword1",
"cisam": "keyword2",
"clear": "keyword3",
"clipclear": "keyword1",
"clipfromfile": "keyword1",
"clipfromstr": "keyword1",
"clipisformat": "keyword1",
"cliplock": "keyword1",
"clipregformat": "keyword1",
"cliptofile": "keyword1",
"cliptostr": "keyword1",
"clipunlock": "keyword1",
"close": "keyword2",
"continue": "keyword2",
"cos": "keyword1",
"cpl": "keyword1",
"crc": "keyword1",
"crc16": "keyword1",
"ctl": "keyword3",
"ctrl": "keyword1",
"cvs": "keyword1",
"cvt": "keyword1",
"data": "keyword3",
"date": "keyword1",
"day": "keyword3",
"dec": "keyword1",
"def": "keyword3",
"default": "keyword3",
"defend": "keyword3",
"delete": "keyword3",
"dim": "keyword3",
"dims": "keyword1",
"dir": "keyword2",
"direct": "keyword2",
"disable": "keyword2",
"dom": "keyword2",
"dread": "keyword3",
"drop": "keyword3",
"dsk": "keyword1",
"dsz": "keyword1",
"dump": "keyword2",
"edit": "keyword3",
"else": "keyword3",
"enable": "keyword2",
"end": "keyword2",
"endif": "keyword3",
"endtrace": "keyword2",
"enter": "keyword3",
"ept": "keyword1",
"erase": "keyword2",
"err": "keyword3",
"errmes": "keyword1",
"escape": "keyword3",
"escoff": "keyword3",
"escon": "keyword3",
"execute": "keyword3",
"exit": "keyword3",
"exitto": "keyword3",
"extract": "keyword2",
"fattr": "keyword1",
"fbin": "keyword1",
"fdec": "keyword1",
"fi": "keyword3",
"fid": "keyword2",
"field": "keyword1",
"file": "keyword2",
"fileopt": "keyword1",
"fill": "keyword1",
"fin": "keyword2",
"find": "keyword2",
"floatingpoint": "keyword1",
"for": "keyword3",
"fpt": "keyword1",
"from": "keyword2",
"gap": "keyword1",
"gosub": "keyword3",
"goto": "keyword3",
"hsa": "keyword1",
"hsh": "keyword1",
"hta": "keyword1",
"if": "keyword3",
"iff": "keyword3",
"imp": "keyword1",
"ind": "keyword2",
"indexed": "keyword2",
"info": "keyword1",
"initfile": "keyword3",
"input": "keyword2",
"inpute": "keyword2",
"inputn": "keyword2",
"int": "keyword1",
"iol": "keyword2",
"iolist": "keyword2",
"ior": "keyword3",
"jul": "keyword1",
"key": "keyword2",
"keyf": "keyword2",
"keyl": "keyword2",
"keyn": "keyword2",
"keyp": "keyword2",
"kgen": "keyword2",
"knum": "keyword2",
"lcheckin": "keyword1",
"lcheckout": "keyword1",
"len": "keyword1",
"let": "keyword3",
"linfo": "keyword1",
"list": "keyword2",
"load": "keyword2",
"lock": "keyword2",
"log": "keyword1",
"lrc": "keyword1",
"lst": "keyword1",
"mask": "keyword1",
"max": "keyword1",
"menuinfo": "keyword1",
"merge": "keyword2",
"min": "keyword1",
"mkdir": "keyword2",
"mkeyed": "keyword2",
"mod": "keyword1",
"msgbox": "keyword1",
"neval": "keyword1",
"next": "keyword3",
"nfield": "keyword1",
"not": "keyword3",
"notice": "keyword1",
"noticetpl": "keyword1",
"num": "keyword1",
"on": "keyword3",
"open": "keyword2",
"opts": "keyword3",
"or": "keyword3",
"pad": "keyword1",
"pck": "keyword1",
"pfx": "keyword3",
"pgm": "keyword1",
"pos": "keyword1",
"precision": "keyword3",
"prefix": "keyword2",
"print": "keyword2",
"process_events": "keyword1",
"program": "keyword1",
"psz": "keyword1",
"pub": "keyword1",
"read": "keyword2",
"read_resource": "keyword2",
"record": "keyword2",
"release": "keyword3",
"remove": "keyword2",
"remove_callback": "keyword1",
"rename": "keyword2",
"renum": "keyword3",
"repeat": "keyword3",
"resclose": "keyword2",
"reserve": "keyword1",
"reset": "keyword3",
"resfirst": "keyword2",
"resget": "keyword2",
"resinfo": "keyword2",
"resnext": "keyword2",
"resopen": "keyword2",
"restore": "keyword3",
"retry": "keyword3",
"return": "keyword3",
"rev": "keyword2",
"rmdir": "keyword2",
"rnd": "keyword1",
"round": "keyword1",
"run": "keyword3",
"save": "keyword2",
"scall": "keyword1",
"select": "keyword2",
"sendmsg": "keyword1",
"serial": "keyword2",
"set_case_sensitive_off": "keyword3",
"set_case_sensitive_on": "keyword3",
"setday": "keyword2",
"setdrive": "keyword2",
"seterr": "keyword3",
"setesc": "keyword3",
"setopts": "keyword3",
"settime": "keyword3",
"settrace": "keyword2",
"seval": "keyword1",
"sgn": "keyword1",
"sin": "keyword1",
"siz": "keyword2",
"sort": "keyword2",
"sqlchn": "keyword2",
"sqlclose": "keyword2",
"sqlerr": "keyword2",
"sqlexec": "keyword2",
"sqlfetch": "keyword2",
"sqllist": "keyword2",
"sqlopen": "keyword2",
"sqlprep": "keyword2",
"sqlset": "keyword2",
"sqltables": "keyword2",
"sqltmpl": "keyword2",
"sqlunt": "keyword2",
"sqr": "keyword1",
"ssn": "keyword3",
"ssort": "keyword1",
"ssz": "keyword1",
"start": "keyword3",
"stbl": "keyword1",
"step": "keyword3",
"stop": "keyword3",
"str": "keyword1",
"string": "keyword2",
"swap": "keyword1",
"swend": "keyword3",
"switch": "keyword3",
"sys": "keyword1",
"table": "keyword2",
"tbl": "keyword2",
"tcb": "keyword1",
"then": "keyword3",
"tim": "keyword2",
"tmpl": "keyword1",
"to": "keyword3",
"tsk": "keyword1",
"unlock": "keyword2",
"unt": "keyword3",
"until": "keyword3",
"upk": "keyword1",
"wait": "keyword3",
"wend": "keyword3",
"where": "keyword2",
"while": "keyword3",
"winfirst": "keyword1",
"wininfo": "keyword1",
"winnext": "keyword1",
"write": "keyword2",
"xfid": "keyword2",
"xfile": "keyword2",
"xfin": "keyword2",
"xor": "keyword3",
}
# Dictionary of keywords dictionaries for bbj mode.
keywordsDictDict = {
"bbj_main": bbj_main_keywords_dict,
}
# Rules for bbj_main ruleset.
def bbj_rule0(colorer, s, i):
return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def bbj_rule1(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def bbj_rule2(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment2", seq="//",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def bbj_rule3(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment2", seq="REM",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def bbj_rule4(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule5(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule6(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule7(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="+",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule8(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="-",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule9(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule10(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="*",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule11(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<>",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="^",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="and",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="or",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def bbj_rule17(colorer, s, i):
return colorer.match_mark_previous(s, i, kind="label", pattern=":",
at_line_start=True, at_whitespace_end=False, at_word_start=False, exclude_match=True)
def bbj_rule18(colorer, s, i):
return colorer.match_mark_previous(s, i, kind="function", pattern="(",
at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=True)
def bbj_rule19(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for bbj_main ruleset.
rulesDict1 = {
"\"": [bbj_rule1,],
"(": [bbj_rule18,],
"*": [bbj_rule10,],
"+": [bbj_rule7,],
"-": [bbj_rule8,],
"/": [bbj_rule0,bbj_rule2,bbj_rule9,],
"0": [bbj_rule19,],
"1": [bbj_rule19,],
"2": [bbj_rule19,],
"3": [bbj_rule19,],
"4": [bbj_rule19,],
"5": [bbj_rule19,],
"6": [bbj_rule19,],
"7": [bbj_rule19,],
"8": [bbj_rule19,],
"9": [bbj_rule19,],
":": [bbj_rule17,],
"<": [bbj_rule6,bbj_rule12,bbj_rule13,],
"=": [bbj_rule4,],
">": [bbj_rule5,bbj_rule11,],
"@": [bbj_rule19,],
"A": [bbj_rule19,],
"B": [bbj_rule19,],
"C": [bbj_rule19,],
"D": [bbj_rule19,],
"E": [bbj_rule19,],
"F": [bbj_rule19,],
"G": [bbj_rule19,],
"H": [bbj_rule19,],
"I": [bbj_rule19,],
"J": [bbj_rule19,],
"K": [bbj_rule19,],
"L": [bbj_rule19,],
"M": [bbj_rule19,],
"N": [bbj_rule19,],
"O": [bbj_rule19,],
"P": [bbj_rule19,],
"Q": [bbj_rule19,],
"R": [bbj_rule3,bbj_rule19,],
"S": [bbj_rule19,],
"T": [bbj_rule19,],
"U": [bbj_rule19,],
"V": [bbj_rule19,],
"W": [bbj_rule19,],
"X": [bbj_rule19,],
"Y": [bbj_rule19,],
"Z": [bbj_rule19,],
"^": [bbj_rule14,],
"_": [bbj_rule19,],
"a": [bbj_rule15,bbj_rule19,],
"b": [bbj_rule19,],
"c": [bbj_rule19,],
"d": [bbj_rule19,],
"e": [bbj_rule19,],
"f": [bbj_rule19,],
"g": [bbj_rule19,],
"h": [bbj_rule19,],
"i": [bbj_rule19,],
"j": [bbj_rule19,],
"k": [bbj_rule19,],
"l": [bbj_rule19,],
"m": [bbj_rule19,],
"n": [bbj_rule19,],
"o": [bbj_rule16,bbj_rule19,],
"p": [bbj_rule19,],
"q": [bbj_rule19,],
"r": [bbj_rule19,],
"s": [bbj_rule19,],
"t": [bbj_rule19,],
"u": [bbj_rule19,],
"v": [bbj_rule19,],
"w": [bbj_rule19,],
"x": [bbj_rule19,],
"y": [bbj_rule19,],
"z": [bbj_rule19,],
}
# x.rulesDictDict for bbj mode.
rulesDictDict = {
"bbj_main": rulesDict1,
}
# Import dict for bbj mode.
importDict = {}
|
properties = {'commentEnd': '*/', 'commentStart': '/*', 'wordBreakChars': ',+-=<>/?^&*'}
bbj_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''}
attributes_dict_dict = {'bbj_main': bbj_main_attributes_dict}
bbj_main_keywords_dict = {'abs': 'keyword1', 'addr': 'keyword3', 'adjn': 'keyword1', 'all': 'keyword3', 'argc': 'keyword1', 'argv': 'keyword1', 'asc': 'keyword1', 'ath': 'keyword1', 'atn': 'keyword1', 'auto': 'keyword3', 'background': 'keyword1', 'begin': 'keyword3', 'bin': 'keyword1', 'break': 'keyword3', 'bsz': 'keyword1', 'call': 'keyword3', 'callback': 'keyword1', 'case': 'keyword3', 'chanopt': 'keyword1', 'chdir': 'keyword2', 'chn': 'keyword3', 'chr': 'keyword1', 'cisam': 'keyword2', 'clear': 'keyword3', 'clipclear': 'keyword1', 'clipfromfile': 'keyword1', 'clipfromstr': 'keyword1', 'clipisformat': 'keyword1', 'cliplock': 'keyword1', 'clipregformat': 'keyword1', 'cliptofile': 'keyword1', 'cliptostr': 'keyword1', 'clipunlock': 'keyword1', 'close': 'keyword2', 'continue': 'keyword2', 'cos': 'keyword1', 'cpl': 'keyword1', 'crc': 'keyword1', 'crc16': 'keyword1', 'ctl': 'keyword3', 'ctrl': 'keyword1', 'cvs': 'keyword1', 'cvt': 'keyword1', 'data': 'keyword3', 'date': 'keyword1', 'day': 'keyword3', 'dec': 'keyword1', 'def': 'keyword3', 'default': 'keyword3', 'defend': 'keyword3', 'delete': 'keyword3', 'dim': 'keyword3', 'dims': 'keyword1', 'dir': 'keyword2', 'direct': 'keyword2', 'disable': 'keyword2', 'dom': 'keyword2', 'dread': 'keyword3', 'drop': 'keyword3', 'dsk': 'keyword1', 'dsz': 'keyword1', 'dump': 'keyword2', 'edit': 'keyword3', 'else': 'keyword3', 'enable': 'keyword2', 'end': 'keyword2', 'endif': 'keyword3', 'endtrace': 'keyword2', 'enter': 'keyword3', 'ept': 'keyword1', 'erase': 'keyword2', 'err': 'keyword3', 'errmes': 'keyword1', 'escape': 'keyword3', 'escoff': 'keyword3', 'escon': 'keyword3', 'execute': 'keyword3', 'exit': 'keyword3', 'exitto': 'keyword3', 'extract': 'keyword2', 'fattr': 'keyword1', 'fbin': 'keyword1', 'fdec': 'keyword1', 'fi': 'keyword3', 'fid': 'keyword2', 'field': 'keyword1', 'file': 'keyword2', 'fileopt': 'keyword1', 'fill': 'keyword1', 'fin': 'keyword2', 'find': 'keyword2', 'floatingpoint': 'keyword1', 'for': 'keyword3', 'fpt': 'keyword1', 'from': 'keyword2', 'gap': 'keyword1', 'gosub': 'keyword3', 'goto': 'keyword3', 'hsa': 'keyword1', 'hsh': 'keyword1', 'hta': 'keyword1', 'if': 'keyword3', 'iff': 'keyword3', 'imp': 'keyword1', 'ind': 'keyword2', 'indexed': 'keyword2', 'info': 'keyword1', 'initfile': 'keyword3', 'input': 'keyword2', 'inpute': 'keyword2', 'inputn': 'keyword2', 'int': 'keyword1', 'iol': 'keyword2', 'iolist': 'keyword2', 'ior': 'keyword3', 'jul': 'keyword1', 'key': 'keyword2', 'keyf': 'keyword2', 'keyl': 'keyword2', 'keyn': 'keyword2', 'keyp': 'keyword2', 'kgen': 'keyword2', 'knum': 'keyword2', 'lcheckin': 'keyword1', 'lcheckout': 'keyword1', 'len': 'keyword1', 'let': 'keyword3', 'linfo': 'keyword1', 'list': 'keyword2', 'load': 'keyword2', 'lock': 'keyword2', 'log': 'keyword1', 'lrc': 'keyword1', 'lst': 'keyword1', 'mask': 'keyword1', 'max': 'keyword1', 'menuinfo': 'keyword1', 'merge': 'keyword2', 'min': 'keyword1', 'mkdir': 'keyword2', 'mkeyed': 'keyword2', 'mod': 'keyword1', 'msgbox': 'keyword1', 'neval': 'keyword1', 'next': 'keyword3', 'nfield': 'keyword1', 'not': 'keyword3', 'notice': 'keyword1', 'noticetpl': 'keyword1', 'num': 'keyword1', 'on': 'keyword3', 'open': 'keyword2', 'opts': 'keyword3', 'or': 'keyword3', 'pad': 'keyword1', 'pck': 'keyword1', 'pfx': 'keyword3', 'pgm': 'keyword1', 'pos': 'keyword1', 'precision': 'keyword3', 'prefix': 'keyword2', 'print': 'keyword2', 'process_events': 'keyword1', 'program': 'keyword1', 'psz': 'keyword1', 'pub': 'keyword1', 'read': 'keyword2', 'read_resource': 'keyword2', 'record': 'keyword2', 'release': 'keyword3', 'remove': 'keyword2', 'remove_callback': 'keyword1', 'rename': 'keyword2', 'renum': 'keyword3', 'repeat': 'keyword3', 'resclose': 'keyword2', 'reserve': 'keyword1', 'reset': 'keyword3', 'resfirst': 'keyword2', 'resget': 'keyword2', 'resinfo': 'keyword2', 'resnext': 'keyword2', 'resopen': 'keyword2', 'restore': 'keyword3', 'retry': 'keyword3', 'return': 'keyword3', 'rev': 'keyword2', 'rmdir': 'keyword2', 'rnd': 'keyword1', 'round': 'keyword1', 'run': 'keyword3', 'save': 'keyword2', 'scall': 'keyword1', 'select': 'keyword2', 'sendmsg': 'keyword1', 'serial': 'keyword2', 'set_case_sensitive_off': 'keyword3', 'set_case_sensitive_on': 'keyword3', 'setday': 'keyword2', 'setdrive': 'keyword2', 'seterr': 'keyword3', 'setesc': 'keyword3', 'setopts': 'keyword3', 'settime': 'keyword3', 'settrace': 'keyword2', 'seval': 'keyword1', 'sgn': 'keyword1', 'sin': 'keyword1', 'siz': 'keyword2', 'sort': 'keyword2', 'sqlchn': 'keyword2', 'sqlclose': 'keyword2', 'sqlerr': 'keyword2', 'sqlexec': 'keyword2', 'sqlfetch': 'keyword2', 'sqllist': 'keyword2', 'sqlopen': 'keyword2', 'sqlprep': 'keyword2', 'sqlset': 'keyword2', 'sqltables': 'keyword2', 'sqltmpl': 'keyword2', 'sqlunt': 'keyword2', 'sqr': 'keyword1', 'ssn': 'keyword3', 'ssort': 'keyword1', 'ssz': 'keyword1', 'start': 'keyword3', 'stbl': 'keyword1', 'step': 'keyword3', 'stop': 'keyword3', 'str': 'keyword1', 'string': 'keyword2', 'swap': 'keyword1', 'swend': 'keyword3', 'switch': 'keyword3', 'sys': 'keyword1', 'table': 'keyword2', 'tbl': 'keyword2', 'tcb': 'keyword1', 'then': 'keyword3', 'tim': 'keyword2', 'tmpl': 'keyword1', 'to': 'keyword3', 'tsk': 'keyword1', 'unlock': 'keyword2', 'unt': 'keyword3', 'until': 'keyword3', 'upk': 'keyword1', 'wait': 'keyword3', 'wend': 'keyword3', 'where': 'keyword2', 'while': 'keyword3', 'winfirst': 'keyword1', 'wininfo': 'keyword1', 'winnext': 'keyword1', 'write': 'keyword2', 'xfid': 'keyword2', 'xfile': 'keyword2', 'xfin': 'keyword2', 'xor': 'keyword3'}
keywords_dict_dict = {'bbj_main': bbj_main_keywords_dict}
def bbj_rule0(colorer, s, i):
return colorer.match_span(s, i, kind='comment1', begin='/*', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def bbj_rule1(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def bbj_rule2(colorer, s, i):
return colorer.match_eol_span(s, i, kind='comment2', seq='//', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def bbj_rule3(colorer, s, i):
return colorer.match_eol_span(s, i, kind='comment2', seq='REM', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def bbj_rule4(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule5(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule6(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule7(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule8(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='-', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule9(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule10(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='*', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule11(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='^', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='and', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='or', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def bbj_rule17(colorer, s, i):
return colorer.match_mark_previous(s, i, kind='label', pattern=':', at_line_start=True, at_whitespace_end=False, at_word_start=False, exclude_match=True)
def bbj_rule18(colorer, s, i):
return colorer.match_mark_previous(s, i, kind='function', pattern='(', at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=True)
def bbj_rule19(colorer, s, i):
return colorer.match_keywords(s, i)
rules_dict1 = {'"': [bbj_rule1], '(': [bbj_rule18], '*': [bbj_rule10], '+': [bbj_rule7], '-': [bbj_rule8], '/': [bbj_rule0, bbj_rule2, bbj_rule9], '0': [bbj_rule19], '1': [bbj_rule19], '2': [bbj_rule19], '3': [bbj_rule19], '4': [bbj_rule19], '5': [bbj_rule19], '6': [bbj_rule19], '7': [bbj_rule19], '8': [bbj_rule19], '9': [bbj_rule19], ':': [bbj_rule17], '<': [bbj_rule6, bbj_rule12, bbj_rule13], '=': [bbj_rule4], '>': [bbj_rule5, bbj_rule11], '@': [bbj_rule19], 'A': [bbj_rule19], 'B': [bbj_rule19], 'C': [bbj_rule19], 'D': [bbj_rule19], 'E': [bbj_rule19], 'F': [bbj_rule19], 'G': [bbj_rule19], 'H': [bbj_rule19], 'I': [bbj_rule19], 'J': [bbj_rule19], 'K': [bbj_rule19], 'L': [bbj_rule19], 'M': [bbj_rule19], 'N': [bbj_rule19], 'O': [bbj_rule19], 'P': [bbj_rule19], 'Q': [bbj_rule19], 'R': [bbj_rule3, bbj_rule19], 'S': [bbj_rule19], 'T': [bbj_rule19], 'U': [bbj_rule19], 'V': [bbj_rule19], 'W': [bbj_rule19], 'X': [bbj_rule19], 'Y': [bbj_rule19], 'Z': [bbj_rule19], '^': [bbj_rule14], '_': [bbj_rule19], 'a': [bbj_rule15, bbj_rule19], 'b': [bbj_rule19], 'c': [bbj_rule19], 'd': [bbj_rule19], 'e': [bbj_rule19], 'f': [bbj_rule19], 'g': [bbj_rule19], 'h': [bbj_rule19], 'i': [bbj_rule19], 'j': [bbj_rule19], 'k': [bbj_rule19], 'l': [bbj_rule19], 'm': [bbj_rule19], 'n': [bbj_rule19], 'o': [bbj_rule16, bbj_rule19], 'p': [bbj_rule19], 'q': [bbj_rule19], 'r': [bbj_rule19], 's': [bbj_rule19], 't': [bbj_rule19], 'u': [bbj_rule19], 'v': [bbj_rule19], 'w': [bbj_rule19], 'x': [bbj_rule19], 'y': [bbj_rule19], 'z': [bbj_rule19]}
rules_dict_dict = {'bbj_main': rulesDict1}
import_dict = {}
|
#
# Time complexity:
# O(lines*columns) (worst case, where all the neighbours have the same color)
# O(1) (best case, where no neighbour has the same color)
#
# Space complexity:
# O(1) (color changes applied in place)
#
def flood_fill(screen, lines, columns, line, column, color):
def inbound(l, c):
return (l >= 0 and l < lines) and (c >= 0 and c < columns)
def key(l, c):
return "{},{}".format(l, c)
stack = [[line, column]]
visited = set()
while stack:
l, c = stack.pop()
# Mark the cell as visited
visited.add(key(l, c))
# Schedule the visit to all neighbours (except diagonal),
# which weren't visited yet and has the same color
neighbours = [
[l-1, c ],
[l+1, c ],
[l , c-1],
[l , c+1]
]
for nl, nc in neighbours:
if inbound(nl, nc) and key(nl, nc) not in visited and screen[nl][nc] == screen[l][c]:
stack.append([nl, nc])
# Paint the current cell
screen[l][c] = color
return screen
|
def flood_fill(screen, lines, columns, line, column, color):
def inbound(l, c):
return (l >= 0 and l < lines) and (c >= 0 and c < columns)
def key(l, c):
return '{},{}'.format(l, c)
stack = [[line, column]]
visited = set()
while stack:
(l, c) = stack.pop()
visited.add(key(l, c))
neighbours = [[l - 1, c], [l + 1, c], [l, c - 1], [l, c + 1]]
for (nl, nc) in neighbours:
if inbound(nl, nc) and key(nl, nc) not in visited and (screen[nl][nc] == screen[l][c]):
stack.append([nl, nc])
screen[l][c] = color
return screen
|
def __residuumSign(self):
if self.outcome == 0:
return -1
else: return 1
|
def __residuum_sign(self):
if self.outcome == 0:
return -1
else:
return 1
|
# -*- coding: utf-8 -*-
class RedisServiceException(Exception):
pass
|
class Redisserviceexception(Exception):
pass
|
def main(request, response):
headers = [("Content-Type", "text/javascript")]
values = []
for key in request.cookies:
for cookie in request.cookies.get_list(key):
values.append('"%s": "%s"' % (key, cookie.value))
# Update the counter to change the script body for every request to trigger
# update of the service worker.
key = request.GET['key']
counter = request.server.stash.take(key)
if counter is None:
counter = 0
counter += 1
request.server.stash.put(key, counter)
body = """
// %d
self.addEventListener('message', e => {
e.source.postMessage({%s})
});""" % (counter, ','.join(values))
return headers, body
|
def main(request, response):
headers = [('Content-Type', 'text/javascript')]
values = []
for key in request.cookies:
for cookie in request.cookies.get_list(key):
values.append('"%s": "%s"' % (key, cookie.value))
key = request.GET['key']
counter = request.server.stash.take(key)
if counter is None:
counter = 0
counter += 1
request.server.stash.put(key, counter)
body = "\n// %d\nself.addEventListener('message', e => {\n e.source.postMessage({%s})\n});" % (counter, ','.join(values))
return (headers, body)
|
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
n = len(target)
maxMask = 1 << n
# dp[i] := min # of stickers to spell out i,
# where i is the bit representation of target
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(maxMask):
if dp[mask] == math.inf:
continue
# try to expand from `mask` by using each sticker
for sticker in stickers:
superMask = mask
for c in sticker:
for i, t in enumerate(target):
# try to apply it on a missing char
if c == t and not (superMask >> i & 1):
superMask |= 1 << i
break
dp[superMask] = min(dp[superMask], dp[mask] + 1)
return -1 if dp[-1] == math.inf else dp[-1]
|
class Solution:
def min_stickers(self, stickers: List[str], target: str) -> int:
n = len(target)
max_mask = 1 << n
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(maxMask):
if dp[mask] == math.inf:
continue
for sticker in stickers:
super_mask = mask
for c in sticker:
for (i, t) in enumerate(target):
if c == t and (not superMask >> i & 1):
super_mask |= 1 << i
break
dp[superMask] = min(dp[superMask], dp[mask] + 1)
return -1 if dp[-1] == math.inf else dp[-1]
|
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# A positive real number is given. Print its fractional part.
# -----------------------------------------------------------
def get_fractional_part(number: float)-> float:
return float(number - (int(number // 1)))
print(get_fractional_part(float(input())))
|
def get_fractional_part(number: float) -> float:
return float(number - int(number // 1))
print(get_fractional_part(float(input())))
|
"""
File: booleans.py
Copyright (c) 2016 Callie Enfield
License: MIT
This code was used to simply gain a better understanding of what different boolean expressions will do.
"""
C = 41 #There will be no output. This expression is setting the variable 'C' equal to 41.
C == 40 #The output will be 'False'. 40 is being compared to 0.
C != 40 and C < 41 #The output will be 'False',since both conditions are not true.
C != 40 or C < 41 #The output will be 'True', since the first condition is true, despite the second condition being false.
not C == 40 #The output will be 'True'. Because of the 'not' at the beginning, the output is reversed. The condition is False, but because of the 'not' the output will be 'True'.
not C > 40 #The output will be 'False'. The condition is true, but because of the 'not' at the beginning of the expression, the output will be reversed.
C <= 41 #The output will be 'True'.
not False #The output will be 'True'.
True and False #The output will be 'False'.
False or True #The output will be 'True'.
False or False or False #The output will be 'False'.
True and True and False #The output will be 'False'.
False == 0 #The output will be 'True'.
True == 0 #The output will be 'False'.
True == 1 #The output will be 'True'.
|
"""
File: booleans.py
Copyright (c) 2016 Callie Enfield
License: MIT
This code was used to simply gain a better understanding of what different boolean expressions will do.
"""
c = 41
C == 40
C != 40 and C < 41
C != 40 or C < 41
not C == 40
not C > 40
C <= 41
not False
True and False
False or True
False or False or False
True and True and False
False == 0
True == 0
True == 1
|
def hello():
print(f"Hello, world!")
if __name__ == '__main__':
hello()
|
def hello():
print(f'Hello, world!')
if __name__ == '__main__':
hello()
|
class IAuthenticationModule:
""" Provides the base authentication interface for Web client authentication modules. """
def Authenticate(self, challenge, request, credentials):
"""
Authenticate(self: IAuthenticationModule,challenge: str,request: WebRequest,credentials: ICredentials) -> Authorization
Returns an instance of the System.Net.Authorization class in respose to an authentication
challenge from a server.
challenge: The authentication challenge sent by the server.
request: The System.Net.WebRequest instance associated with the challenge.
credentials: The credentials associated with the challenge.
Returns: An System.Net.Authorization instance containing the authorization message for the request,or
null if the challenge cannot be handled.
"""
pass
def PreAuthenticate(self, request, credentials):
"""
PreAuthenticate(self: IAuthenticationModule,request: WebRequest,credentials: ICredentials) -> Authorization
Returns an instance of the System.Net.Authorization class for an authentication request to a
server.
request: The System.Net.WebRequest instance associated with the authentication request.
credentials: The credentials associated with the authentication request.
Returns: An System.Net.Authorization instance containing the authorization message for the request.
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
AuthenticationType = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets the authentication type provided by this authentication module.
Get: AuthenticationType(self: IAuthenticationModule) -> str
"""
CanPreAuthenticate = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets a value indicating whether the authentication module supports preauthentication.
Get: CanPreAuthenticate(self: IAuthenticationModule) -> bool
"""
|
class Iauthenticationmodule:
""" Provides the base authentication interface for Web client authentication modules. """
def authenticate(self, challenge, request, credentials):
"""
Authenticate(self: IAuthenticationModule,challenge: str,request: WebRequest,credentials: ICredentials) -> Authorization
Returns an instance of the System.Net.Authorization class in respose to an authentication
challenge from a server.
challenge: The authentication challenge sent by the server.
request: The System.Net.WebRequest instance associated with the challenge.
credentials: The credentials associated with the challenge.
Returns: An System.Net.Authorization instance containing the authorization message for the request,or
null if the challenge cannot be handled.
"""
pass
def pre_authenticate(self, request, credentials):
"""
PreAuthenticate(self: IAuthenticationModule,request: WebRequest,credentials: ICredentials) -> Authorization
Returns an instance of the System.Net.Authorization class for an authentication request to a
server.
request: The System.Net.WebRequest instance associated with the authentication request.
credentials: The credentials associated with the authentication request.
Returns: An System.Net.Authorization instance containing the authorization message for the request.
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
authentication_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the authentication type provided by this authentication module.\n\n\n\nGet: AuthenticationType(self: IAuthenticationModule) -> str\n\n\n\n'
can_pre_authenticate = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a value indicating whether the authentication module supports preauthentication.\n\n\n\nGet: CanPreAuthenticate(self: IAuthenticationModule) -> bool\n\n\n\n'
|
js = """
const quote = String.fromCharCode(34);
const newline = String.fromCharCode(10);
const marker = quote + quote + quote;
const quine = 'js = ' + marker + js + marker + newline + 'py = ' + marker + py + marker + py;
exports.handler = async (body, ctx) => {
return new ctx.HTTPResponse({
body: Buffer.from(quine),
});
};
"""
py = """
backtick = chr(96)
newline = chr(10)
quine = 'const js = ' + backtick + js + backtick + ';' + newline + 'const py = ' + backtick + py + backtick + ';' + js
def handler(body, ctx):
return ctx.HTTPResponse(body='{}'.format(quine))
"""
backtick = chr(96)
newline = chr(10)
quine = 'const js = ' + backtick + js + backtick + ';' + newline + 'const py = ' + backtick + py + backtick + ';' + js
def handler(body, ctx):
return ctx.HTTPResponse(body='{}'.format(quine))
|
js = "\nconst quote = String.fromCharCode(34);\nconst newline = String.fromCharCode(10);\nconst marker = quote + quote + quote;\nconst quine = 'js = ' + marker + js + marker + newline + 'py = ' + marker + py + marker + py;\nexports.handler = async (body, ctx) => {\n return new ctx.HTTPResponse({\n body: Buffer.from(quine),\n });\n};\n"
py = "\nbacktick = chr(96)\nnewline = chr(10)\nquine = 'const js = ' + backtick + js + backtick + ';' + newline + 'const py = ' + backtick + py + backtick + ';' + js\ndef handler(body, ctx):\n return ctx.HTTPResponse(body='{}'.format(quine))\n"
backtick = chr(96)
newline = chr(10)
quine = 'const js = ' + backtick + js + backtick + ';' + newline + 'const py = ' + backtick + py + backtick + ';' + js
def handler(body, ctx):
return ctx.HTTPResponse(body='{}'.format(quine))
|
# 8-3
def make_shirt(size, string):
"""Make shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt('M', 'Hello, World')
make_shirt(size='M', string='Hello, World again')
# 8-4
def make_shirt(size='L', string='I love Python'):
"""Make python shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt()
make_shirt(size='M')
make_shirt(string='Hello, World')
# 8-5
def describe_city(name='guangzhou', country='china'):
"""Describe a city you lived in"""
print(name.title() + ' is in ' + country.title())
describe_city('Nanjing')
describe_city(country='united states')
describe_city('palo alto', 'united states')
|
def make_shirt(size, string):
"""Make shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt('M', 'Hello, World')
make_shirt(size='M', string='Hello, World again')
def make_shirt(size='L', string='I love Python'):
"""Make python shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt()
make_shirt(size='M')
make_shirt(string='Hello, World')
def describe_city(name='guangzhou', country='china'):
"""Describe a city you lived in"""
print(name.title() + ' is in ' + country.title())
describe_city('Nanjing')
describe_city(country='united states')
describe_city('palo alto', 'united states')
|
variant = dict(
mlflow_uri="http://128.2.210.74:8080",
gpu=False,
algorithm="PPO",
version="normal",
actor_width=64, # Need to tune
critic_width=256,
replay_buffer_size=int(3E3),
algorithm_kwargs=dict(
min_num_steps_before_training=0,
num_epochs=150,
num_eval_steps_per_epoch=1000,
num_train_loops_per_epoch=10,
num_expl_steps_per_train_loop=2048,
num_trains_per_train_loop=100,
batch_size=256,
max_path_length=1000,
clear_buffer_every_train_loop=True,
),
trainer_kwargs=dict(
epsilon=0.2, # Need to tune
discount=.99, # Need to tune
intrinsic_discount=.9999,
policy_lr=3E-4, # Need to tune
val_lr=3E-4, # No need to use different
use_rnd=False,
rnd_coef=5,
predictor_update_proportion=0.05,
),
rnd_kwargs=dict(
rnd_output_size=2,
rnd_lr=3E-4,
rnd_latent_size=2,
use_normaliser=True, # Specifies whether to use observation normalisation for actor & critic
),
target_kwargs=dict(
tdlambda=0.95,
target_lookahead=15,
use_dones_for_rnd_critic=False,
),
policy_kwargs=dict(
std=0.1, # This is a non-learnable constant if set to a scalar value
),
)
# env_variant = dict(
# env_str='Swimmer-v2',
# )
env_variant = dict(
env_str='agnosticmaas-v0',
lam=1,
sigma2=1,
agent_lambda=2,
num_hypotheses=30,
num_timesteps=150,
num_EA_iterations=10,
EA_tolerance=0.0001,
cost_iterations=10,
upper_limit_N=10,
log_space_resolution=100,
MLE_regularizer=.1,
WASSERSTEIN_ITERS=100,
verbose=False,
adaptive_grid=False,
direct_wasserstein=True,
fisher_in_state=True,
reward_shaping=False,
)
|
variant = dict(mlflow_uri='http://128.2.210.74:8080', gpu=False, algorithm='PPO', version='normal', actor_width=64, critic_width=256, replay_buffer_size=int(3000.0), algorithm_kwargs=dict(min_num_steps_before_training=0, num_epochs=150, num_eval_steps_per_epoch=1000, num_train_loops_per_epoch=10, num_expl_steps_per_train_loop=2048, num_trains_per_train_loop=100, batch_size=256, max_path_length=1000, clear_buffer_every_train_loop=True), trainer_kwargs=dict(epsilon=0.2, discount=0.99, intrinsic_discount=0.9999, policy_lr=0.0003, val_lr=0.0003, use_rnd=False, rnd_coef=5, predictor_update_proportion=0.05), rnd_kwargs=dict(rnd_output_size=2, rnd_lr=0.0003, rnd_latent_size=2, use_normaliser=True), target_kwargs=dict(tdlambda=0.95, target_lookahead=15, use_dones_for_rnd_critic=False), policy_kwargs=dict(std=0.1))
env_variant = dict(env_str='agnosticmaas-v0', lam=1, sigma2=1, agent_lambda=2, num_hypotheses=30, num_timesteps=150, num_EA_iterations=10, EA_tolerance=0.0001, cost_iterations=10, upper_limit_N=10, log_space_resolution=100, MLE_regularizer=0.1, WASSERSTEIN_ITERS=100, verbose=False, adaptive_grid=False, direct_wasserstein=True, fisher_in_state=True, reward_shaping=False)
|
#
# PySNMP MIB module ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:50:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint")
etsysModules, = mibBuilder.importSymbols("ENTERASYS-MIB-NAMES", "etsysModules")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
IpAddress, Counter32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, Bits, ModuleIdentity, TimeTicks, ObjectIdentity, MibIdentifier, Counter64, Unsigned32, NotificationType, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "Bits", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "MibIdentifier", "Counter64", "Unsigned32", "NotificationType", "Gauge32")
RowStatus, TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString", "TruthValue")
etsysRadiusAcctClientMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27))
etsysRadiusAcctClientMIB.setRevisions(('2009-08-07 15:48', '2004-11-12 15:23', '2004-09-09 14:37', '2004-08-30 15:55', '2004-08-25 15:03', '2002-09-13 19:30',))
if mibBuilder.loadTexts: etsysRadiusAcctClientMIB.setLastUpdated('200908071548Z')
if mibBuilder.loadTexts: etsysRadiusAcctClientMIB.setOrganization('Enterasys Networks')
etsysRadiusAcctClientMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1))
etsysRadiusAcctClientEnable = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysRadiusAcctClientEnable.setStatus('current')
etsysRadiusAcctClientUpdateInterval = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)).clone(1800)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysRadiusAcctClientUpdateInterval.setStatus('current')
etsysRadiusAcctClientIntervalMinimum = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 2147483647)).clone(600)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysRadiusAcctClientIntervalMinimum.setStatus('current')
etsysRadiusAcctClientServerTable = MibTable((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4), )
if mibBuilder.loadTexts: etsysRadiusAcctClientServerTable.setStatus('current')
etsysRadiusAcctClientServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1), ).setIndexNames((0, "ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerIndex"))
if mibBuilder.loadTexts: etsysRadiusAcctClientServerEntry.setStatus('current')
etsysRadiusAcctClientServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: etsysRadiusAcctClientServerIndex.setStatus('current')
etsysRadiusAcctClientServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerAddressType.setStatus('current')
etsysRadiusAcctClientServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 3), InetAddress().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerAddress.setStatus('current')
etsysRadiusAcctClientServerPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerPortNumber.setStatus('current')
etsysRadiusAcctClientServerSecret = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerSecret.setStatus('current')
etsysRadiusAcctClientServerSecretEntered = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 6), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerSecretEntered.setStatus('current')
etsysRadiusAcctClientServerRetryTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 10)).clone(5)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerRetryTimeout.setStatus('current')
etsysRadiusAcctClientServerRetries = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 20)).clone(2)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerRetries.setStatus('current')
etsysRadiusAcctClientServerClearTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerClearTime.setStatus('deprecated')
etsysRadiusAcctClientServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 10), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerStatus.setStatus('current')
etsysRadiusAcctClientServerUpdateInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), )).clone(-1)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerUpdateInterval.setStatus('current')
etsysRadiusAcctClientServerIntervalMinimum = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(60, 2147483647), )).clone(-1)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: etsysRadiusAcctClientServerIntervalMinimum.setStatus('current')
etsysRadiusAcctClientMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2))
etsysRadiusAcctClientMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1))
etsysRadiusAcctClientMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2))
etsysRadiusAcctClientMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 1)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientEnable"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientUpdateInterval"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientIntervalMinimum"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddressType"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddress"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerPortNumber"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecret"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecretEntered"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetryTimeout"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetries"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerClearTime"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBGroup = etsysRadiusAcctClientMIBGroup.setStatus('deprecated')
etsysRadiusAcctClientMIBGroupV2 = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 2)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientEnable"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientUpdateInterval"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientIntervalMinimum"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddressType"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddress"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerPortNumber"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecret"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecretEntered"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetryTimeout"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetries"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBGroupV2 = etsysRadiusAcctClientMIBGroupV2.setStatus('deprecated')
etsysRadiusAcctClientMIBGroupV3 = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 3)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientEnable"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientUpdateInterval"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientIntervalMinimum"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddressType"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerAddress"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerPortNumber"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecret"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerSecretEntered"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetryTimeout"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerRetries"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerStatus"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerIntervalMinimum"), ("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientServerUpdateInterval"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBGroupV3 = etsysRadiusAcctClientMIBGroupV3.setStatus('current')
etsysRadiusAcctClientMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 2)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBCompliance = etsysRadiusAcctClientMIBCompliance.setStatus('deprecated')
etsysRadiusAcctClientMIBComplianceV2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 3)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientMIBGroupV2"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBComplianceV2 = etsysRadiusAcctClientMIBComplianceV2.setStatus('deprecated')
etsysRadiusAcctClientMIBComplianceV3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 4)).setObjects(("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", "etsysRadiusAcctClientMIBGroupV3"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysRadiusAcctClientMIBComplianceV3 = etsysRadiusAcctClientMIBComplianceV3.setStatus('current')
mibBuilder.exportSymbols("ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB", etsysRadiusAcctClientMIBComplianceV2=etsysRadiusAcctClientMIBComplianceV2, etsysRadiusAcctClientServerClearTime=etsysRadiusAcctClientServerClearTime, etsysRadiusAcctClientServerPortNumber=etsysRadiusAcctClientServerPortNumber, etsysRadiusAcctClientServerAddressType=etsysRadiusAcctClientServerAddressType, etsysRadiusAcctClientIntervalMinimum=etsysRadiusAcctClientIntervalMinimum, etsysRadiusAcctClientServerAddress=etsysRadiusAcctClientServerAddress, etsysRadiusAcctClientServerSecret=etsysRadiusAcctClientServerSecret, etsysRadiusAcctClientMIBCompliances=etsysRadiusAcctClientMIBCompliances, etsysRadiusAcctClientServerIndex=etsysRadiusAcctClientServerIndex, etsysRadiusAcctClientServerRetryTimeout=etsysRadiusAcctClientServerRetryTimeout, etsysRadiusAcctClientMIB=etsysRadiusAcctClientMIB, etsysRadiusAcctClientServerUpdateInterval=etsysRadiusAcctClientServerUpdateInterval, PYSNMP_MODULE_ID=etsysRadiusAcctClientMIB, etsysRadiusAcctClientMIBObjects=etsysRadiusAcctClientMIBObjects, etsysRadiusAcctClientMIBGroupV2=etsysRadiusAcctClientMIBGroupV2, etsysRadiusAcctClientMIBGroup=etsysRadiusAcctClientMIBGroup, etsysRadiusAcctClientServerSecretEntered=etsysRadiusAcctClientServerSecretEntered, etsysRadiusAcctClientServerStatus=etsysRadiusAcctClientServerStatus, etsysRadiusAcctClientServerTable=etsysRadiusAcctClientServerTable, etsysRadiusAcctClientMIBCompliance=etsysRadiusAcctClientMIBCompliance, etsysRadiusAcctClientMIBGroupV3=etsysRadiusAcctClientMIBGroupV3, etsysRadiusAcctClientMIBGroups=etsysRadiusAcctClientMIBGroups, etsysRadiusAcctClientEnable=etsysRadiusAcctClientEnable, etsysRadiusAcctClientServerRetries=etsysRadiusAcctClientServerRetries, etsysRadiusAcctClientUpdateInterval=etsysRadiusAcctClientUpdateInterval, etsysRadiusAcctClientServerEntry=etsysRadiusAcctClientServerEntry, etsysRadiusAcctClientServerIntervalMinimum=etsysRadiusAcctClientServerIntervalMinimum, etsysRadiusAcctClientMIBConformance=etsysRadiusAcctClientMIBConformance, etsysRadiusAcctClientMIBComplianceV3=etsysRadiusAcctClientMIBComplianceV3)
|
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint')
(etsys_modules,) = mibBuilder.importSymbols('ENTERASYS-MIB-NAMES', 'etsysModules')
(inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddress', 'InetAddressType')
(object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup')
(ip_address, counter32, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, bits, module_identity, time_ticks, object_identity, mib_identifier, counter64, unsigned32, notification_type, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Counter32', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'Bits', 'ModuleIdentity', 'TimeTicks', 'ObjectIdentity', 'MibIdentifier', 'Counter64', 'Unsigned32', 'NotificationType', 'Gauge32')
(row_status, textual_convention, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TextualConvention', 'DisplayString', 'TruthValue')
etsys_radius_acct_client_mib = module_identity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27))
etsysRadiusAcctClientMIB.setRevisions(('2009-08-07 15:48', '2004-11-12 15:23', '2004-09-09 14:37', '2004-08-30 15:55', '2004-08-25 15:03', '2002-09-13 19:30'))
if mibBuilder.loadTexts:
etsysRadiusAcctClientMIB.setLastUpdated('200908071548Z')
if mibBuilder.loadTexts:
etsysRadiusAcctClientMIB.setOrganization('Enterasys Networks')
etsys_radius_acct_client_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1))
etsys_radius_acct_client_enable = mib_scalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
etsysRadiusAcctClientEnable.setStatus('current')
etsys_radius_acct_client_update_interval = mib_scalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647)).clone(1800)).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
etsysRadiusAcctClientUpdateInterval.setStatus('current')
etsys_radius_acct_client_interval_minimum = mib_scalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(60, 2147483647)).clone(600)).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
etsysRadiusAcctClientIntervalMinimum.setStatus('current')
etsys_radius_acct_client_server_table = mib_table((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4))
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerTable.setStatus('current')
etsys_radius_acct_client_server_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1)).setIndexNames((0, 'ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerIndex'))
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerEntry.setStatus('current')
etsys_radius_acct_client_server_index = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerIndex.setStatus('current')
etsys_radius_acct_client_server_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 2), inet_address_type().clone('ipv4')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerAddressType.setStatus('current')
etsys_radius_acct_client_server_address = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 3), inet_address().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerAddress.setStatus('current')
etsys_radius_acct_client_server_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)).clone(1813)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerPortNumber.setStatus('current')
etsys_radius_acct_client_server_secret = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 5), octet_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerSecret.setStatus('current')
etsys_radius_acct_client_server_secret_entered = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 6), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerSecretEntered.setStatus('current')
etsys_radius_acct_client_server_retry_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(2, 10)).clone(5)).setUnits('seconds').setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerRetryTimeout.setStatus('current')
etsys_radius_acct_client_server_retries = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 20)).clone(2)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerRetries.setStatus('current')
etsys_radius_acct_client_server_clear_time = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerClearTime.setStatus('deprecated')
etsys_radius_acct_client_server_status = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 10), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerStatus.setStatus('current')
etsys_radius_acct_client_server_update_interval = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 11), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(-1, -1), value_range_constraint(0, 2147483647))).clone(-1)).setUnits('seconds').setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerUpdateInterval.setStatus('current')
etsys_radius_acct_client_server_interval_minimum = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 1, 4, 1, 12), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(-1, -1), value_range_constraint(60, 2147483647))).clone(-1)).setUnits('seconds').setMaxAccess('readcreate')
if mibBuilder.loadTexts:
etsysRadiusAcctClientServerIntervalMinimum.setStatus('current')
etsys_radius_acct_client_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2))
etsys_radius_acct_client_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1))
etsys_radius_acct_client_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2))
etsys_radius_acct_client_mib_group = object_group((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 1)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientEnable'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientUpdateInterval'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientIntervalMinimum'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddressType'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddress'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerPortNumber'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecret'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecretEntered'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetryTimeout'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetries'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerClearTime'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_group = etsysRadiusAcctClientMIBGroup.setStatus('deprecated')
etsys_radius_acct_client_mib_group_v2 = object_group((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 2)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientEnable'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientUpdateInterval'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientIntervalMinimum'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddressType'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddress'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerPortNumber'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecret'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecretEntered'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetryTimeout'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetries'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_group_v2 = etsysRadiusAcctClientMIBGroupV2.setStatus('deprecated')
etsys_radius_acct_client_mib_group_v3 = object_group((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 2, 3)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientEnable'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientUpdateInterval'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientIntervalMinimum'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddressType'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerAddress'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerPortNumber'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecret'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerSecretEntered'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetryTimeout'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerRetries'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerStatus'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerIntervalMinimum'), ('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientServerUpdateInterval'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_group_v3 = etsysRadiusAcctClientMIBGroupV3.setStatus('current')
etsys_radius_acct_client_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 2)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientMIBGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_compliance = etsysRadiusAcctClientMIBCompliance.setStatus('deprecated')
etsys_radius_acct_client_mib_compliance_v2 = module_compliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 3)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientMIBGroupV2'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_compliance_v2 = etsysRadiusAcctClientMIBComplianceV2.setStatus('deprecated')
etsys_radius_acct_client_mib_compliance_v3 = module_compliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 27, 2, 1, 4)).setObjects(('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', 'etsysRadiusAcctClientMIBGroupV3'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsys_radius_acct_client_mib_compliance_v3 = etsysRadiusAcctClientMIBComplianceV3.setStatus('current')
mibBuilder.exportSymbols('ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB', etsysRadiusAcctClientMIBComplianceV2=etsysRadiusAcctClientMIBComplianceV2, etsysRadiusAcctClientServerClearTime=etsysRadiusAcctClientServerClearTime, etsysRadiusAcctClientServerPortNumber=etsysRadiusAcctClientServerPortNumber, etsysRadiusAcctClientServerAddressType=etsysRadiusAcctClientServerAddressType, etsysRadiusAcctClientIntervalMinimum=etsysRadiusAcctClientIntervalMinimum, etsysRadiusAcctClientServerAddress=etsysRadiusAcctClientServerAddress, etsysRadiusAcctClientServerSecret=etsysRadiusAcctClientServerSecret, etsysRadiusAcctClientMIBCompliances=etsysRadiusAcctClientMIBCompliances, etsysRadiusAcctClientServerIndex=etsysRadiusAcctClientServerIndex, etsysRadiusAcctClientServerRetryTimeout=etsysRadiusAcctClientServerRetryTimeout, etsysRadiusAcctClientMIB=etsysRadiusAcctClientMIB, etsysRadiusAcctClientServerUpdateInterval=etsysRadiusAcctClientServerUpdateInterval, PYSNMP_MODULE_ID=etsysRadiusAcctClientMIB, etsysRadiusAcctClientMIBObjects=etsysRadiusAcctClientMIBObjects, etsysRadiusAcctClientMIBGroupV2=etsysRadiusAcctClientMIBGroupV2, etsysRadiusAcctClientMIBGroup=etsysRadiusAcctClientMIBGroup, etsysRadiusAcctClientServerSecretEntered=etsysRadiusAcctClientServerSecretEntered, etsysRadiusAcctClientServerStatus=etsysRadiusAcctClientServerStatus, etsysRadiusAcctClientServerTable=etsysRadiusAcctClientServerTable, etsysRadiusAcctClientMIBCompliance=etsysRadiusAcctClientMIBCompliance, etsysRadiusAcctClientMIBGroupV3=etsysRadiusAcctClientMIBGroupV3, etsysRadiusAcctClientMIBGroups=etsysRadiusAcctClientMIBGroups, etsysRadiusAcctClientEnable=etsysRadiusAcctClientEnable, etsysRadiusAcctClientServerRetries=etsysRadiusAcctClientServerRetries, etsysRadiusAcctClientUpdateInterval=etsysRadiusAcctClientUpdateInterval, etsysRadiusAcctClientServerEntry=etsysRadiusAcctClientServerEntry, etsysRadiusAcctClientServerIntervalMinimum=etsysRadiusAcctClientServerIntervalMinimum, etsysRadiusAcctClientMIBConformance=etsysRadiusAcctClientMIBConformance, etsysRadiusAcctClientMIBComplianceV3=etsysRadiusAcctClientMIBComplianceV3)
|
par = []
impar = []
print('Para o inicio da contagem, inicie com 1 para mostrar os impares e 2 para os pares.')
n1 = int(input('Digite o inico da contagem [ 1 ] [ 2 ]:'))
n2 = int(input('Digite o final da contagem:'))
for c in range(n1, n2+1, 2):
if n1 == 2:
par.append(c)
elif n1 == 1:
impar.append(c)
print(f'Com a contagem de {n1} a {n2}.')
if n1 == 2:
print(f'Temos um total de {par} pares.')
elif n1 == 1:
print(f'E temos o total de {impar} impares.')
|
par = []
impar = []
print('Para o inicio da contagem, inicie com 1 para mostrar os impares e 2 para os pares.')
n1 = int(input('Digite o inico da contagem [ 1 ] [ 2 ]:'))
n2 = int(input('Digite o final da contagem:'))
for c in range(n1, n2 + 1, 2):
if n1 == 2:
par.append(c)
elif n1 == 1:
impar.append(c)
print(f'Com a contagem de {n1} a {n2}.')
if n1 == 2:
print(f'Temos um total de {par} pares.')
elif n1 == 1:
print(f'E temos o total de {impar} impares.')
|
""" Data structures to store CommCareHQ reports """
class Report(object):
""" This class is a generic object for representing data
intended for specific reports. It is mostly useful so that
we can transform these structures arbitrarily into xml,
csv, json, etc. without changing our report generators
"""
def __init__(self, title=''):
self.title = title
self.generating_url = ''
# should be a list of DataSets
self.datasets = []
def __unicode__(self):
string = "Report: " + unicode(self.title) + "\n"
for dataset in self.datasets:
string = string + unicode(dataset)
return string + "\n\n"
def __str__(self):
return unicode(self)
class DataSet(object):
""" represents a set or multiple sets of data
with a common index (x-axis). So, for example, one dataset
could be composed of registrations per x, visits per x,
closures per x, etc. (x being the same for all sets)
"""
def __init__(self, name=''):
self.name = name
self.params = {}
# should be a list of valuesets
self.valuesets = []
self.indices = ''
def __unicode__(self):
string = "DataSet: " + unicode(self.name) + "\n"
for valueset in self.valuesets:
for value in valueset:
string = string + " " + unicode(value) + "\n"
string = string + "\n\n"
return string
class Values(list):
""" represents a set of index/value pairs """
def __init__(self, name=''):
self.stats = {}
# indices are determined on a per-dataset basis
self.name = name
def run_stats(self, stats):
""" calculates statistics
stats: specifies the statistics to return
Given a list of requested statistics, this function populates
self.stats with the computed values. Currently we only support 'sum',
but one can imagine supporting std dev, mean, variance, etc.
"""
if not stats: return
for stat in stats:
if stat == 'sum':
sum = 0
for v in self:
sum = sum + long(v[-1])
self.stats[stat] = sum
|
""" Data structures to store CommCareHQ reports """
class Report(object):
""" This class is a generic object for representing data
intended for specific reports. It is mostly useful so that
we can transform these structures arbitrarily into xml,
csv, json, etc. without changing our report generators
"""
def __init__(self, title=''):
self.title = title
self.generating_url = ''
self.datasets = []
def __unicode__(self):
string = 'Report: ' + unicode(self.title) + '\n'
for dataset in self.datasets:
string = string + unicode(dataset)
return string + '\n\n'
def __str__(self):
return unicode(self)
class Dataset(object):
""" represents a set or multiple sets of data
with a common index (x-axis). So, for example, one dataset
could be composed of registrations per x, visits per x,
closures per x, etc. (x being the same for all sets)
"""
def __init__(self, name=''):
self.name = name
self.params = {}
self.valuesets = []
self.indices = ''
def __unicode__(self):
string = 'DataSet: ' + unicode(self.name) + '\n'
for valueset in self.valuesets:
for value in valueset:
string = string + ' ' + unicode(value) + '\n'
string = string + '\n\n'
return string
class Values(list):
""" represents a set of index/value pairs """
def __init__(self, name=''):
self.stats = {}
self.name = name
def run_stats(self, stats):
""" calculates statistics
stats: specifies the statistics to return
Given a list of requested statistics, this function populates
self.stats with the computed values. Currently we only support 'sum',
but one can imagine supporting std dev, mean, variance, etc.
"""
if not stats:
return
for stat in stats:
if stat == 'sum':
sum = 0
for v in self:
sum = sum + long(v[-1])
self.stats[stat] = sum
|
# Crie um programa onde o usuario digite
# uma expressao qualquer que use parenteses.
# Seu aplicativo devera analisar se a
# expressao passada esta com os
# parenteses abertos e fechados na ordem correta.
expr = str(input('Digite a expressao: '))
pilha = list()
for simb in expr:
if simb == '(':
pilha.append('(')
elif simb == ')':
if len(pilha) > 0:
pilha.pop()
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressao esta valida!')
else:
print('Sua expressao esta errada!')
|
expr = str(input('Digite a expressao: '))
pilha = list()
for simb in expr:
if simb == '(':
pilha.append('(')
elif simb == ')':
if len(pilha) > 0:
pilha.pop()
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressao esta valida!')
else:
print('Sua expressao esta errada!')
|
# Python Program To Sort The Elements Of A Dictionary Based On A Key Or Value
'''
Function Name : Sort Elements Of Dictionary Based On Key, Value.
Function Date : 13 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
'''
colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}
# Sort The Dictionary By Keys i.e. 0th Elements
c1 = sorted(colors.items(), key = lambda t: t[0])
print(c1)
# Sort The Dictionary By Values , i.e. 1st Elements
c2 = sorted(colors.items(), key = lambda t: t[1])
print(c2)
|
"""
Function Name : Sort Elements Of Dictionary Based On Key, Value.
Function Date : 13 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
"""
colors = {10: 'Red', 35: 'Green', 15: 'Blue', 25: 'White'}
c1 = sorted(colors.items(), key=lambda t: t[0])
print(c1)
c2 = sorted(colors.items(), key=lambda t: t[1])
print(c2)
|
# Mergesort is the best sorting algorithm for use with a linked-list
# Time Complexity O(nlogn)
# Merging will require log(n) doublings from subarrays of size (1) to a single array of size length(n),
# where each pass will require (n) iterations to compare and sort each element
# Space Complexity O(n) arrays
# O(1) linked-list
def mergesort(a):
if len(a) > 1: # divide array into subarrays of length one
m = len(a)//2 # floor division returns a truncated integer by rounding towards negative infinity
l = a[:m]
r = a[m:]
mergesort(l) # create auxillary arrays requiring O(n) memory in addition to the call stack overhead
mergesort(r)
i=0 # left half index
j=0 # right half index
k=0 # merge array index
while i < len(l) and j < len(r): # WHILE left and right halves both contain elements
if l[i] < r[j]:
a[k]=l[i]
i += 1
else:
a[k]=r[j]
j += 1
k += 1
while i < len(l): # WHILE only left half contains elements
a[k]=l[i]
i += 1
k += 1
while j < len(r): # WHILE only right half contains elements
a[k]=r[j]
j += 1
k += 1
x = [68,99,49,54,26,93,17,1,0,33,77]
print("Sorting {}" .format(x))
mergesort(x)
print("Result is {}" .format(x))
|
def mergesort(a):
if len(a) > 1:
m = len(a) // 2
l = a[:m]
r = a[m:]
mergesort(l)
mergesort(r)
i = 0
j = 0
k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
a[k] = l[i]
i += 1
else:
a[k] = r[j]
j += 1
k += 1
while i < len(l):
a[k] = l[i]
i += 1
k += 1
while j < len(r):
a[k] = r[j]
j += 1
k += 1
x = [68, 99, 49, 54, 26, 93, 17, 1, 0, 33, 77]
print('Sorting {}'.format(x))
mergesort(x)
print('Result is {}'.format(x))
|
"""VTK/FURY Tools
This module implements a set o tools to enhance VTK given new functionalities.
"""
class Uniform:
"""This creates a uniform shader variable
It's responsible to store the value of a given uniform
variable and call the related vtk_program
"""
def __init__(self, name, uniform_type, value):
"""
Parameters
----------
name: str
name of the uniform variable
uniform_type: str
Uniform variable type which will be used inside the shader.
Any of this are valid: 1fv, 1iv, 2f, 2fv, 2i, 3f, 3fv,
3uc, 4f, 4fv, 4uc, GroupUpdateTime, Matrix,
Matrix3x3, Matrix4x4, Matrix4x4v, f, i
value: float or ndarray
value: type(uniform_type)
should be a value which represent's the shader uniform
variable. For example, if uniform_type is 'f' then value
should be a float; if uniform_type is '3f' then value
should be a 1x3 array.
"""
self.name = name
self.value = value
self.uniform_type = uniform_type
self.valid_types = [
'1fv', '1iv', '2f', '2fv', '2i', '3f', '3fv',
'3uc', '4f', '4fv', '4uc', 'GroupUpdateTime', 'Matrix',
'Matrix3x3', 'Matrix4x4', 'Matrix4x4v', 'f', 'i']
if self.uniform_type not in self.valid_types:
raise ValueError(
f"""Uniform type {self.uniform_type} not valid.
Choose one of this values: {self.valid_types}""")
self.vtk_func_uniform = f'SetUniform{self.uniform_type}'
def execute_program(self, program):
""" Given a shader program, this method
will update the value with the associated uniform variable
in a draw call
Parameters
----------
program: vtkmodules.vtkRenderingOpenGL2.vtkShaderProgram
A shader program which will be used to update the uniform
"""
program.__getattribute__(self.vtk_func_uniform)(
self.name, self.value)
def __repr__(self):
return f'Uniform(name={self.name}, value={self.value})'
class Uniforms:
def __init__(self, uniforms):
"""Creates an object which store and execute an uniform variable.
Parameters
-----------
uniforms: list
List of Uniform objects.
Examples
--------
.. highlight:: python
.. code-block:: python
uniforms = [
Uniform(name='edgeWidth', uniform_type='f', value=edgeWidth)...
]
CustomUniforms = Uniforms(markerUniforms)
add_shader_callback(
sq_actor, CustomUniforms)
sq_actor.CustomUniforms = CustomUniforms
sq_actor.CustomUniforms.edgeWidth = 0.5
"""
self.uniforms = uniforms
for obj in self.uniforms:
# if isinstance(obj, Uniform) is False:
# raise ValueError(f"""{obj} it's not an Uniform object""")
setattr(self, obj.name, obj)
def __call__(self, _caller, _event, calldata=None,):
"""This method should be used as a callback for a vtk Observer
Execute the shader program with the given uniform variables.
"""
program = calldata
if program is None:
return None
for uniform in self.uniforms:
uniform.execute_program(program)
def __repr__(self):
return f'Uniforms({[obj.name for obj in self.uniforms]})'
|
"""VTK/FURY Tools
This module implements a set o tools to enhance VTK given new functionalities.
"""
class Uniform:
"""This creates a uniform shader variable
It's responsible to store the value of a given uniform
variable and call the related vtk_program
"""
def __init__(self, name, uniform_type, value):
"""
Parameters
----------
name: str
name of the uniform variable
uniform_type: str
Uniform variable type which will be used inside the shader.
Any of this are valid: 1fv, 1iv, 2f, 2fv, 2i, 3f, 3fv,
3uc, 4f, 4fv, 4uc, GroupUpdateTime, Matrix,
Matrix3x3, Matrix4x4, Matrix4x4v, f, i
value: float or ndarray
value: type(uniform_type)
should be a value which represent's the shader uniform
variable. For example, if uniform_type is 'f' then value
should be a float; if uniform_type is '3f' then value
should be a 1x3 array.
"""
self.name = name
self.value = value
self.uniform_type = uniform_type
self.valid_types = ['1fv', '1iv', '2f', '2fv', '2i', '3f', '3fv', '3uc', '4f', '4fv', '4uc', 'GroupUpdateTime', 'Matrix', 'Matrix3x3', 'Matrix4x4', 'Matrix4x4v', 'f', 'i']
if self.uniform_type not in self.valid_types:
raise value_error(f'Uniform type {self.uniform_type} not valid.\n Choose one of this values: {self.valid_types}')
self.vtk_func_uniform = f'SetUniform{self.uniform_type}'
def execute_program(self, program):
""" Given a shader program, this method
will update the value with the associated uniform variable
in a draw call
Parameters
----------
program: vtkmodules.vtkRenderingOpenGL2.vtkShaderProgram
A shader program which will be used to update the uniform
"""
program.__getattribute__(self.vtk_func_uniform)(self.name, self.value)
def __repr__(self):
return f'Uniform(name={self.name}, value={self.value})'
class Uniforms:
def __init__(self, uniforms):
"""Creates an object which store and execute an uniform variable.
Parameters
-----------
uniforms: list
List of Uniform objects.
Examples
--------
.. highlight:: python
.. code-block:: python
uniforms = [
Uniform(name='edgeWidth', uniform_type='f', value=edgeWidth)...
]
CustomUniforms = Uniforms(markerUniforms)
add_shader_callback(
sq_actor, CustomUniforms)
sq_actor.CustomUniforms = CustomUniforms
sq_actor.CustomUniforms.edgeWidth = 0.5
"""
self.uniforms = uniforms
for obj in self.uniforms:
setattr(self, obj.name, obj)
def __call__(self, _caller, _event, calldata=None):
"""This method should be used as a callback for a vtk Observer
Execute the shader program with the given uniform variables.
"""
program = calldata
if program is None:
return None
for uniform in self.uniforms:
uniform.execute_program(program)
def __repr__(self):
return f'Uniforms({[obj.name for obj in self.uniforms]})'
|
def solution(inp):
data = [row.split() for row in inp.splitlines()]
count = 0
for passphrase in data:
if len(passphrase) == len(set(passphrase)):
count = count + 1
return count
def main():
with open('input.txt', 'r') as f:
inp = f.read()
print('[*] Reading input from input.txt...')
print('[*] The solution is: ')
print(solution(inp))
if __name__=='__main__':
main()
|
def solution(inp):
data = [row.split() for row in inp.splitlines()]
count = 0
for passphrase in data:
if len(passphrase) == len(set(passphrase)):
count = count + 1
return count
def main():
with open('input.txt', 'r') as f:
inp = f.read()
print('[*] Reading input from input.txt...')
print('[*] The solution is: ')
print(solution(inp))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
__author__ = "venkat"
__author_email__ = "venkatram0273@gmail.com"
|
__author__ = 'venkat'
__author_email__ = 'venkatram0273@gmail.com'
|
# version code 80e56511a793+
# Please fill out this stencil and submit using the provided submission script.
# Be sure that the file voting_record_dump109.txt is in the matrix/ directory.
## 1: (Task 2.12.1) Create Voting Dict
def create_voting_dict(strlist):
"""
Input: a list of strings. Each string represents the voting record of a senator.
The string consists of
- the senator's last name,
- a letter indicating the senator's party,
- a couple of letters indicating the senator's home state, and
- a sequence of numbers (0's, 1's, and negative 1's) indicating the senator's
votes on bills
all separated by spaces.
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting record.
Example:
>>> vd = create_voting_dict(['Kennedy D MA -1 -1 1 1', 'Snowe R ME 1 1 1 1'])
>>> vd == {'Snowe': [1, 1, 1, 1], 'Kennedy': [-1, -1, 1, 1]}
True
You can use the .split() method to split each string in the
strlist into a list; the first element of the list will be the senator's
name, the second will be his/her party affiliation (R or D), the
third will be his/her home state, and the remaining elements of
the list will be that senator's voting record on a collection of bills.
You can use the built-in procedure int() to convert a string
representation of an integer (e.g. '1') to the actual integer
(e.g. 1).
The lists for each senator should preserve the order listed in voting data.
In case you're feeling clever, this can be done in one line.
"""
pass
## 2: (Task 2.12.2) Policy Compare
def policy_compare(sen_a, sen_b, voting_dict):
"""
Input: last names of sen_a and sen_b, and a voting dictionary mapping senator
names to lists representing their voting records.
Output: the dot-product (as a number) representing the degree of similarity
between two senators' voting policies
Example:
>>> voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}
>>> policy_compare('Fox-Epstein','Ravella', voting_dict)
-2
The code should correct compute dot-product even if the numbers are not all in {0,1,-1}.
>>> policy_compare('A', 'B', {'A':[100,10,1], 'B':[2,5,3]})
253
You should definitely try to write this in one line.
"""
pass
## 3: (Task 2.12.3) Most Similar
def most_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is most
like the input senator (excluding, of course, the input senator
him/herself). Resolve ties arbitrarily.
Example:
>>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
>>> most_similar('Klein', vd)
'Fox-Epstein'
>>> vd == {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
True
>>> vd = {'a': [1,1,1,0], 'b': [1,-1,0,0], 'c': [-1,0,0,0], 'd': [-1,0,0,1], 'e': [1, 0, 0,0]}
>>> most_similar('c', vd)
'd'
Note that you can (and are encouraged to) re-use your policy_compare procedure.
"""
return ""
## 4: (Task 2.12.4) Least Similar
def least_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is least like the input
senator.
Example:
>>> vd = {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]}
>>> least_similar('a', vd)
'c'
>>> vd == {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]}
True
>>> vd = {'a': [-1,0,0], 'b': [1,0,0], 'c': [-1,1,0], 'd': [-1,1,1]}
>>> least_similar('c', vd)
'b'
"""
pass
## 5: (Task 2.12.5) Chafee, Santorum
most_like_chafee = ''
least_like_santorum = ''
## 6: (Task 2.12.7) Most Average Democrat
def find_average_similarity(sen, sen_set, voting_dict):
"""
Input: the name of a senator, a set of senator names, and a voting dictionary.
Output: the average dot-product between sen and those in sen_set.
Example:
>>> vd = {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]}
>>> sens = {'Fox-Epstein','Ravella','Oyakawa','Loery'}
>>> find_average_similarity('Klein', sens, vd)
-0.5
>>> sens == {'Fox-Epstein','Ravella', 'Oyakawa', 'Loery'}
True
>>> vd == {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]}
True
"""
return ...
most_average_Democrat = ... # give the last name (or code that computes the last name)
## 7: (Task 2.12.8) Average Record
def find_average_record(sen_set, voting_dict):
"""
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
of the senators in the input set
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
>>> senators = {'Fox-Epstein','Ravella'}
>>> find_average_record(senators, voting_dict)
[-0.5, -0.5, 0.0]
>>> voting_dict == {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
True
>>> senators
{'Fox-Epstein','Ravella'}
>>> d = {'c': [-1,-1,0], 'b': [0,1,1], 'a': [0,1,1], 'e': [-1,-1,1], 'd': [-1,1,1]}
>>> find_average_record({'a','c','e'}, d)
[-0.6666666666666666, -0.3333333333333333, 0.6666666666666666]
>>> find_average_record({'a','c','e','b'}, d)
[-0.5, 0.0, 0.75]
>>> find_average_record({'a'}, d)
[0.0, 1.0, 1.0]
"""
return ...
average_Democrat_record = ... # give the vector as a list
## 8: (Task 2.12.9) Bitter Rivals
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein':[-1,0,1], 'Fox-Epstein':[-1,-1,-1], 'Ravella':[0,0,1], 'Oyakawa':[1,1,1], 'Loery':[1,1,0]}
>>> br = bitter_rivals(voting_dict)
>>> br == ('Fox-Epstein', 'Oyakawa') or br == ('Oyakawa', 'Fox-Epstein')
True
"""
return (..., ...)
|
def create_voting_dict(strlist):
"""
Input: a list of strings. Each string represents the voting record of a senator.
The string consists of
- the senator's last name,
- a letter indicating the senator's party,
- a couple of letters indicating the senator's home state, and
- a sequence of numbers (0's, 1's, and negative 1's) indicating the senator's
votes on bills
all separated by spaces.
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting record.
Example:
>>> vd = create_voting_dict(['Kennedy D MA -1 -1 1 1', 'Snowe R ME 1 1 1 1'])
>>> vd == {'Snowe': [1, 1, 1, 1], 'Kennedy': [-1, -1, 1, 1]}
True
You can use the .split() method to split each string in the
strlist into a list; the first element of the list will be the senator's
name, the second will be his/her party affiliation (R or D), the
third will be his/her home state, and the remaining elements of
the list will be that senator's voting record on a collection of bills.
You can use the built-in procedure int() to convert a string
representation of an integer (e.g. '1') to the actual integer
(e.g. 1).
The lists for each senator should preserve the order listed in voting data.
In case you're feeling clever, this can be done in one line.
"""
pass
def policy_compare(sen_a, sen_b, voting_dict):
"""
Input: last names of sen_a and sen_b, and a voting dictionary mapping senator
names to lists representing their voting records.
Output: the dot-product (as a number) representing the degree of similarity
between two senators' voting policies
Example:
>>> voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}
>>> policy_compare('Fox-Epstein','Ravella', voting_dict)
-2
The code should correct compute dot-product even if the numbers are not all in {0,1,-1}.
>>> policy_compare('A', 'B', {'A':[100,10,1], 'B':[2,5,3]})
253
You should definitely try to write this in one line.
"""
pass
def most_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is most
like the input senator (excluding, of course, the input senator
him/herself). Resolve ties arbitrarily.
Example:
>>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
>>> most_similar('Klein', vd)
'Fox-Epstein'
>>> vd == {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
True
>>> vd = {'a': [1,1,1,0], 'b': [1,-1,0,0], 'c': [-1,0,0,0], 'd': [-1,0,0,1], 'e': [1, 0, 0,0]}
>>> most_similar('c', vd)
'd'
Note that you can (and are encouraged to) re-use your policy_compare procedure.
"""
return ''
def least_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is least like the input
senator.
Example:
>>> vd = {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]}
>>> least_similar('a', vd)
'c'
>>> vd == {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]}
True
>>> vd = {'a': [-1,0,0], 'b': [1,0,0], 'c': [-1,1,0], 'd': [-1,1,1]}
>>> least_similar('c', vd)
'b'
"""
pass
most_like_chafee = ''
least_like_santorum = ''
def find_average_similarity(sen, sen_set, voting_dict):
"""
Input: the name of a senator, a set of senator names, and a voting dictionary.
Output: the average dot-product between sen and those in sen_set.
Example:
>>> vd = {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]}
>>> sens = {'Fox-Epstein','Ravella','Oyakawa','Loery'}
>>> find_average_similarity('Klein', sens, vd)
-0.5
>>> sens == {'Fox-Epstein','Ravella', 'Oyakawa', 'Loery'}
True
>>> vd == {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]}
True
"""
return ...
most_average__democrat = ...
def find_average_record(sen_set, voting_dict):
"""
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
of the senators in the input set
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
>>> senators = {'Fox-Epstein','Ravella'}
>>> find_average_record(senators, voting_dict)
[-0.5, -0.5, 0.0]
>>> voting_dict == {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
True
>>> senators
{'Fox-Epstein','Ravella'}
>>> d = {'c': [-1,-1,0], 'b': [0,1,1], 'a': [0,1,1], 'e': [-1,-1,1], 'd': [-1,1,1]}
>>> find_average_record({'a','c','e'}, d)
[-0.6666666666666666, -0.3333333333333333, 0.6666666666666666]
>>> find_average_record({'a','c','e','b'}, d)
[-0.5, 0.0, 0.75]
>>> find_average_record({'a'}, d)
[0.0, 1.0, 1.0]
"""
return ...
average__democrat_record = ...
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein':[-1,0,1], 'Fox-Epstein':[-1,-1,-1], 'Ravella':[0,0,1], 'Oyakawa':[1,1,1], 'Loery':[1,1,0]}
>>> br = bitter_rivals(voting_dict)
>>> br == ('Fox-Epstein', 'Oyakawa') or br == ('Oyakawa', 'Fox-Epstein')
True
"""
return (..., ...)
|
s1=set([1,3,7,94])
s2=set([2,3])
print(s1)
print(s2)
print(s1.intersection(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.symmetric_difference(s2))
print(s1.union(s2))
s1.difference_update(s2) #S1 becomes equal to the difference
print(s1)
s1=set([1,3])
s1.discard(1)
s1.remove(3)
print(s1)
s1.add(5)
print(s1)
t=([6,7])
s2.update(t)
print(s2)
x=s2.pop()
print(x)
|
s1 = set([1, 3, 7, 94])
s2 = set([2, 3])
print(s1)
print(s2)
print(s1.intersection(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.symmetric_difference(s2))
print(s1.union(s2))
s1.difference_update(s2)
print(s1)
s1 = set([1, 3])
s1.discard(1)
s1.remove(3)
print(s1)
s1.add(5)
print(s1)
t = [6, 7]
s2.update(t)
print(s2)
x = s2.pop()
print(x)
|
def convert_to_alt_caps(message):
lower = message.lower()
upper = message.upper()
data = []
space_offset = 0
for i in range(len(lower)):
if not lower[i].isalpha():
space_offset += 1
if (i + space_offset) % 2 == 0:
data.append(lower[i])
else:
data.append(upper[i])
return ''.join(data)
def main():
input_str = "Pikachu"
print(input_str)
print(convert_to_alt_caps(input_str))
input_str = "section is AWESOME"
print(input_str)
print(convert_to_alt_caps(input_str))
if __name__ == '__main__':
main()
|
def convert_to_alt_caps(message):
lower = message.lower()
upper = message.upper()
data = []
space_offset = 0
for i in range(len(lower)):
if not lower[i].isalpha():
space_offset += 1
if (i + space_offset) % 2 == 0:
data.append(lower[i])
else:
data.append(upper[i])
return ''.join(data)
def main():
input_str = 'Pikachu'
print(input_str)
print(convert_to_alt_caps(input_str))
input_str = 'section is AWESOME'
print(input_str)
print(convert_to_alt_caps(input_str))
if __name__ == '__main__':
main()
|
TIME_FORMAT = ('day', 'hour')
OPERATORS = {
'==': lambda x, y: x == y,
'<=': lambda x, y: x <= y,
'>=': lambda x, y: x >= y,
'>': lambda x, y: x > y,
'<': lambda x, y: x < y,
}
class TimeDelta(object):
def __init__(self, amount, fmt, operator):
if int(amount) < 0:
raise ValueError('amount must be over zero')
if fmt not in TIME_FORMAT:
raise ValueError(
'Time format must be one of {}'
''.format(', '.join(TIME_FORMAT))
)
if operator not in OPERATORS.keys():
raise ValueError(
'Comparision type must be one of {}'
''.format(', '.join(OPERATORS.keys()))
)
if int(amount) > 1:
fmt += 's'
self.amount = amount
self.format = fmt
self.operator = operator
def parse(self, results):
d = []
for content in results:
# O(N) - hacky as fuck! :(
val, fmt = content['age'].split(' ')
if fmt == self.format and \
OPERATORS[self.operator](int(val), int(self.amount)):
d.append(content)
return d
|
time_format = ('day', 'hour')
operators = {'==': lambda x, y: x == y, '<=': lambda x, y: x <= y, '>=': lambda x, y: x >= y, '>': lambda x, y: x > y, '<': lambda x, y: x < y}
class Timedelta(object):
def __init__(self, amount, fmt, operator):
if int(amount) < 0:
raise value_error('amount must be over zero')
if fmt not in TIME_FORMAT:
raise value_error('Time format must be one of {}'.format(', '.join(TIME_FORMAT)))
if operator not in OPERATORS.keys():
raise value_error('Comparision type must be one of {}'.format(', '.join(OPERATORS.keys())))
if int(amount) > 1:
fmt += 's'
self.amount = amount
self.format = fmt
self.operator = operator
def parse(self, results):
d = []
for content in results:
(val, fmt) = content['age'].split(' ')
if fmt == self.format and OPERATORS[self.operator](int(val), int(self.amount)):
d.append(content)
return d
|
# -*- coding: utf-8 -*-
"""
"""
#make noarg a VERY unique value. Was using empty tuple, but python caches it, this should be quite unique
def unique_generator():
def UNIQUE_CLOSURE():
return UNIQUE_CLOSURE
return ("<UNIQUE VALUE>", UNIQUE_CLOSURE,)
NOARG = unique_generator()
|
"""
"""
def unique_generator():
def unique_closure():
return UNIQUE_CLOSURE
return ('<UNIQUE VALUE>', UNIQUE_CLOSURE)
noarg = unique_generator()
|
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
banset = set(banned)
for c in "!?',;.":
paragraph = paragraph.replace(c, ' ')
cnt = Counter(word for word in paragraph.lower().split())
ans, best = '', 0
for word in cnt:
if cnt[word] > best and word not in banset:
ans, best = word, cnt[word]
return ans
|
class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
banset = set(banned)
for c in "!?',;.":
paragraph = paragraph.replace(c, ' ')
cnt = counter((word for word in paragraph.lower().split()))
(ans, best) = ('', 0)
for word in cnt:
if cnt[word] > best and word not in banset:
(ans, best) = (word, cnt[word])
return ans
|
#program to input a number, if it is not a number generate an error message.
while True:
try:
a = int(input("Input a number: "))
break
except ValueError:
print("\nThis is not a number. Try again...")
print()
break
|
while True:
try:
a = int(input('Input a number: '))
break
except ValueError:
print('\nThis is not a number. Try again...')
print()
break
|
# Introduction to deep learning with Python
# A. Forward propogation
# Process of working from the input layer to the hidden layer to the final output layer
# Values contained within the input layer are multiplied by the weights that are connected to the interactions for the hidden layer.
# Details contained within this hidden layer nodes are then multiplied by the weights that connect to the output layer to create the prediction
# First two chapters are aiming to predict the number of bank transactions that a customer will make
# Calculate node 0 value: node_0_value
node_0_value = (input_data * weights['node_0']).sum()
# Calculate node 1 value: node_1_value
node_1_value = (input_data * weights['node_1']).sum()
# Put node values into array: hidden_layer_outputs
hidden_layer_outputs = np.array([node_0_value, node_1_value])
# Calculate output: output
output = (hidden_layer_outputs * weights['output']).sum()
# Print output
print(output)
# B. Activation functions
# Used to introduce non-linear interactions that occur. Aims to move away from simple linear interactions
# These functions are applied at each node to convert the inputs into an output value for that node.
# 1. The Rectified Linear Activation Function. Aims to predict only positive values by taking the maximum of input and zero. Don't want to
# predict negative transaction values
def relu(input):
'''Define your relu activation function here'''
# Calculate the value for the output of the relu function: output
output = max(input, 0)
# Return the value just calculated
return(output)
# Calculate node 0 value: node_0_output
node_0_input = (input_data * weights['node_0']).sum()
node_0_output = relu(node_0_input)
# Calculate node 1 value: node_1_output
node_1_input = (input_data * weights['node_1']).sum()
node_1_output = relu(node_1_input)
# Put node values into array: hidden_layer_outputs
hidden_layer_outputs = np.array([node_0_output, node_1_output])
# Calculate model output (do not apply relu)
model_output = (hidden_layer_outputs * weights['output']).sum()
# Print model output
print(model_output)
# 2. Applying the network to many observations
# Define predict_with_network()
def predict_with_network(input_data_row, weights):
# Calculate node 0 value
node_0_input = (input_data_row * weights['node_0']).sum()
node_0_output = relu(node_0_input)
# Calculate node 1 value
node_1_input = (input_data_row * weights['node_1']).sum()
node_1_output = relu(node_1_input)
# Put node values into array: hidden_layer_outputs
hidden_layer_outputs = np.array([node_0_output, node_1_output])
# Calculate model output
input_to_final_layer = (hidden_layer_outputs * weights['output']).sum()
model_output = relu(input_to_final_layer)
# Return model output
return(model_output)
# Create empty list to store prediction results
results = []
for input_data_row in input_data:
# Append prediction to results
results.append(predict_with_network(input_data_row, weights))
# Print results
print(results)
# C. Deeper networks
# 1. Multi-layer neural network. The hidden layers build on top of each other. In this example there are four layers; input, hidden_1, hidden_2 and output.
# The model works to calulate predictions by working through each layer until the prediction is ready for the output layer
def predict_with_network(input_data):
# Calculate node 0 in the first hidden layer
node_0_0_input = (input_data * weights['node_0_0']).sum()
node_0_0_output = relu(node_0_0_input)
# Calculate node 1 in the first hidden layer
node_0_1_input = (input_data * weights['node_0_1']).sum()
node_0_1_output = relu(node_0_1_input)
# Put node values into array: hidden_0_outputs
hidden_0_outputs = np.array([node_0_0_output, node_0_1_output])
# Calculate node 0 in the second hidden layer
node_1_0_input = (hidden_0_outputs * weights['node_1_0']).sum()
node_1_0_output = relu(node_1_0_input)
# Calculate node 1 in the second hidden layer
node_1_1_input = (hidden_0_outputs * weights['node_1_1']).sum()
node_1_1_output = relu(node_1_1_input)
# Put node values into array: hidden_1_outputs
hidden_1_outputs = np.array([node_1_0_output, node_1_1_output])
# Calculate model output: model_output
model_output = (hidden_1_outputs * weights['output']).sum()
# Return model_output
return(model_output)
output = predict_with_network(input_data)
print(output)
|
node_0_value = (input_data * weights['node_0']).sum()
node_1_value = (input_data * weights['node_1']).sum()
hidden_layer_outputs = np.array([node_0_value, node_1_value])
output = (hidden_layer_outputs * weights['output']).sum()
print(output)
def relu(input):
"""Define your relu activation function here"""
output = max(input, 0)
return output
node_0_input = (input_data * weights['node_0']).sum()
node_0_output = relu(node_0_input)
node_1_input = (input_data * weights['node_1']).sum()
node_1_output = relu(node_1_input)
hidden_layer_outputs = np.array([node_0_output, node_1_output])
model_output = (hidden_layer_outputs * weights['output']).sum()
print(model_output)
def predict_with_network(input_data_row, weights):
node_0_input = (input_data_row * weights['node_0']).sum()
node_0_output = relu(node_0_input)
node_1_input = (input_data_row * weights['node_1']).sum()
node_1_output = relu(node_1_input)
hidden_layer_outputs = np.array([node_0_output, node_1_output])
input_to_final_layer = (hidden_layer_outputs * weights['output']).sum()
model_output = relu(input_to_final_layer)
return model_output
results = []
for input_data_row in input_data:
results.append(predict_with_network(input_data_row, weights))
print(results)
def predict_with_network(input_data):
node_0_0_input = (input_data * weights['node_0_0']).sum()
node_0_0_output = relu(node_0_0_input)
node_0_1_input = (input_data * weights['node_0_1']).sum()
node_0_1_output = relu(node_0_1_input)
hidden_0_outputs = np.array([node_0_0_output, node_0_1_output])
node_1_0_input = (hidden_0_outputs * weights['node_1_0']).sum()
node_1_0_output = relu(node_1_0_input)
node_1_1_input = (hidden_0_outputs * weights['node_1_1']).sum()
node_1_1_output = relu(node_1_1_input)
hidden_1_outputs = np.array([node_1_0_output, node_1_1_output])
model_output = (hidden_1_outputs * weights['output']).sum()
return model_output
output = predict_with_network(input_data)
print(output)
|
class Destiny2APIError(Exception):
pass
class Destiny2InvalidParameters(Destiny2APIError):
pass
class Destiny2APICooldown(Destiny2APIError):
pass
class Destiny2RefreshTokenError(Destiny2APIError):
pass
class Destiny2MissingAPITokens(Destiny2APIError):
pass
class Destiny2MissingManifest(Destiny2APIError):
pass
|
class Destiny2Apierror(Exception):
pass
class Destiny2Invalidparameters(Destiny2APIError):
pass
class Destiny2Apicooldown(Destiny2APIError):
pass
class Destiny2Refreshtokenerror(Destiny2APIError):
pass
class Destiny2Missingapitokens(Destiny2APIError):
pass
class Destiny2Missingmanifest(Destiny2APIError):
pass
|
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
dic = {}
for i, num in enumerate(numbers):
if target - num in dic:
return [dic[target - num] + 1, i + 1]
dic[num] = i
|
class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
dic = {}
for (i, num) in enumerate(numbers):
if target - num in dic:
return [dic[target - num] + 1, i + 1]
dic[num] = i
|
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays;"
user_table_drop = "DROP TABLE IF EXISTS users;"
song_table_drop = "DROP TABLE IF EXISTS songs;"
artist_table_drop = "DROP TABLE IF EXISTS artists;"
time_table_drop = "DROP TABLE IF EXISTS time;"
# CREATE TABLES
songplay_table_create = ("""CREATE TABLE IF NOT EXISTS songplays (
songplay_id SERIAL PRIMARY KEY,
start_time TIMESTAMP NOT NULL,
user_id INT NOT NULL,
level VARCHAR(4),
song_id VARCHAR,
artist_id VARCHAR,
session_id INT NOT NULL,
location TEXT,
user_agent TEXT
)
""")
user_table_create = ("""CREATE TABLE IF NOT EXISTS users (
user_id INT UNIQUE NOT NULL PRIMARY KEY,
first_name TEXT,
last_name TEXT,
gender VARCHAR(1),
level VARCHAR(4)
)
""")
song_table_create = ("""CREATE TABLE IF NOT EXISTS songs (
song_id VARCHAR UNIQUE NOT NULL PRIMARY KEY,
title TEXT,
artist_id VARCHAR,
year INT,
duration NUMERIC
)
""")
artist_table_create = ("""CREATE TABLE IF NOT EXISTS artists (
artist_id VARCHAR UNIQUE NOT NULL PRIMARY KEY,
name TEXT,
location TEXT,
latitude NUMERIC,
longitude NUMERIC
)
""")
time_table_create = ("""CREATE TABLE IF NOT EXISTS time (
start_time TIME UNIQUE NOT NULL,
hour INT,
day INT,
week INT,
month VARCHAR(10),
year INT,
weekday VARCHAR(10)
)
""")
# INSERT RECORDS
songplay_table_insert = ("""INSERT INTO songplays (
start_time,
user_id,
level,
song_id,
artist_id,
session_id,
location,
user_agent
)
VALUES (to_timestamp(%s), %s, %s, %s, %s, %s, %s, %s)
""")
user_table_insert = ("""INSERT INTO users (
user_id,
first_name,
last_name,
gender,
level
)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (user_id)
DO UPDATE SET level = EXCLUDED.level
""")
song_table_insert = ("""INSERT INTO songs (
song_id,
title,
artist_id,
year,
duration
)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (song_id)
DO NOTHING
""")
artist_table_insert = ("""INSERT INTO artists (
artist_id,
name,
location,
latitude,
longitude
)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (artist_id)
DO NOTHING
""")
time_table_insert = ("""INSERT INTO time (
start_time,
hour,
day,
week,
month,
year,
weekday
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (start_time)
DO NOTHING
""")
# FIND SONGS
song_select = ("""SELECT songs.song_id, songs.artist_id
FROM songs JOIN artists ON songs.artist_id = artists.artist_id
WHERE songs.title = (%s) AND artists.name = (%s) AND songs.duration = (%s);
""")
# QUERY LISTS
create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]
drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
|
songplay_table_drop = 'DROP TABLE IF EXISTS songplays;'
user_table_drop = 'DROP TABLE IF EXISTS users;'
song_table_drop = 'DROP TABLE IF EXISTS songs;'
artist_table_drop = 'DROP TABLE IF EXISTS artists;'
time_table_drop = 'DROP TABLE IF EXISTS time;'
songplay_table_create = 'CREATE TABLE IF NOT EXISTS songplays (\n songplay_id SERIAL PRIMARY KEY, \n start_time TIMESTAMP NOT NULL, \n user_id INT NOT NULL, \n level VARCHAR(4), \n song_id VARCHAR, \n artist_id VARCHAR, \n session_id INT NOT NULL, \n location TEXT, \n user_agent TEXT\n )\n '
user_table_create = 'CREATE TABLE IF NOT EXISTS users (\n user_id INT UNIQUE NOT NULL PRIMARY KEY, \n first_name TEXT, \n last_name TEXT, \n gender VARCHAR(1), \n level VARCHAR(4)\n )\n '
song_table_create = 'CREATE TABLE IF NOT EXISTS songs (\n song_id VARCHAR UNIQUE NOT NULL PRIMARY KEY, \n title TEXT, \n artist_id VARCHAR, \n year INT, \n duration NUMERIC\n )\n '
artist_table_create = 'CREATE TABLE IF NOT EXISTS artists (\n artist_id VARCHAR UNIQUE NOT NULL PRIMARY KEY, \n name TEXT, \n location TEXT, \n latitude NUMERIC, \n longitude NUMERIC\n )\n '
time_table_create = 'CREATE TABLE IF NOT EXISTS time (\n start_time TIME UNIQUE NOT NULL, \n hour INT, \n day INT, \n week INT, \n month VARCHAR(10), \n year INT, \n weekday VARCHAR(10)\n )\n '
songplay_table_insert = 'INSERT INTO songplays (\n start_time, \n user_id, \n level, \n song_id, \n artist_id, \n session_id, \n location, \n user_agent\n ) \n VALUES (to_timestamp(%s), %s, %s, %s, %s, %s, %s, %s)\n '
user_table_insert = 'INSERT INTO users (\n user_id, \n first_name, \n last_name, \n gender, \n level\n ) \n VALUES (%s, %s, %s, %s, %s)\n ON CONFLICT (user_id) \n DO UPDATE SET level = EXCLUDED.level\n '
song_table_insert = 'INSERT INTO songs (\n song_id, \n title, \n artist_id, \n year, \n duration\n ) \n VALUES (%s, %s, %s, %s, %s)\n ON CONFLICT (song_id) \n DO NOTHING\n '
artist_table_insert = 'INSERT INTO artists (\n artist_id, \n name, \n location, \n latitude, \n longitude\n ) \n VALUES (%s, %s, %s, %s, %s)\n ON CONFLICT (artist_id) \n DO NOTHING\n '
time_table_insert = 'INSERT INTO time (\n start_time, \n hour, \n day, \n week, \n month, \n year, \n weekday\n ) \n VALUES (%s, %s, %s, %s, %s, %s, %s) \n ON CONFLICT (start_time) \n DO NOTHING\n '
song_select = 'SELECT songs.song_id, songs.artist_id \n FROM songs JOIN artists ON songs.artist_id = artists.artist_id \n WHERE songs.title = (%s) AND artists.name = (%s) AND songs.duration = (%s);\n '
create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]
drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
|
# OpenWeatherMap API Key
weather_api_key = "601b4c14f4ddb46a0080bbfb5ca51d3e"
# Google API Key
g_key = "AIzaSyDNUFB01N6sBwZfPznGBiHayHJrON12pYw"
|
weather_api_key = '601b4c14f4ddb46a0080bbfb5ca51d3e'
g_key = 'AIzaSyDNUFB01N6sBwZfPznGBiHayHJrON12pYw'
|
class BaseModel:
def __init__(self):
self.ops = {}
|
class Basemodel:
def __init__(self):
self.ops = {}
|
# user.py
__all__ = ['User']
class User:
pass
def user_helper_1():
pass
|
__all__ = ['User']
class User:
pass
def user_helper_1():
pass
|
description = 'IPC Motor bus device configuration'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
tango_base = instrument_values['tango_base']
# data from instrument.inf
# used for:
# - shutter_gamma (addr 0x31)
# - nok2 (addr 0x32, 0x33)
# - nok3 (addr 0x34, 0x35)
# - nok4 reactor side (addr 0x36)
# - zb0 (addr 0x37)
# - zb1 (addr 0x38)
#
devices = dict(
nokbus1 = device('nicos.devices.vendor.ipc.IPCModBusTango',
tangodevice = tango_base + 'test/ipcsms_a/bio',
lowlevel = True,
),
)
|
description = 'IPC Motor bus device configuration'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
tango_base = instrument_values['tango_base']
devices = dict(nokbus1=device('nicos.devices.vendor.ipc.IPCModBusTango', tangodevice=tango_base + 'test/ipcsms_a/bio', lowlevel=True))
|
def extractMichilunWordpressCom(item):
'''
Parser for 'michilun.wordpress.com'
'''
bad = [
'Recommendations and Reviews',
]
if any([tmp in item['tags'] for tmp in bad]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Side Projects - Scheme of the Official Descendant', 'Scheme of the Official Descendant', 'translated'),
('Song in the Peach Blossoms', 'Song in the Peach Blossoms', 'translated'),
('Onrain (Online - The Novel)', 'Onrain (Online - The Novel)', 'translated'),
('At the End of the Wish', 'At the End of the Wish', 'translated'),
('Bringing Calamity to the Nation', 'Bringing Calamity to the Nation', 'translated'),
('Side Projects - The Flame\'s Daughter', 'The Flame\'s Daughter', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
def extract_michilun_wordpress_com(item):
"""
Parser for 'michilun.wordpress.com'
"""
bad = ['Recommendations and Reviews']
if any([tmp in item['tags'] for tmp in bad]):
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('Side Projects - Scheme of the Official Descendant', 'Scheme of the Official Descendant', 'translated'), ('Song in the Peach Blossoms', 'Song in the Peach Blossoms', 'translated'), ('Onrain (Online - The Novel)', 'Onrain (Online - The Novel)', 'translated'), ('At the End of the Wish', 'At the End of the Wish', 'translated'), ('Bringing Calamity to the Nation', 'Bringing Calamity to the Nation', 'translated'), ("Side Projects - The Flame's Daughter", "The Flame's Daughter", 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowestCommonAncestor(self, root, A, B):
if root is None or root is A or root is B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
if left:
return left
return right
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowest_common_ancestor(self, root, A, B):
if root is None or root is A or root is B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
if left:
return left
return right
|
def main():
with open('inputs/01.in') as f:
data = [int(line) for line in f]
print(sum(data))
result = 0
seen = {0}
while True:
for item in data:
result += item
if result in seen:
print(result)
return
seen.add(result)
if __name__ == '__main__':
main()
|
def main():
with open('inputs/01.in') as f:
data = [int(line) for line in f]
print(sum(data))
result = 0
seen = {0}
while True:
for item in data:
result += item
if result in seen:
print(result)
return
seen.add(result)
if __name__ == '__main__':
main()
|
strikeout = 'K'
className = "This is CS50."
age = 30
anotherAge = 63
pi = 3.14
morePi = 3.1415962
fun = True
print("strikeout: {}".format(strikeout))
print("className: {}".format(className))
print("age: {}".format(age))
print("anotherAge: {}".format(anotherAge))
print("pi: {}".format(pi))
print("morePi: {}".format(morePi))
print("fun: {}".format(fun))
|
strikeout = 'K'
class_name = 'This is CS50.'
age = 30
another_age = 63
pi = 3.14
more_pi = 3.1415962
fun = True
print('strikeout: {}'.format(strikeout))
print('className: {}'.format(className))
print('age: {}'.format(age))
print('anotherAge: {}'.format(anotherAge))
print('pi: {}'.format(pi))
print('morePi: {}'.format(morePi))
print('fun: {}'.format(fun))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.