content
stringlengths 7
1.05M
|
---|
class a:
def __init__(self,da):
self.da = da
return
def go(self):
dd()
return None
def dd():
print('ok')
return None
aa = a(1)
aa.go() |
"""
These methods can be called inside WebCAT to determine which tests are loaded
for a given section/exam pair. This allows a common WebCAT submission site to
support different project tests
"""
def section():
# Instructor section (instructor to change before distribution)
#return 8527
#return 8528
return 8529
def exam():
# A or B exam (instructor to change to match specific project distribution
return "A"
#return "B"
|
text = '''
Victor Hugo's ({}) tale of injustice, heroism and love follows the fortunes of Jean Valjean, an escaped convict determined to put his criminal past behind him. But his attempts to become a respected member of the community are constantly put under threat: by his own conscience, when, owing to a case of mistaken identity, another man is arrested in his place; and by the relentless investigations of the dogged Inspector Javert. It is not simply for himself that Valjean must stay free, however, for he has sworn to protect the baby daughter of Fantine, driven to prostitution by poverty.
Norman Denny's ({}) lively English translation is accompanied by an introduction discussing Hugo's political and artistic aims in writing Les Miserables.
Victor Hugo (1802-85) wrote volumes of criticism, dramas, satirical verse and political journalism but is best remembered for his novels, especially Notre-Dame de Paris (also known as The Hunchback of Notre-Dame) and Les Miserables, which was adapted into one of the most successful musicals of all time.
'All human life is here'
Cameron Mackintosh, producer of the musical Les Miserables
'One of the half-dozen greatest novels of the world'
Upton Sinclair
'A great writer - inventive, witty, sly, innovatory'
A. S. Byatt, author of Possession
'''
name = 'Victor'
word1 = 'writer'
word2 = 'witty'
numbers = "0123456789"
small_letters = 'abcdefghijklmnopqrstuvwxyz'
big_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
name_index = text.find(name)
name_plus3 = text[name_index: name_index+len(name)+3]
word1_index = text.find(word1, 0, 100)
word2_index = text.find(word2, int(len(text)/2), len(text))
count_characters = text.count('of')
is_text_starts_with_name = text.startswith(name)
is_text_ends_with_name = text.endswith(name)
text = text.format('1822-95', '1807-63')
words = text.split(' ')
text1 = ''.join(words)
text2 = ','.join(words)
text3 = '_'.join(words)
text4 = ' '.join(words)
text5 = text.replace('of', '@🐔')
text6 = text.capitalize()
text7 = text.replace('a', '')
text8 = text.strip()
upper_name = name.upper()
lower_name = name.lower()
is_name_upper = name.isupper()
is_name_lower = name.islower()
is_big_letters_upper = big_letters.isupper()
is_small_letters_lower = small_letters.islower()
stringed_integer = '90'.isnumeric()
stringed_float = '90.5'.isnumeric()
converted_int = int('90')
converted_float = float('90.5')
converted_string = str(183)
is_digit = converted_string[1].isdigit()
edges = small_letters[0] + big_letters[-1]
body = numbers[1:-1]
evens = numbers[::2]
odds = numbers[1::2]
print('name', name)
print('word1', word1)
print('word2', word2)
print('numbers', numbers)
print('small_letters', small_letters)
print('big_letters', big_letters)
print('name_index', name_index)
print('name_plus3', name_plus3)
print('word1_index', word1_index)
print('word2_index', word2_index)
print('count_characters -> \'of\' in the text', count_characters)
print('is_text_starts_with_name', is_text_starts_with_name)
print('is_text_ends_with_name', is_text_ends_with_name)
print('\n\n\n\n\n', 'text', text, '\n\n\n\n\n')
print('\n\n\n\n\n', 'words', words, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text1', text1, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text2', text2, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text3', text3, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text4', text4, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text5', text5, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text6', text6, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text7', text7, '\n\n\n\n\n')
print('\n\n\n\n\n', 'text8', text8, '\n\n\n\n\n')
print('upper_name', upper_name)
print('lower_name', lower_name)
print('is_name_upper', is_name_upper)
print('is_name_lower', is_name_lower)
print('is_big_letters_upper', is_big_letters_upper)
print('is_small_letters_lower', is_small_letters_lower)
print('stringed_integer', stringed_integer)
print('stringed_float', stringed_float)
print('converted_int', converted_int)
print('converted_float', converted_float)
print('converted_string', converted_string)
print('is_digit', is_digit)
print('edges', edges)
print('body', body)
print('evens', evens)
print('odds', odds)
|
"""
PermCheck
Check whether array A is a permutation.
https://codility.com/demo/results/demoANZ7M2-GFU/
Task description
A non-empty zero-indexed array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
is a permutation, but array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
"""
def solution(A):
# write your code in Python 2.7
s = set(A)
N_set = len(s) #O(n)
N = len(A)
if N != N_set: return 0
sum_N = N*(N+1)/2 #O(1)
sum_A = sum(A) #O(n)
return 1 if sum_N == sum_A else 0 |
'''
Created on Dec 27, 2019
@author: duane
'''
DOLLAR = ord('$')
LBRACE = ord('{')
RBRACE = ord('}')
LPAREN = ord('(')
RPAREN = ord(')')
class IStrFindResult(object):
OK = 0
NOTFOUND = 1
SYNTAX = 2
def __init__(self):
self.result = IStrFindResult.SYNTAX
self.lhs = 0
self.rhs = 0
self.name = None
class IStr(list):
'''
This closely models a basic ASCII string
Note: Unicode strings are expressly not supported here.
The problem this addresses occurs during macro processing.
Sometimes macros are defined externally
Other times, macros are fully defined with a package.
Often macros need to be resolved either partially or fully
When a macro is only external - they get in the way of resolving other macros
To work around that, we convert the string into an array of integers
Then for every macro byte that is 'external' we add 0x100
This makes the byte 'non-matchable'
Later, when we convert the resolved string into we strip the 0x100.
'''
IGNORE = 0x100
def __init__(self, s):
'''
Constructor
'''
# convert to integers
list.__init__(self, map(ord, s))
def __str__(self):
# return as string, stripping flags
return ''.join(map(lambda v: chr(v & 0xff), self))
def sslice(self, lhs, rhs):
# return as string, stripping flags
return ''.join(map(lambda v: chr(v & 0xff), self[lhs:rhs]))
def iarray(self):
return self[:]
def mark(self, lhs, rhs, flagvalue=IGNORE):
'''
Apply flags to locations between left and right hand sides, ie: [lhs:rhs]
'''
for idx in range(lhs, rhs):
self[idx] |= flagvalue
def locate(self, needle, lhs, rhs):
'''Find this needle(char) in the hay stack(list).'''
try:
return self.index(needle, lhs, rhs)
except:
# not found
return -1
def replace(self, lhs, rhs, newcontent):
'''replace the data between [lhs:rhs] with newcontent'''
self[lhs: rhs] = map(ord, newcontent)
def next_macro(self, lhs, rhs):
'''
Find a macro within the string, return (lhs,rhs) if found
If not found, return (-1,-1)
If syntax error, return (-2,-2)
'''
result = IStrFindResult()
result.lhs = lhs
result.rhs = rhs
# if it is not long enough...
if (rhs - lhs) < 4:
result.code = result.NOTFOUND
return result
# We search for the CLOSING
# Consider nested: ${ ${foo}_${bar} }
# The first thing we must do is "foo"
# So find the close
tmp = self.locate(RBRACE, result.lhs,result.rhs)
if tmp >= 0:
_open_symbol = LBRACE
else:
tmp = self.locate(RPAREN,result.lhs,result.rhs)
_open_symbol = RPAREN
if tmp < 0:
# not found
result.code = result.NOTFOUND
return result
# We want to end at RHS where the closing symbol is
result.rhs = tmp
while result.lhs < result.rhs:
# find DOLLAR
dollar_loc = self.locate(DOLLAR, result.lhs, result.rhs)
if dollar_loc < 0:
# above, we know we have a CLOSE
# We could call this a SYNTAX error
# but ... we won't we'll leave this as NOT FOUND
result.code = result.NOTFOUND
return result
# we have: DOLLAR + CLOSE
# Can we find DOLLAR + OPEN?
ch = self[dollar_loc+1]
if ch != _open_symbol:
# Nope... try again after dollar
result.lhs = dollar_loc+1
continue
result.lhs = dollar_loc
# Do we have a nested macro, ie: ${${x}}
tmp = self.locate(DOLLAR, dollar_loc + 1, result.rhs)
if tmp >= 0:
# we do have a nested macro
result.lhs = tmp
continue
# nope, we are good
# Everything between LHS and RHS should be a macro
result.code = result.OK
result.name = self.sslice(result.lhs + 2, result.rhs)
# the RHS should include the closing symbol
result.rhs += 1
return result
# not found syntax stray dollar or brace
result.code = result.SYNTAX
return result
def test_istr():
def check2(l, r, text, dut):
print("----")
print("Check (%d,%d)" % (l, r))
print("s = %s" % str(dut))
print("i = %s" % dut.iarray())
result = dut.next_macro(0, len(dut))
if (result.lhs != l) or (result.rhs != r):
print("str = %s" % str(dut))
print("int = %s" % dut.iarray())
print("Error: (%d,%d) != (%d,%d)" % (l, r, result.lhs, result.rhs))
assert (False)
if text is not None:
assert( result.name == text )
dut.mark(l, r)
return dut
def check(l, r, s):
if l >= 0:
expected = s[l + 2:r - 1]
else:
expected = None
dut = IStr(s)
check2(l, r, expected, dut)
st = str(dut)
assert (st == s)
return dut
check(-1, -1, "")
check(-1, -1, "a")
check(-1, -1, "ab")
check(-1, -1, "abc")
check(-1, -1, "abcd")
check(-1, -1, "abcde")
check(-1, -1, "abcdef")
check(0, 4, "${a}")
check(0, 5, "${ab}")
check(0, 6, "${abc}")
check(0, 7, "${abcd}")
check(1, 5, "a${a}")
check(2, 6, "ab${a}")
check(3, 7, "abc${a}")
check(4, 8, "abcd${a}")
check(5, 9, "abcde${a}")
check(0, 4, "${a}a")
check(0, 4, "${a}ab")
check(0, 4, "${a}abc")
check(0, 4, "${a}abcd")
check(0, 4, "${a}abcde")
dut = check(4, 8, "abcd${a}xyz")
dut.replace(4, 8, "X")
check2(-1, -1, None, dut)
r = str(dut)
print("Got: %s" % r)
assert ("abcdXxyz" == str(dut))
# now nested tests
dut = check(5, 9, "abc${${Y}}xyz")
dut.replace(5, 9, "X")
r = str(dut)
assert (r == "abc${X}xyz")
dut = check2(3, 7, "${X}", dut)
dut.replace(3, 7, "ABC")
s = str(dut)
r = "abcABCxyz"
assert (s == r)
print("Success")
if __name__ == '__main__':
test_istr()
|
P, R = input().split()
if P == '0': print('C')
elif R == '0': print('B')
else: print('A') |
md_template_d144 = """verbosity=0
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=160
ny=80
nz=80
[Domain]
ox=0.
oy=0.
oz=0.
lx=42.4813
ly=21.2406
lz=21.2406
[Potentials]
pseudopotential=pseudo.D_tm_pbe
[Poisson]
solver=@
max_steps_initial=@50
max_steps=@50
reset=@
bcx=periodic
bcy=periodic
bcz=periodic
[Run]
type=MD
[MD]
type=@
num_steps=@
dt=@15.
[XLBOMD]
dissipation=@5
align=@
[Quench]
max_steps=@5
max_steps_tight=@
atol=1.e-@10
num_lin_iterations=3
ortho_freq=100
[SpreadPenalty]
type=@energy
damping=@
target=@1.75
alpha=@0.01
[Orbitals]
initial_type=Gaussian
initial_width=1.5
overallocate_factor=@2.
[ProjectedMatrices]
solver=@short_sighted
[LocalizationRegions]
radius=@8.
auxiliary_radius=@
move_tol=@0.1
[Restart]
input_filename=wave.out
input_level=3
interval=@
"""
md_template_H2O_64 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=128
ny=128
nz=128
[Domain]
ox=0.
oy=0.
oz=0.
lx=23.4884
ly=23.4884
lz=23.4884
[Potentials]
pseudopotential=pseudo.O_ONCV_PBE_SG15
pseudopotential=pseudo.D_ONCV_PBE_SG15
[Poisson]
solver=@
max_steps=@
[Run]
type=MD
[Quench]
max_steps=1000
atol=1.e-@
[MD]
type=@
num_steps=@
dt=10.
print_interval=5
[XLBOMD]
dissipation=@
align=@
[Restart]
input_filename=wave.out
input_level=4
output_level=4
interval=@
"""
quench_template_H2O_64 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=128
ny=128
nz=128
[Domain]
ox=0.
oy=0.
oz=0.
lx=23.4884
ly=23.4884
lz=23.4884
[Potentials]
pseudopotential=pseudo.O_ONCV_PBE_SG15
pseudopotential=pseudo.D_ONCV_PBE_SG15
[Run]
type=QUENCH
[Quench]
max_steps=1000
atol=1.e-8
[Orbitals]
initial_type=Fourier
[Restart]
output_level=4
"""
quench_template_d144 = """verbosity=1
xcFunctional=PBE
FDtype=4th
[Mesh]
nx=160
ny=80
nz=80
[Domain]
ox=0.
oy=0.
oz=0.
lx=42.4813
ly=21.2406
lz=21.2406
[Potentials]
pseudopotential=pseudo.D_tm_pbe
[Poisson]
solver=@
max_steps_initial=@50
max_steps=@50
bcx=periodic
bcy=periodic
bcz=periodic
[Run]
type=QUENCH
[Quench]
max_steps=200
atol=1.e-7
num_lin_iterations=3
ortho_freq=100
[SpreadPenalty]
type=@energy
damping=@
target=@1.75
alpha=@0.01
[Orbitals]
initial_type=Gaussian
initial_width=1.5
[ProjectedMatrices]
solver=@short_sighted
[LocalizationRegions]
radius=@8.
[Restart]
output_type=distributed
"""
H2O_64_params={
'nodes': '32',
'ntasks': '256',
'omp_num_threads': 8 if omp_num_threads == 4 else omp_num_threads,
'cores_per_task': '2',
'potentials': 'ln -s $maindir/potentials/pseudo.O_ONCV_PBE_SG15\nln -s $maindir/potentials/pseudo.D_ONCV_PBE_SG15',
'lrs': '',
'jobname': 'H2O_64',
}
d144_params={
'nodes': '8',
'walltime': '01:30:00',
'ntasks': '125',
'omp_num_threads': omp_num_threads,
'cores_per_task': '1',
'potentials': 'ln -s $maindir/potentials/pseudo.D_tm_pbe',
'lrs': '-l lrs.in',
'jobname': 'd144',
}
vulcan_params={
'queue': 'psmall',
'scratch_path': '/p/lscratchv/mgmolu/dunn27/mgmol/',
'gres': 'lscratchv',
'exe': 'mgmol-bgq',
}
cab_params={
'queue': 'pbatch',
'scratch_path': '/p/lscratchd/dunn27/mgmol/',
'gres': 'lscratchd',
'omp_num_threads': '1',
'exe': 'mgmol-pel',
'walltime': '01:30:00',
}
runfile_quench_template="""#!/bin/tcsh
#MSUB -l nodes={nodes},walltime={walltime}
#MSUB -o mgmol.out
#MSUB -q {queue}
#MSUB -A comp
#MSUB -l gres={gres}
#MSUB -N {jobname}
rm -f queued
echo ' ' > running
use boost-nompi-1.55.0
export BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0
export Boost_NO_SYSTEM_PATHS=ON
setenv OMP_NUM_THREADS {omp_num_threads}
set ntasks = {ntasks}
set maindir = $home/mgmol
set exe = $maindir/bin/{exe}
set datadir = `pwd`
set scratchdir = {scratch_path}`basename $datadir`
mkdir $scratchdir
cd $scratchdir
echo ' ' > running
set cfg_quench = mgmol_quench.cfg
cp $datadir/$cfg_quench .
cp $datadir/coords.in .
cp $datadir/lrs.in .
{potentials}
#1st run
srun -n $ntasks -c {cores_per_task} $exe -c $cfg_quench -i coords.in {lrs}
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
rm -f running
echo ' ' > queued
"""
runfile_md_template="""#!/bin/tcsh
#MSUB -l nodes={nodes},walltime={walltime}
#MSUB -o mgmol.out
#MSUB -q {queue}
#MSUB -A comp
#MSUB -l gres={gres}
#MSUB -N {jobname}
rm -f queued
echo ' ' > running
use boost-nompi-1.55.0
export BOOST_ROOT=/usr/local/tools/boost-nompi-1.55.0
export Boost_NO_SYSTEM_PATHS=ON
setenv OMP_NUM_THREADS {omp_num_threads}
set ntasks = {ntasks}
set maindir = $home/mgmol
set exe = $maindir/bin/{exe}
set datadir = `pwd`
set scratchdir = {scratch_path}`basename $datadir`
mkdir $scratchdir
cd $scratchdir
echo ' ' > running
set cfg_md = mgmol_md.cfg
cp $datadir/$cfg_md .
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
#MD run
srun -n $ntasks -c {cores_per_task} $exe -c $cfg_md
#restart
rm -f wave.out
set restart_file=`ls -ld * | awk '/snapshot0/ {{ print $9 }}' | tail -n1`
ln -s -f $restart_file wave.out
rm -f running
echo ' ' > queued
"""
|
#Create the pre-defined song values and empty variables...Correct names not used so each starting letter would be unique
numbers = (1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 )
letters = ['a ','b ','c ','d ','e ','f ','g ','h ','i ','j ','k ','l ','m ','n ','o ','p ','q ','r ']
roman = ['I ', 'II ', 'III ', 'IV ', 'V ', 'VI ', 'VII ', 'VIII ', 'IX ', 'X ', 'XI ', 'XII ', 'XIII ', 'XIV ', 'XV ', 'XVI ', 'XVII ', 'XVIII']
military = ['alpha ', 'bravo ', 'charlie ', 'delta ', 'echo ', 'foxtrot ', 'golf ', 'hotel ', 'india ', 'juliet ', 'kilo ', 'lima ', 'mike ', 'november ', 'oscar ', 'papa ', 'quebec ', 'romeo ']
german = ['eins', 'zwei', 'drei', 'vier', 'fünf', 'sechs', 'sieben', 'acht', 'neun', 'zehn', 'elf', 'zwölf', 'dreizehn', 'vierzehn', 'fünfzehn', 'sechzehn', 'siebzehn', 'achtzehn']
pi = ['3 ','point ','1 ','4 ','1 ','5 ','9 ','2 ','6 ','5 ','3 ','5 ','8 ','9 ','7 ','9 ','3 ','2 ']
##Build morse code sequences
t = 'dot'
s = 'dash'
m1 = t, s, s, s, s
m2 = t, t, s, s, s
m3 = t, t, t, s, s
m4 = t, t, t, t, s
m5 = t, t, t, t, t
m6 = s, t, t, t, t
m7 = s, s, t, t, t
m8 = s, s, s, t, t
m9 = s, s, s, s, t
m0 = s, s, s, s, s
code = [m1, m2, m3, m4, m5, m6, m7, m8, m9, m1 + m0, m1 + m1, m1 + m2, m1 + m3, m1 + m4, m1 + m5, m1 + m6, m1 + m7, m1 + m8]
##Other ideas: piglatin, japanese, spanish, prime, tau, e, ...
##NEED TO ADD INVALID ENTRY CATCHES
print("Hello, let's sing a song that everybody loves!\n")
sing = 'y'
while sing == 'y':
user = []
variation = input ("Please input what variation you wish to perform be entering 'numbers', 'letters', 'roman', 'military', 'pi', 'german', 'code', or 'user' to make your own song: \n").lower().strip()
##Seeming silly switching of strings to list types
if variation == "numbers" or variation == "n":
variation = numbers
elif variation == "letters" or variation == "l":
variation = letters
elif variation == "roman" or variation == "r":
variation = roman
elif variation == "military" or variation == "m":
variation = military
elif variation == "pi" or variation == "p":
variation = pi
elif variation == "german" or variation == "g":
variation = german
elif variation == "code" or variation == "c":
variation = code
elif variation == "user" or variation == "u":
while len(user) < 18:
user.append(input ("Enter a word: "))
#User input to select the song pattern
pattern = input ("\nNow please tell me what pattern to use by entering 'forward', 'backward', 'even', or 'odd':\n")
print ("\nHere we go: \n\n")
#Asemble the song...IMPROVE FORMAT SO OUTPUT IS EASIER TO READ
song1 = "Oh, there are "
song2 = " wheels on a big rig truck!"
a = song1, variation[::], song2
b = song1, variation[::-1], song2
c = song1, variation[::2], song2
d = song1, variation[1::2], song2
##Use pattern.startswith()?...Also, might be better to seperate forward/backward and even/odd choices.
if pattern == 'forward' or pattern == 'f':
print (a)
elif pattern == 'backward' or pattern == 'b':
print (b)
elif pattern == 'odd' or pattern == 'o':
print (c)
elif pattern == 'even' or pattern == 'e':
print (d)
sing = input('\n\nWould you like to sing it again? (y/n) ').lower()
## This is the end of the while loop
else:
print ("\nOK, Goodbye!")
|
"""
[E] Given a sorted array, create a new array containing squares of all the
number of the input array in the sorted order.
Input: [-2, -1, 0, 2, 3]
Output: [0, 1, 4, 4, 9]
"""
# Time: O(N) Space: O(n)
def make_squares(arr):
n = len(arr)
squares = [0 for x in range(n)]
highestSquareIdx = n - 1
left, right = 0, n - 1
while left <= right:
leftSquare = arr[left] * arr[left]
rightSquare = arr[right] * arr[right]
if leftSquare > rightSquare:
squares[highestSquareIdx] = leftSquare
left += 1
else:
squares[highestSquareIdx] = rightSquare
right -= 1
highestSquareIdx -= 1
return squares
|
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rules for importing and registering a local JDK."""
load(":default_java_toolchain.bzl", "JVM8_TOOLCHAIN_CONFIGURATION", "default_java_toolchain")
def _detect_java_version(repository_ctx, java_bin):
properties_out = repository_ctx.execute([java_bin, "-XshowSettings:properties"]).stderr
# This returns an indented list of properties separated with newlines:
# " java.vendor.url.bug = ... \n"
# " java.version = 11.0.8\n"
# " java.version.date = 2020-11-05\"
strip_properties = [property.strip() for property in properties_out.splitlines()]
version_property = [property for property in strip_properties if property.startswith("java.version = ")]
if len(version_property) != 1:
return None
version_value = version_property[0][len("java.version = "):]
parts = version_value.split(".")
major = parts[0]
if len(parts) == 1:
return major
elif major == "1": # handles versions below 1.8
minor = parts[1]
return minor
return major
def local_java_runtime(name, java_home, version, runtime_name = None, visibility = ["//visibility:public"]):
"""Defines a java_runtime target together with Java runtime and compile toolchain definitions.
Java runtime toolchain is constrained by flag --java_runtime_version having
value set to either name or version argument.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation. This requires a different configuration for JDK8
than the newer versions.
Args:
name: name of the target.
java_home: Path to the JDK.
version: Version of the JDK.
runtime_name: name of java_runtime target if it already exists.
visibility: Visibility that will be applied to the java runtime target
"""
if runtime_name == None:
runtime_name = name
native.java_runtime(
name = runtime_name,
java_home = java_home,
visibility = visibility,
)
native.config_setting(
name = name + "_name_setting",
values = {"java_runtime_version": name},
visibility = ["//visibility:private"],
)
native.config_setting(
name = name + "_version_setting",
values = {"java_runtime_version": version},
visibility = ["//visibility:private"],
)
native.config_setting(
name = name + "_name_version_setting",
values = {"java_runtime_version": name + "_" + version},
visibility = ["//visibility:private"],
)
native.alias(
name = name + "_settings_alias",
actual = select({
name + "_name_setting": name + "_name_setting",
name + "_version_setting": name + "_version_setting",
"//conditions:default": name + "_name_version_setting",
}),
visibility = ["//visibility:private"],
)
native.toolchain(
name = "runtime_toolchain_definition",
target_settings = [":%s_settings_alias" % name],
toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",
toolchain = runtime_name,
)
if version == "8":
default_java_toolchain(
name = name + "_toolchain_java8",
configuration = JVM8_TOOLCHAIN_CONFIGURATION,
source_version = version,
target_version = version,
java_runtime = runtime_name,
)
elif type(version) == type("") and version.isdigit() and int(version) > 8:
for version in range(8, int(version) + 1):
default_java_toolchain(
name = name + "_toolchain_java" + str(version),
source_version = str(version),
target_version = str(version),
java_runtime = runtime_name,
)
# else version is not recognized and no compilation toolchains are predefined
def _local_java_repository_impl(repository_ctx):
"""Repository rule local_java_repository implementation.
Args:
repository_ctx: repository context
"""
java_home = repository_ctx.attr.java_home
java_home_path = repository_ctx.path(java_home)
if not java_home_path.exists:
fail('The path indicated by the "java_home" attribute "%s" (absolute: "%s") ' +
"does not exist." % (java_home, str(java_home_path)))
repository_ctx.file(
"WORKSPACE",
"# DO NOT EDIT: automatically generated WORKSPACE file for local_java_repository\n" +
"workspace(name = \"{name}\")\n".format(name = repository_ctx.name),
)
extension = ".exe" if repository_ctx.os.name.lower().find("windows") != -1 else ""
java_bin = java_home_path.get_child("bin").get_child("java" + extension)
if not java_bin.exists:
# Java binary does not exist
repository_ctx.file(
"BUILD.bazel",
_NOJDK_BUILD_TPL.format(
local_jdk = repository_ctx.name,
java_binary = "bin/java" + extension,
java_home = java_home,
),
False,
)
return
# Detect version
version = repository_ctx.attr.version if repository_ctx.attr.version != "" else _detect_java_version(repository_ctx, java_bin)
# Prepare BUILD file using "local_java_runtime" macro
build_file = ""
if repository_ctx.attr.build_file != None:
build_file = repository_ctx.read(repository_ctx.path(repository_ctx.attr.build_file))
runtime_name = '"jdk"' if repository_ctx.attr.build_file else None
local_java_runtime_macro = """
local_java_runtime(
name = "%s",
runtime_name = %s,
java_home = "%s",
version = "%s",
)
""" % (repository_ctx.name, runtime_name, java_home, version)
repository_ctx.file(
"BUILD.bazel",
'load("@bazel_tools//tools/jdk:local_java_repository.bzl", "local_java_runtime")\n' +
build_file +
local_java_runtime_macro,
)
# Symlink all files
for file in repository_ctx.path(java_home).readdir():
repository_ctx.symlink(file, file.basename)
# Build file template, when JDK does not exist
_NOJDK_BUILD_TPL = '''load("@bazel_tools//tools/jdk:fail_rule.bzl", "fail_rule")
fail_rule(
name = "jdk",
header = "Auto-Configuration Error:",
message = ("Cannot find Java binary {java_binary} in {java_home}; either correct your JAVA_HOME, " +
"PATH or specify Java from remote repository (e.g. " +
"--java_runtime_version=remotejdk_11")
)
config_setting(
name = "localjdk_setting",
values = {{"java_runtime_version": "{local_jdk}"}},
visibility = ["//visibility:private"],
)
toolchain(
name = "runtime_toolchain_definition",
target_settings = [":localjdk_setting"],
toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",
toolchain = ":jdk",
)
'''
_local_java_repository_rule = repository_rule(
implementation = _local_java_repository_impl,
local = True,
configure = True,
attrs = {
"java_home": attr.string(),
"version": attr.string(),
"build_file": attr.label(),
},
)
def local_java_repository(name, java_home, version = "", build_file = None):
"""Registers a runtime toolchain for local JDK and creates an unregistered compile toolchain.
Toolchain resolution is constrained with --java_runtime_version flag
having value of the "name" or "version" parameter.
Java compile toolchains are created for --java_language_version flags values
between 8 and version (inclusive). Java compile toolchains use the same
(local) JDK for compilation.
If there is no JDK "virtual" targets are created, which fail only when actually needed.
Args:
name: A unique name for this rule.
java_home: Location of the JDK imported.
build_file: optionally BUILD file template
version: optionally java version
"""
_local_java_repository_rule(name = name, java_home = java_home, version = version, build_file = build_file)
native.register_toolchains("@" + name + "//:runtime_toolchain_definition")
|
"""Text parts."""
SEPARATOR = '----------------------------------'
CONT_GAME = 'enter для продолжения игры'
GREETING = 'Добро пожаловать в игру ''Сундук сокровищ''!\n' \
'Попробуй себя в роли капитана корабля, собери ' \
'команду и достань все сокровища!'
NAME_QUESTION = 'Как тебя зовут?'
CHOOSE_LEVEL = 'Выбери уровень сложности, он влияет на стоимость ' \
'сокровищ на островах. \n' \
'1 - легко \n' \
'2 - средне \n' \
'3 - тяжело'
INTRODUCTION = 'В наследство от дядюшки тебе достался корабль, \n' \
'несколько золотых монет и карта, на которой \n' \
'отмечены 10 островов. На каждом из островов \n' \
'зарыт клад. Но для того, чтобы достать его, \n' \
'необходимо обезвредить ловушку. Чем больше \n' \
'порядковый номер острова, тем ценнее хранящееся \n' \
'на нем сокровище и тем труднее его получить. \n\n' \
'Цель игры - добыть все сокровища и скопить как можно больше монет. \n\n' \
'Команда твоего корабля сможет обезвредить ловушку, \n' \
'только если будет иметь нужное количество очков \n' \
'логики, силы и ловкости. \n\n' \
'!!! Сумма всех требуемых очков равна номеру острова,\n' \
'но точная комбинация тебе неизвестна. !!!'
ORACLE_QUESTION = 'Здесь неподалеку живет известный оракул. За определенную\n' \
'плату он сможет предсказать с какой ловушкой\n' \
'ты столкнешься на острове. Пойдешь ли ты к нему?\n' \
'----------------------------------\n'\
'1 - да, пойду\n' \
'2 - нет, сам разберусь'
ORACLE_QUESTION_1 = 'Что ты хочешь узнать у оракула? \n' \
'----------------------------------\n'\
'1 - я передумал, буду сам себе оракул! \n'\
'2 - сколько очков логики должно быть у команды? (1 монета) \n'\
'3 - сколько очков силы должно быть у команды? (1 монета) \n'\
'4 - сколько очков ловкости должно быть у команды? (1 монета) \n'\
'5 - узнать все требуемые характеристики (3 монеты)'
ORACLE_QUESTION_2 = 'Что ты хочешь узнать у оракула? \n' \
'----------------------------------\n'\
'1 - я передумал, буду сам себе оракул! \n'\
'2 - сколько очков логики должно быть у команды? (1 монета) \n'\
'3 - сколько очков силы должно быть у команды? (1 монета) \n'\
'4 - сколько очков ловкости должно быть у команды? (1 монета)'
GO_TAVERN_TEXT = 'Отлично! Для похода на остров тебе понадобится \n' \
'команда, а нанять ее ты сможешь в таверне.'
EXIT_QUESTION = 'Продолжить игру?\n' \
'----------------------------------\n'\
'1 - да\n' \
'2 - нет'
SUCCESS_STEP = 'Поздравляю! Ты смог достать спрятанное сокровище! \n' \
'Самое время готовиться к следующему походу.'
FAILURE_STEP = 'К сожалению, ты не смог достать сокровище. \n' \
'Если у тебя еще остались монеты, то можешь \n' \
'попробовать организовать поход заново. Удачи!'
WINNING = 'Поздравляю! Ты собрал сокровища со всех окрестных \n' \
'островов, можешь выкинуть ненужную теперь карту) \n' \
'Конец игры.'
LOSING = 'Сожалею, ты потратил все деньги. Карьера пиратского \n' \
'капитана подошла к концу. А дядюшка в тебя верил! \n' \
'Конец игры.'
NAMES = ['Боб', 'Ричард', 'Алан', 'Степан', 'Грозный Глаз', 'Гарри',
'Моррис', 'Джек', 'Алекс', 'Сэм', 'Том', 'Янис', 'Геральт',
'Ринсвинд', 'Купер', 'Борис', 'Джон', 'Рон']
|
"""
Here you find either new implemented modules or alternate implementations
of already modules. This directory is intended to have a second implementation
beside the main implementation to have a discussion which implementation to
favor on the long run.
"""
|
"""Registry utilities to handle formats for gmso Topology."""
class UnsupportedFileFormatError(Exception):
"""Exception to be raised whenever the file loading or saving is not supported."""
class Registry:
"""A registry to incorporate a callable with a file extension."""
def __init__(self):
self.handlers = {}
def _assert_can_process(self, extension):
if extension not in self.handlers:
raise UnsupportedFileFormatError(
f"Extension {extension} cannot be processed as no utility "
f"is defined in the current API to handle {extension} files."
)
def get_callable(self, extension):
"""Get the callable associated with extension."""
self._assert_can_process(extension)
return self.handlers[extension]
SaversRegistry = Registry()
LoadersRegistry = Registry()
class saves_as:
"""Decorator to aid saving."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as saver for an extension."""
for ext in self.extensions:
SaversRegistry.handlers[ext] = method
return method
class loads_as:
"""Decorator to aid loading."""
def __init__(self, *extensions):
extension_set = set(extensions)
self.extensions = extension_set
def __call__(self, method):
"""Register the method as loader for an extension."""
for ext in self.extensions:
LoadersRegistry.handlers[ext] = method
return method
|
dosyaadi = input("Enter file name: ")
dosyaadi = str(dosyaadi + ".txt")
with open(dosyaadi, 'r') as file :
dosyaicerigi = file.read()
silinecek = str(input("Enter the text that you wish to delete: "))
dosyaicerigi = dosyaicerigi.replace(silinecek, '')
with open(dosyaadi, 'w') as file:
file.write(dosyaicerigi)
file.close()
print("-" * 30)
print("Successfully deleted!")
print("-" * 30)
|
"""
decoded AUTH_HEADER (newlines added for readability):
{
"identity": {
"account_number": "1234",
"internal": {
"org_id": "5678"
},
"type": "User",
"user": {
"email": "test@example.com",
"first_name": "Firstname",
"is_active": true,
"is_internal": true,
"is_org_admin": false,
"last_name": "Lastname",
"locale": "en_US",
"username": "test_username"
}
}
"entitlements": {
"smart_management": {
"is_entitled": true
}
}
}
"""
AUTH_HEADER = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6"
"IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiI1"
"Njc4In0sInR5cGUiOiJVc2VyIiwidXNlciI6eyJl"
"bWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJmaXJz"
"dF9uYW1lIjoiRmlyc3RuYW1lIiwiaXNfYWN0aXZl"
"Ijp0cnVlLCJpc19pbnRlcm5hbCI6dHJ1ZSwiaXNf"
"b3JnX2FkbWluIjpmYWxzZSwibGFzdF9uYW1lIjoi"
"TGFzdG5hbWUiLCJsb2NhbGUiOiJlbl9VUyIsInVz"
"ZXJuYW1lIjoidGVzdF91c2VybmFtZSJ9fSwiZW50"
"aXRsZW1lbnRzIjogeyJzbWFydF9tYW5hZ2VtZW50"
"IjogeyJpc19lbnRpdGxlZCI6IHRydWUgfX19Cg=="
}
AUTH_HEADER_NO_ENTITLEMENTS = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6Ij"
"EyMzQiLCJ0eXBlIjoiVXNlciIsInVzZXIiOnsidXNl"
"cm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIiwiZW1haWwiOi"
"J0ZXN0QGV4YW1wbGUuY29tIiwiZmlyc3RfbmFtZSI6"
"IkZpcnN0bmFtZSIsImxhc3RfbmFtZSI6Ikxhc3RuYW"
"1lIiwiaXNfYWN0aXZlIjp0cnVlLCJpc19vcmdfYWRt"
"aW4iOmZhbHNlLCJpc19pbnRlcm5hbCI6dHJ1ZSwibG"
"9jYWxlIjoiZW5fVVMifSwiaW50ZXJuYWwiOnsib3Jn"
"X2lkIjoiNTY3OCJ9fX0KCg=="
}
AUTH_HEADER_SMART_MGMT_FALSE = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJhY2NvdW50X251bWJlciI6"
"IjEyMzQiLCJpbnRlcm5hbCI6eyJvcmdfaWQiOiAi"
"NTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1c2VyIjp7"
"ImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImZp"
"cnN0X25hbWUiOiJGaXJzdG5hbWUiLCJpc19hY3Rp"
"dmUiOnRydWUsImlzX2ludGVybmFsIjp0cnVlLCJp"
"c19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0X25hbWUi"
"OiJMYXN0bmFtZSIsImxvY2FsZSI6ImVuX1VTIiwi"
"dXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1lIn19LCJl"
"bnRpdGxlbWVudHMiOnsic21hcnRfbWFuYWdlbWVu"
"dCI6eyJpc19lbnRpdGxlZCI6IGZhbHNlfX19Cg=="
}
# this can't happen in real life, adding test anyway
AUTH_HEADER_NO_ACCT_BUT_HAS_ENTS = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJpbnRlcm5hbCI6eyJvcmdf"
"aWQiOiAiNTY3OCJ9LCJ0eXBlIjogIlVzZXIiLCJ1"
"c2VyIjp7ImVtYWlsIjoidGVzdEBleGFtcGxlLmNv"
"bSIsImZpcnN0X25hbWUiOiJGaXJzdG5hbWUiLCJp"
"c19hY3RpdmUiOnRydWUsImlzX2ludGVybmFsIjp0"
"cnVlLCJpc19vcmdfYWRtaW4iOmZhbHNlLCJsYXN0"
"X25hbWUiOiJMYXN0bmFtZSIsImxvY2FsZSI6ImVu"
"X1VTIiwidXNlcm5hbWUiOiJ0ZXN0X3VzZXJuYW1l"
"In19LCJlbnRpdGxlbWVudHMiOnsic21hcnRfbWFu"
"YWdlbWVudCI6eyJpc19lbnRpdGxlZCI6IHRydWV9"
"fX0K"
}
"""
decoded AUTH_HEADER_NO_ACCT (newlines added for readablity):
{
"identity": {
"internal": {
"org_id": "9999"
},
"type": "User",
"user": {
"email": "nonumber@example.com",
"first_name": "No",
"is_active": true,
"is_internal": true,
"is_org_admin": false,
"last_name": "Number",
"locale": "en_US",
"username": "nonumber"
}
}
}
"""
AUTH_HEADER_NO_ACCT = {
"X-RH-IDENTITY": "eyJpZGVudGl0eSI6eyJ0eXBlIjoiVXNlciIsInVzZXIiO"
"nsidXNlcm5hbWUiOiJub251bWJlciIsImVtYWlsIjoibm"
"9udW1iZXJAZXhhbXBsZS5jb20iLCJmaXJzdF9uYW1lIjo"
"iTm8iLCJsYXN0X25hbWUiOiJOdW1iZXIiLCJpc19hY3Rp"
"dmUiOnRydWUsImlzX29yZ19hZG1pbiI6ZmFsc2UsImlzX"
"2ludGVybmFsIjp0cnVlLCJsb2NhbGUiOiJlbl9VUyJ9LC"
"JpbnRlcm5hbCI6eyJvcmdfaWQiOiI5OTk5In19fQo="
}
BASELINE_ONE_LOAD = {
"baseline_facts": [
{"name": "arch", "value": "x86_64"},
{"name": "phony.arch.fact", "value": "some value"},
],
"display_name": "arch baseline",
}
BASELINE_TWO_LOAD = {
"baseline_facts": [
{"name": "memory", "value": "64GB"},
{"name": "cpu_sockets", "value": "16"},
],
"display_name": "cpu + mem baseline",
}
BASELINE_THREE_LOAD = {
"baseline_facts": [
{"name": "nested", "values": [{"name": "cpu_sockets", "value": "16"}]}
],
"display_name": "cpu + mem baseline",
}
BASELINE_PARTIAL_ONE = {"baseline_facts": [{"name": "hello", "value": "world"}]}
BASELINE_PARTIAL_TWO = {
"display_name": "ABCDE",
"baseline_facts": [
{
"name": "hello",
"values": [
{"name": "nested_one", "value": "one"},
{"name": "nested_two", "value": "two"},
],
}
],
}
BASELINE_PARTIAL_CONFLICT = {"display_name": "arch baseline"}
CREATE_FROM_INVENTORY = {
"display_name": "created_from_inventory",
"inventory_uuid": "df925152-c45d-11e9-a1f0-c85b761454fa",
}
SYSTEM_WITH_PROFILE = {
"account": "9876543",
"bios_uuid": "e380fd4a-28ae-11e9-974c-c85b761454fb",
"created": "2018-01-31T13:00:00.100010Z",
"display_name": None,
"fqdn": None,
"id": "bbbbbbbb-28ae-11e9-afd9-c85b761454fa",
"insights_id": "00000000-28af-11e9-9ab0-c85b761454fa",
"ip_addresses": ["10.0.0.3", "2620:52:0:2598:5054:ff:fecd:ae15"],
"mac_addresses": ["52:54:00:cd:ae:00", "00:00:00:00:00:00"],
"rhel_machine_id": None,
"satellite_id": None,
"subscription_manager_id": "RHN Classic and Red Hat Subscription Management",
"system_profile": {
"salutation": "hi",
"system_profile_exists": False,
"installed_packages": [
"openssl-1.1.1c-2.fc30.x86_64",
"python2-libs-2.7.16-2.fc30.x86_64",
],
"id": "bbbbbbbb-28ae-11e9-afd9-c85b761454fa",
},
"tags": [],
"updated": "2018-01-31T14:00:00.500000Z",
}
|
#!/usr/bin/python
_author_ = "Matthew Zheng"
_purpose_ = "Sets up the unit class"
class Unit:
'''This is a class of lists'''
def __init__(self):
self.baseUnits = ["m", "kg", "A", "s", "K", "mol", "cd", "sr", "rad"]
self.derivedUnits = ["Hz", "N", "Pa", "J", "W", "C", "V", "F", "ohm", "S", "Wb", "T", "H", "°C", "lm", "lx", "Bq", "Gy", "Sv", "kat"]
def baseCheck(self, userList):
'''Converts elements in str list to base units'''
converted = []
for i in (userList):
isSquared = False
unitPreIndex = ""
#checks if it has a carat in the expression
for ind, j in enumerate(list(i)):
if j == "^":
isSquared = True
unitPreIndex = ''.join(list(i)[:ind])
break
#converts non-unary unit to base unit and checks for squared variables
while(i not in (self.baseUnits or self.derivedUnits) and len(list(i)) != 1 and unitPreIndex not in (self.baseUnits or self.derivedUnits) and len(unitPreIndex) != 1):
orgNameList = list(i)
#identify prefix removed
self.idPrefix = orgNameList.pop(0)
i = ''.join(orgNameList)
print("The program removed the prefix %s and converted your unit to it's base unit: %s." % (self.idPrefix, i))
#checks if it is a special unit
if(i not in (self.baseUnits and self.derivedUnits)):
#append in case for special units
break
else:
#append in case for base unit
break
#Appends base unit
if(i in (self.baseUnits or self.derivedUnits) and isSquared == False):
converted.append(i)
elif(isSquared == True):
toAppend = []
numReps = []
#run once to get number of times the unit is squared
for index, val in enumerate(list(i)):
if val == "^":
numStart = index+1
numReps.append(''.join(list(i)[numStart:]))
toAppend.append(''.join(list(i)[:index]))
break
#convert numReps into an int
intReps = int(''.join(numReps))
#append number of units specified by the carat
for l in range (intReps):
if(''.join(toAppend) not in (self.baseUnits or self.derivedUnits)):
print("Your variable %s was not in the commonly used units OR it is a derived unit such as N, newtons -- we will add it to the product regardless." % ''.join(toAppend))
converted.append(''.join(toAppend))
#Exception for special units
else:
print("Your variable %s was not in the commonly used units OR it is a derived unit such as N, newtons -- we will add it to the product regardless." % i)
converted.append(i)
return(converted)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 22:23:07 2020
@author: Neal LONG
Try to construct URL with string.format
"""
base_url = "http://quotes.money.163.com/service/gszl_{:>06}.html?type={}"
stock = "000002"
api_type = 'cp'
print("http://quotes.money.163.com/service/gszl_"+stock+".html?type="+api_type)
print(base_url.format(stock,api_type))
print('='*40)
stock = "00002"
print("http://quotes.money.163.com/service/gszl_"+stock+".html?type="+api_type)
print(base_url.format(stock,api_type))
print('='*40)
print('='*40)
print('{:>6}'.format('236'))
print('{:>06}'.format('236'))
print("Every {} should know the use of {}-{} programming and {}"
.format("programmer", "Open", "Source", "Operating Systems"))
print("Every {3} should know the use of {2}-{1} programming and {0}"
.format("programmer", "Open", "Source", "Operating Systems")) |
'''
DNA++ (c) DNA++ 2017
All rights reserved.
@author: neilswainston
'''
|
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
soma = col3 = maior = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'[{l}][{c}]: '))
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]:^5}]', end='')
if matriz[l][c] % 2 == 0:
soma += matriz[l][c]
print()
for l in range(0, 3):
col3 += matriz[l][2]
for c in range(0, 3):
if c == 0:
maior = matriz[1][c]
elif matriz[1][c] > maior:
maior = matriz[1][c]
print(f'A soma dos numeros pares é {soma}')
print(f'A soma dos valores da 3 coluna é {col3}')
print(f'O maior numero da 2 linha é {maior}') |
"""Mock responses for recommendations."""
SEARCH_REQ = {
"criteria": {
"policy_type": ['reputation_override'],
"status": ['NEW', 'REJECTED', 'ACCEPTED'],
"hashes": ['111', '222']
},
"rows": 50,
"sort": [
{
"field": "impact_score",
"order": "DESC"
}
]
}
SEARCH_RESP = {
"results": [
{
"recommendation_id": "91e9158f-23cc-47fd-af7f-8f56e2206523",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede",
"filename": "XprotectService",
"application": {
"type": "EXE",
"value": "FOO"
}
},
"workflow": {
"status": "NEW",
"changed_by": "rbaratheon@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T20:53:39.000Z",
"comment": "Ours is the fury"
},
"impact": {
"org_adoption": "LOW",
"impacted_devices": 45,
"event_count": 76,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
},
{
"recommendation_id": "bd50c2b2-5403-4e9e-8863-9991f70df026",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0",
"filename": "sophos ui.msi"
},
"workflow": {
"status": "NEW",
"changed_by": "tlannister@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T20:53:09.000Z",
"comment": "Always pay your debts"
},
"impact": {
"org_adoption": "HIGH",
"impacted_devices": 8,
"event_count": 25,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
},
{
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "NEW",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
],
"num_found": 3
}
ACTION_INIT = {
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "NEW",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
ACTION_REQS = [
{
"action": "ACCEPT",
"comment": "Alpha"
},
{
"action": "RESET"
},
{
"action": "REJECT",
"comment": "Charlie"
},
]
ACTION_REFRESH_SEARCH = {
"criteria": {
"status": ['NEW', 'REJECTED', 'ACCEPTED'],
"policy_type": ['reputation_override']
},
"rows": 50
}
ACTION_SEARCH_RESP = {
"results": [ACTION_INIT],
"num_found": 1
}
ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED']
ACTION_INIT_ACCEPTED = {
"recommendation_id": "0d9da444-cfa7-4488-9fad-e2abab099b68",
"rule_type": "reputation_override",
"policy_id": 0,
"new_rule": {
"override_type": "SHA256",
"override_list": "WHITE_LIST",
"sha256_hash": "2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124",
"filename": "mimecast for outlook 7.8.0.125 (x86).msi"
},
"workflow": {
"status": "ACCEPTED",
"ref_id": "e9410b754ea011ebbfd0db2585a41b07",
"changed_by": "estark@example.com",
"create_time": "2021-05-18T16:37:07.000Z",
"update_time": "2021-08-31T15:13:40.000Z",
"comment": "Winter is coming"
},
"impact": {
"org_adoption": "MEDIUM",
"impacted_devices": 45,
"event_count": 79,
"impact_score": 0,
"update_time": "2021-05-18T16:37:07.000Z"
}
}
|
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
return root
return None |
def assert_not_none(actual_result, message=""):
if not message:
message = f"{actual_result} resulted with None"
assert actual_result, message
def assert_equal(actual_result, expected_result, message=""):
if not message:
message = f"{actual_result} is not equal to expected " \
f"result {expected_result}"
assert actual_result == expected_result, message
def assert_in_list(searched_list, wanted_element, message=""):
if not message:
message = f"Failed to find '{wanted_element}' in list {searched_list}"
assert wanted_element in searched_list, message
def assert_not_in_list(searched_list, unwanted_element, message=""):
if not message:
message = f"'{unwanted_element}' found in list {searched_list} \n " \
f"although it should not be"
assert unwanted_element not in searched_list, message
def assert_of_type(wanted_type, wanted_object, message=""):
if not message:
message = f"{wanted_object} is not of type: {wanted_type}"
assert isinstance(wanted_object, wanted_type), message
|
# Square 方片 => sq => RGB蓝色(Blue)
# Plum 梅花 => pl => RGB绿色(Green)
# Spade 黑桃 => sp => RGB黑色(Black)
# Heart 红桃 => he => RGB红色(Red)
init_poker = {
'local': {
'head': [-1, -1, -1],
'mid': [-1, -1, -1, -1, -1],
'tail': [-1, -1, -1, -1, -1],
'drop': [-1, -1, -1, -1],
'hand': [-1, -1, -1]
},
'player1': {
'head': [-1, -1, -1],
'mid': [-1, -1, -1, -1, -1],
'tail': [-1, -1, -1, -1, -1],
'drop': [-1, -1, -1, -1],
'hand': [-1, -1, -1]
},
'player2': {
'head': [-1, -1, -1],
'mid': [-1, -1, -1, -1, -1],
'tail': [-1, -1, -1, -1, -1],
'drop': [-1, -1, -1, -1],
'hand': [-1, -1, -1]
}
}
# Square
Blue = {
'2': 0,
'3': 1,
'4': 2,
'5': 3,
'6': 4,
'7': 5,
'8': 6,
'9': 7,
'10': 8,
'J': 9,
'Q': 10,
'K': 11,
'A': 12
}
# Plum
Green = {
'2': 13,
'3': 14,
'4': 15,
'5': 16,
'6': 17,
'7': 18,
'8': 19,
'9': 20,
'10': 21,
'J': 22,
'Q': 23,
'K': 24,
'A': 25
}
# Heart
Red = {
'2': 26,
'3': 27,
'4': 28,
'5': 29,
'6': 30,
'7': 31,
'8': 32,
'9': 33,
'10': 34,
'J': 35,
'Q': 36,
'K': 37,
'A': 38
}
# Spade
Black = {
'2': 39,
'3': 40,
'4': 41,
'5': 42,
'6': 43,
'7': 44,
'8': 45,
'9': 46,
'10': 47,
'J': 48,
'Q': 49,
'K': 50,
'A': 51
}
POKER_SCOPE = [
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'J',
'Q',
'K',
'A'
]
|
"""
This is the doc for the Grid Diagnostics module. These functions
are based on the grid diagnostics from the GEneral Meteorological
PAcKage (GEMPAK). Note that the names are case sensitive and some
are named slightly different from GEMPAK functions to avoid conflicts
with Jython built-ins (e.g. str).
<P>
In the following operators, scalar operands are named S<sub>n</sub> and
vector operands are named V<sub>n</sub>. Lowercase u and v refer to the
grid relative components of a vector.
"""
def GRAVITY():
""" Gravity constant """
return DerivedGridFactory.GRAVITY;
# Math functions
def atn2(S1,S2,WA=0):
""" Wrapper for atan2 built-in
<div class=jython>
ATN2 (S1, S2) = ATAN ( S1 / S2 )<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.atan2(S1,S2,WA)
def add(S1,S2,WA=0):
""" Addition
<div class=jython>
ADD (S1, S2) = S1 + S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.add(S1,S2,WA)
def mul(S1,S2,WA=0):
""" Multiply
<div class=jython>
MUL (S1, S2) = S1 * S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.multiply(S1,S2,WA)
def quo(S1,S2,WA=0):
""" Divide
<div class=jython>
QUO (S1, S2) = S1 / S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.divide(S1,S2,WA)
def sub(S1,S2,WA=0):
""" Subtract
<div class=jython>
SUB (S1, S2) = S1 - S2<br>
WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)
</div>
"""
return GridMath.subtract(S1,S2,WA)
# Scalar quantities
def adv(S,V):
""" Horizontal Advection, negative by convention
<div class=jython>
ADV ( S, V ) = - ( u * DDX (S) + v * DDY (S) )
</div>
"""
return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S)))
def avg(S1,S2):
""" Average of 2 scalars
<div class=jython>
AVG (S1, S2) = ( S1 + S2 ) / 2
</div>
"""
return add(S1,S2)/2
def avor(V):
""" Absolute Vorticity
<div class=jython>
AVOR ( V ) = VOR ( V ) + CORL(V)
</div>
"""
relv = vor(V)
return add(relv,corl(relv))
def circs(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CIRC", int(D))
def corl(S):
""" Coriolis Parameter for all points in a grid
<div class=jython>
CORL = TWO_OMEGA*sin(latr)
</div>
"""
return DerivedGridFactory.createCoriolisGrid(S)
def cress(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CRES", int(D))
def cros(V1,V2):
""" Vector cross product magnitude
<div class=jython>
CROS ( V1, V2 ) = u1 * v2 - u2 * v1
</div>
"""
return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1)))
def ddx(S):
""" Take the derivative with respect to the domain's X coordinate
"""
return GridMath.ddx(S);
def ddy(S):
""" Take the derivative with respect to the domain's Y coordinate
"""
return GridMath.ddy(S);
def defr(V):
""" Total deformation
<div class=jython>
DEF ( V ) = ( STRD (V) ** 2 + SHR (V) ** 2 ) ** .5
</div>
"""
return mag(strd(V),shr(V))
def div(V):
""" Horizontal Divergence
<div class=jython>
DIV ( V ) = DDX ( u ) + DDY ( v )
</div>
"""
return add(ddx(ur(V)),ddy(vr(V)))
def dirn(V):
""" North relative direction of a vector
<div class=jython>
DIRN ( V ) = DIRR ( un(v), vn(v) )
</div>
"""
return dirr(DerivedGridFactory.createTrueFlowVector(V))
def dirr(V):
""" Grid relative direction of a vector
"""
return DerivedGridFactory.createVectorDirection(V)
def dot(V1,V2):
""" Vector dot product
<div class=jython>
DOT ( V1, V2 ) = u1 * u2 + v1 * v2
</div>
"""
product = mul(V1,V2)
return add(ur(product),vr(product))
def gwfs(S, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return GridUtil.smooth(S, "GWFS", int(N))
def jcbn(S1,S2):
""" Jacobian Determinant
<div class=jython>
JCBN ( S1, S2 ) = DDX (S1) * DDY (S2) - DDY (S1) * DDX (S2)
</div>
"""
return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2)))
def latr(S):
""" Latitudue all points in a grid
"""
return DerivedGridFactory.createLatitudeGrid(S)
def lap(S):
""" Laplacian operator
<div class=jython>
LAP ( S ) = DIV ( GRAD (S) )
</div>
"""
grads = grad(S)
return div(grads)
def lav(S,level1=None,level2=None, unit=None):
""" Layer Average of a multi layer grid
<div class=jython>
LAV ( S ) = ( S (level1) + S (level2) ) / 2.
</div>
"""
if level1 == None:
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE)
else:
return layerAverage(S,level1,level2, unit)
def ldf(S,level1,level2, unit=None):
""" Layer Difference
<div class=jython>
LDF ( S ) = S (level1) - S (level2)
</div>
"""
return layerDiff(S,level1,level2, unit);
def mag(*a):
""" Magnitude of a vector
"""
if (len(a) == 1):
return DerivedGridFactory.createVectorMagnitude(a[0]);
else:
return DerivedGridFactory.createVectorMagnitude(a[0],a[1]);
def mixr(temp,rh):
""" Mixing Ratio from Temperature, RH (requires pressure domain)
"""
return DerivedGridFactory.createMixingRatio(temp,rh)
def relh(temp,mixr):
""" Create Relative Humidity from Temperature, mixing ratio (requires pressure domain)
"""
return DerivedGridFactory.createRelativeHumidity(temp,mixr)
def pvor(S,V):
""" Potetial Vorticity (usually from theta and wind)
"""
return DerivedGridFactory.createPotentialVorticity(S,V)
def rects(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "RECT", int(D))
def savg(S):
""" Average over whole grid
<div class=jython>
SAVG ( S ) = average of all non-missing grid point values
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def savs(S):
""" Average over grid subset
<div class=jython>
SAVS ( S ) = average of all non-missing grid point values in the subset
area
</div>
"""
return savg(S)
def sdiv(S,V):
""" Horizontal Flux Divergence
<div class=jython>
SDIV ( S, V ) = S * DIV ( V ) + DOT ( V, GRAD ( S ) )
</div>
"""
return add(mul(S,(div(V))) , dot(V,grad(S)))
def shr(V):
""" Shear Deformation
<div class=jython>
SHR ( V ) = DDX ( v ) + DDY ( u )
</div>
"""
return add(ddx(vr(V)),ddy(ur(V)))
def sm5s(S):
""" Smooth a scalar grid using a 5-point smoother
<div class=jython>
SM5S ( S ) = .5 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
</div>
"""
return GridUtil.smooth(S, "SM5S")
def sm9s(S):
""" Smooth a scalar grid using a 9-point smoother
<div class=jython>
SM9S ( S ) = .25 * S (i,j) + .125 * ( S (i+1,j) + S (i,j+1) +
S (i-1,j) + S (i,j-1) )
+ .0625 * ( S (i+1,j+1) +
S (i+1,j-1) +
S (i-1,j+1) +
S (i-1,j-1) )
</div>
"""
return GridUtil.smooth(S, "SM9S")
def strd(V):
""" Stretching Deformation
<div class=jython>
STRD ( V ) = DDX ( u ) - DDY ( v )
</div>
"""
return sub(ddx(ur(V)),ddy(vr(V)))
def thta(temp):
""" Potential Temperature from Temperature (requires pressure domain)
"""
return DerivedGridFactory.createPotentialTemperature(temp)
def thte(temp,rh):
""" Equivalent Potential Temperature from Temperature and Relative
humidity (requires pressure domain)
"""
return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh)
def un(V):
""" North relative u component
"""
return ur(DerivedGridFactory.createTrueFlowVector(V))
def ur(V):
""" Grid relative u component
"""
return DerivedGridFactory.getUComponent(V)
def vn(V):
""" North relative v component
"""
return vr(DerivedGridFactory.createTrueFlowVector(V))
def vor(V):
""" Relative Vorticity
<div class=jython>
VOR ( V ) = DDX ( v ) - DDY ( u )
</div>
"""
return sub(ddx(vr(V)),ddy(ur(V)))
def vr(V):
""" Grid relative v component
"""
return DerivedGridFactory.getVComponent(V)
def xav(S):
""" Average along a grid row
<div class=jython>
XAV (S) = ( S (X1) + S (X2) + ... + S (KXD) ) / KNT
KXD = number of points in row
KNT = number of non-missing points in row
XAV for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X)
def xsum(S):
""" Sum along a grid row
<div class=jython>
XSUM (S) = ( S (X1) + S (X2) + ... + S (KXD) )
KXD = number of points in row
XSUM for a row is stored at every point in that row.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X)
def yav(S):
""" Average along a grid column
<div class=jython>
YAV (S) = ( S (Y1) + S (Y2) + ... + S (KYD) ) / KNT
KYD = number of points in column
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y)
def ysum(S):
""" Sum along a grid column
<div class=jython>
YSUM (S) = ( S (Y1) + S (Y2) + ... + S (KYD) )
KYD = number of points in row
YSUM for a column is stored at every point in that column.
</div>
"""
return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y)
def zav(S):
""" Average across the levels of a grid at all points
<div class=jython>
ZAV (S) = ( S (Z1) + S (Z2) + ... + S (KZD) ) / KNT
KZD = number of levels
KNT = number of non-missing points in column
</div>
"""
return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)
def zsum(S):
""" Sum across the levels of a grid at all points
<div class=jython>
ZSUM (S) = ( S (Z1) + S (Z2) + ... + S (KZD) )
KZD = number of levels
ZSUM for a vertical column is stored at every point
</div>
"""
return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM)
def wshr(V, Z, top, bottom):
""" Magnitude of the vertical wind shear in a layer
<div class=jython>
WSHR ( V ) = MAG [ VLDF (V) ] / LDF (Z)
</div>
"""
dv = mag(vldf(V,top,bottom))
dz = ldf(Z,top,bottom)
return quo(dv,dz)
# Vector output
def age(obs,geo):
""" Ageostrophic wind
<div class=jython>
AGE ( S ) = [ u (OBS) - u (GEO(S)), v (OBS) - v (GEO(S)) ]
</div>
"""
return sub(obs,geo)
def circv(S, D=2):
"""
<div class=jython>
Apply a circular aperature smoothing to the grid points. The weighting
function is the circular aperature diffraction function. D is
the radius of influence in grid increments, increasing D increases
the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CIRC", int(D))
def cresv(S, D=2):
"""
<div class=jython>
Apply a Cressman smoothing to the grid points. The smoothed value
is given by a weighted average of surrounding grid points. D is
the radius of influence in grid increments,
increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "CRES", int(D))
def dvdx(V):
""" Partial x derivative of a vector
<div class=jython>
DVDX ( V ) = [ DDX (u), DDX (v) ]
</div>
"""
return vecr(ddx(ur(V)), ddx(vr(V)))
def dvdy(V):
""" Partial x derivative of a vector
<div class=jython>
DVDY ( V ) = [ DDY (u), DDY (v) ]
</div>
"""
return vecr(ddy(ur(V)), ddy(vr(V)))
def frnt(S,V):
""" Frontogenesis function from theta and the wind
<div class=jython>
FRNT ( THTA, V ) = 1/2 * MAG ( GRAD (THTA) ) *
( DEF * COS (2 * BETA) - DIV ) <p>
Where: BETA = ASIN ( (-DDX (THTA) * COS (PSI) <br>
- DDY (THTA) * SIN (PSI))/ <br>
MAG ( GRAD (THTA) ) ) <br>
PSI = 1/2 ATAN2 ( SHR / STR ) <br>
</div>
"""
shear = shr(V)
strch = strd(V)
psi = .5*atn2(shear,strch)
dxt = ddx(S)
dyt = ddy(S)
cosd = cos(psi)
sind = sin(psi)
gradt = grad(S)
mgradt = mag(gradt)
a = -cosd*dxt-sind*dyt
beta = asin(a/mgradt)
frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V))
return frnto
def geo(z):
""" geostrophic wind from height
<div class=jython>
GEO ( S ) = [ - DDY (S) * const / CORL, DDX (S) * const / CORL ]
</div>
"""
return DerivedGridFactory.createGeostrophicWindVector(z)
def grad(S):
""" Gradient of a scalar
<div class=jython>
GRAD ( S ) = [ DDX ( S ), DDY ( S ) ]
</div>
"""
return vecr(ddx(S),ddy(S))
def gwfv(V, N=6):
"""
<div class=jython>
Horizontal smoothing using normally distributed weights
with theoretical response of 1/e for N * delta-x wave.
Increasing N increases the smoothing. (default N=6)
</div>
"""
return gwfs(V, N)
def inad(V1,V2):
""" Inertial advective wind
<div class=jython>
INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ),
DOT ( V1, GRAD (v2) ) ]
</div>
"""
return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2))))
def qvec(S,V):
""" Q-vector at a level ( K / m / s )
<div class=jython>
QVEC ( S, V ) = [ - ( DOT ( DVDX (V), GRAD (S) ) ),
- ( DOT ( DVDY (V), GRAD (S) ) ) ]
where S can be any thermal paramenter, usually THTA.
</div>
"""
grads = grad(S)
qvecu = newName(-dot(dvdx(V),grads),"qvecu")
qvecv = newName(-dot(dvdy(V),grads),"qvecv")
return vecr(qvecu,qvecv)
def qvcl(THTA,V):
""" Q-vector ( K / m / s )
<div class=jython>
QVCL ( THTA, V ) = ( 1/( D (THTA) / DP ) ) *
[ ( DOT ( DVDX (V), GRAD (THTA) ) ),
( DOT ( DVDY (V), GRAD (THTA) ) ) ]
</div>
"""
dtdp = GridMath.partial(THTA,2)
gradt = grad(THTA)
qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),"qvecudp")
qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),"qvecvdp")
return vecr(qvecudp,qvecvdp)
def rectv(S, D=2):
"""
<div class=jython>
Apply a rectangular aperature smoothing to the grid points. The weighting
function is the product of the rectangular aperature diffraction function
in the x and y directions. D is the radius of influence in grid
increments, increasing D increases the smoothing. (default D=2)
</div>
"""
return GridUtil.smooth(S, "RECT", int(D))
def sm5v(V):
""" Smooth a scalar grid using a 5-point smoother (see sm5s)
"""
return sm5s(V)
def sm9v(V):
""" Smooth a scalar grid using a 9-point smoother (see sm9s)
"""
return sm9s(V)
def thrm(S, level1, level2, unit=None):
""" Thermal wind
<div class=jython>
THRM ( S ) = [ u (GEO(S)) (level1) - u (GEO(S)) (level2),
v (GEO(S)) (level1) - v (GEO(S)) (level2) ]
</div>
"""
return vldf(geo(S),level1,level2, unit)
def vadd(V1,V2):
""" add the components of 2 vectors
<div class=jython>
VADD (V1, V2) = [ u1+u2, v1+v2 ]
</div>
"""
return add(V1,V2)
def vecn(S1,S2):
""" Make a true north vector from two components
<div class=jython>
VECN ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return makeTrueVector(S1,S2)
def vecr(S1,S2):
""" Make a vector from two components
<div class=jython>
VECR ( S1, S2 ) = [ S1, S2 ]
</div>
"""
return makeVector(S1,S2)
def vlav(V,level1,level2, unit=None):
""" calculate the vector layer average
<div class=jython>
VLDF(V) = [(u(level1) - u(level2))/2,
(v(level1) - v(level2))/2]
</div>
"""
return layerAverage(V, level1, level2, unit)
def vldf(V,level1,level2, unit=None):
""" calculate the vector layer difference
<div class=jython>
VLDF(V) = [u(level1) - u(level2),
v(level1) - v(level2)]
</div>
"""
return layerDiff(V,level1,level2, unit)
def vmul(V1,V2):
""" Multiply the components of 2 vectors
<div class=jython>
VMUL (V1, V2) = [ u1*u2, v1*v2 ]
</div>
"""
return mul(V1,V2)
def vquo(V1,V2):
""" Divide the components of 2 vectors
<div class=jython>
VQUO (V1, V2) = [ u1/u2, v1/v2 ]
</div>
"""
return quo(V1,V2)
def vsub(V1,V2):
""" subtract the components of 2 vectors
<div class=jython>
VSUB (V1, V2) = [ u1-u2, v1-v2 ]
</div>
"""
return sub(V1,V2)
def LPIndex(u, v, z, t, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52
</div>
"""
Z = windShear(u, v, z, top, bottom, unit)*7.268
uwind = getSliceAtLevel(u, top)
vwind = getSliceAtLevel(v, top)
temp = newUnit(getSliceAtLevel(t, top), "temperature", "celsius")
HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718
HU = (ddx(vwind) + ddy(uwind))*0.318
L = add(noUnit(Z), add(noUnit(HU), noUnit(HT)))
L = (L - 2.520)*(-0.59)
P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,"exp"))
LP = setLevel(P ,top, unit)
return LP
def EllrodIndex(u, v, z, top, bottom, unit):
""" calculate the wind shear between discrete layers
<div class=jython>
EI = VWS X ( DEF + DIV)
</div>
"""
VWS = windShear(u, v, z, top, bottom, unit)*100.0
#
uwind = getSliceAtLevel(u, top)
vwind = getSliceAtLevel(v, top)
DIV = (ddx(uwind) + ddy(vwind))* (-1.0)
#
DSH = ddx(vwind) + ddy(uwind)
DST = ddx(uwind) - ddy(vwind)
DEF = sqrt(DSH * DSH + DST * DST)
EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV)))
return setLevel(EI, top, unit)
|
# 2019 advent day 3
MOVES = {
'R': (lambda x: (x[0], x[1] + 1)),
'L': (lambda x: (x[0], x[1] - 1)),
'U': (lambda x: (x[0] + 1, x[1])),
'D': (lambda x: (x[0] - 1, x[1])),
}
def build_route(directions: list) -> list:
current_location = (0, 0)
route = []
for d in directions:
direction, amount = d[0], int(d[1:])
for _ in range(amount):
current_location = MOVES[direction](current_location)
route.append(current_location)
return route
def find_intersections(r1: list, r2: list) -> set:
return set(r1).intersection(set(r2))
def find_shortest_manhattan_distance(points: set) -> int:
return min((abs(p[0]) + abs(p[1])) for p in points)
#R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'
#R2 = 'U62,R66,U55,R34,D71,R55,D58,R83'
#R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'
#R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'
def main():
#route1 = build_route(R1.split(','))
#route2 = build_route(R2.split(','))
with open('day3input.txt') as f:
line1, line2 = f.readlines()
route1 = build_route(line1.strip().split(','))
route2 = build_route(line2.strip().split(','))
print(find_shortest_manhattan_distance(find_intersections(route1, route2)))
if __name__ == "__main__":
main()
|
#Yannick p6e8 Escribe un programa que te pida primero un número y luego te pida números hasta que la suma de los números introducidos coincida con el número inicial. El programa termina escribiendo la lista de números.
limite = int(input("Escribe limite:"))
valores = int(input("Escribe un valor:"))
listavalores = []
listavalores.append(valores)
while limite > sum(listavalores):
valores = int(input("Escribe otro valor"))
listavalores.append(valores)
print(f"El limite a superar es {limite}. La lista creada es ", end="")
for i in range(len(listavalores)):
print (listavalores[i], end=" ")
print(f"ya que la suma de estos numeros es {sum(listavalores)}")
|
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[0][0]
elif i == 0:
dp[i][j] = grid[i][j] + dp[i][j - 1]
elif j == 0:
dp[i][j] = grid[i][j] + dp[i - 1][j]
else:
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m - 1][n - 1]
|
# -*- coding: utf-8 -*-
info = {
"name": "ebu",
"date_order": "DMY",
"january": [
"mweri wa mbere",
"mbe"
],
"february": [
"mweri wa kaĩri",
"kai"
],
"march": [
"mweri wa kathatũ",
"kat"
],
"april": [
"mweri wa kana",
"kan"
],
"may": [
"mweri wa gatano",
"gat"
],
"june": [
"mweri wa gatantatũ",
"gan"
],
"july": [
"mweri wa mũgwanja",
"mug"
],
"august": [
"mweri wa kanana",
"knn"
],
"september": [
"mweri wa kenda",
"ken"
],
"october": [
"mweri wa ikũmi",
"iku"
],
"november": [
"mweri wa ikũmi na ũmwe",
"imw"
],
"december": [
"mweri wa ikũmi na kaĩrĩ",
"igi"
],
"monday": [
"njumatatu",
"tat"
],
"tuesday": [
"njumaine",
"ine"
],
"wednesday": [
"njumatano",
"tan"
],
"thursday": [
"aramithi",
"arm"
],
"friday": [
"njumaa",
"maa"
],
"saturday": [
"njumamothii",
"nmm"
],
"sunday": [
"kiumia",
"kma"
],
"am": [
"ki"
],
"pm": [
"ut"
],
"year": [
"mwaka"
],
"month": [
"mweri"
],
"week": [
"kiumia"
],
"day": [
"mũthenya"
],
"hour": [
"ithaa"
],
"minute": [
"ndagĩka"
],
"second": [
"sekondi"
],
"relative-type": {
"1 year ago": [
"last year"
],
"0 year ago": [
"this year"
],
"in 1 year": [
"next year"
],
"1 month ago": [
"last month"
],
"0 month ago": [
"this month"
],
"in 1 month": [
"next month"
],
"1 week ago": [
"last week"
],
"0 week ago": [
"this week"
],
"in 1 week": [
"next week"
],
"1 day ago": [
"ĩgoro"
],
"0 day ago": [
"ũmũnthĩ"
],
"in 1 day": [
"rũciũ"
],
"0 hour ago": [
"this hour"
],
"0 minute ago": [
"this minute"
],
"0 second ago": [
"now"
]
},
"locale_specific": {},
"skip": [
" ",
".",
",",
";",
"-",
"/",
"'",
"|",
"@",
"[",
"]",
","
]
}
|
# See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite
good_table_names = [
'foo',
'123abc',
'123abc.txt',
'123abc-ABC.txt',
'foo""bar',
'😀',
'_sqlite',
]
# See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite
bad_table_names = [
'"',
'"foo"',
'sqlite_',
'sqlite_reserved',
]
|
# Apresentação
print('Programa para somar 8 valores utilizando vetores/listas')
print()
# Declaração do vetor
valores = [0, 0, 0, 0, 0, 0, 0, 0]
# Solicita os valores
for i in range(len(valores)):
valores[i] = int(input('Informe o valor: '))
# Cálculo da soma
soma = 0
for i in range(len(valores)):
soma += valores[i]
# Apresenta o resultado
print(f'A soma dos valores é {soma}')
|
budget = float(input())
nights = int(input())
price_night = float(input())
percent_extra = int(input())
if nights > 7:
price_night = price_night - (price_night * 0.05)
sum = nights * price_night
total_sum = sum + (budget * percent_extra / 100)
if total_sum <= budget:
print(f"Ivanovi will be left with {(budget - total_sum):.2f} leva after vacation.")
else:
print(f"{(total_sum - budget):.2f} leva needed.") |
root_URL = "https://tr.wiktionary.org/wiki/Vikis%C3%B6zl%C3%BCk:S%C3%B6zc%C3%BCk_listesi_"
filepath = "words.csv"
#letters=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O",
# "P","R","S","T","U","V","Y","Z"] ##İ,Ç,Ö,Ş,Ü harfleri not work correctly
letters=["C"] |
# 入力
N = int(input())
S, P = (
zip(*(
(s, int(p))
for s, p in (input().split() for _ in range(N))
)) if N else
((), ())
)
ans = '\n'.join(
str(i)
for _, _, i in sorted(
zip(
S,
P,
range(1, N + 1)
),
key=lambda t: (t[0], -t[1])
)
)
# 出力
print(ans)
|
class Skidoo(object):
''' a mapping which claims to contain all keys, each with a value
of 23; item setting and deletion are no-ops; you can also call
an instance with arbitrary positional args, result is 23. '''
__metaclass__ = MetaInterfaceChecker
__implements__ = IMinimalMapping, ICallable
def __getitem__(self, key): return 23
def __setitem__(self, key, value): pass
def __delitem__(self, key): pass
def __contains__(self, key): return True
def __call__(self, *args): return 23
sk = Skidoo()
|
# criar um programa que pergunte as dimensões de uma parede, calcule sua área e informe quantos litros de tinta
# seriam necessários para a pintura, após perguntar o rendimento da tinta informado na lata
print('=' * 40)
print('{:^40}'.format('Assistente de pintura'))
print('=' * 40)
altura = float(input('Informe a altura da parede em metros: '))
largura = float(input('Informe a largura da parede em metros: '))
area = altura * largura
print('\nA área total da parede é de {:.2f}m²'.format(area))
litros = float(input('\nQuantos litros contém a lata de tinta escolhida? '))
rendlata = float(input('Qual o rendimento em metros informado na lata? '))
rendlitro = rendlata / litros
print('\nSe a lata possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata))
print('então o rendimento por litro é de {:.2f}m²'.format(rendlitro))
print('\nSerão necessário {:.2f}L para pintar toda a parede'.format(area / rendlitro)) |
#!/usr/bin/env python
# coding: UTF-8
#
# @package Actor
# @author Ariadne Pinheiro
# @date 26/08/2020
#
# Actor class, which is the base class for Disease objects.
#
##
class Actor:
# Holds the value of the next "free" id.
__ID = 0
##
# Construct a new Actor object.
# - Sets the initial values of its member variables.
# - Sets the unique ID for the object and initializes the reference to the World
# object to which this Actor object belongs to null.
# - The ID of the first Actor object is 0.
# - The ID gets incremented by one each time a new Actor object is created.
# - Sets the iteration counter to zero and initialize the location of the
# object to cell (0,0).
#
def __init__(self):
# X coordinate of this actor.
self.__locX = 0
# Y coordinate of this actor.
self.__locY = 0
# World this actor belongs to.
self.__world = None
# Unique identifier for this actor.
self.__actorID = Actor.__ID
Actor.__ID += 1
# Iteration counter.
self.__itCounter = 0
##
# Used for testing
# @return ActorID
#
def getID(self):
return self.__actorID
##
# Used for testing
# @return number of iterations
#
def Iteration(self):
return self.__itCounter
##
# Prints on screen in the format "Iteration <ID>: Actor <Actor ID>".
#
# The @f$<ID>@f$ is replaced by the current iteration number. @f$<Actor ID>@f$ is
# replaced by the unique ID of the Actor object that performs the act(self)
# method.
#
# For instance, the actor with ID 1 shows the following result on
# the output screen after its act(self) method has been called twice.
# <PRE>
# Iteration 0: Actor 1
# Iteration 1: Actor 1
# </PRE>
#
def act(self):
print("Iteration {}: Actor {}".format(self.__itCounter, self.__actorID))
self.__itCounter += 1
##
# Sets the cell coordinates of this object.
#
# @param x the column.
# @param y the row.
#
# @throws ValueError when x < 0 or x >= world width,
# @throws ValueError when y < 0 or y >= world height,
# @throws RuntimeError when the world is null.
#
def setLocation(self, x, y):
if self.__world is None:
raise RuntimeError
if (0 <= x < self.__world.getWidth()) and (0 <= y < self.__world.getHeight()):
self.__locX = x
self.__locY = y
else:
raise ValueError
##
# Sets the world this actor is into.
#
# @param world Reference to the World object this Actor object is added.
# @throws RuntimeError when world is null.
#
def addedToWorld(self, world):
if world is None:
raise RuntimeError
self.__world = world
##
# Gets the world this object in into.
#
# @return the world this object belongs to
#
def getWorld(self):
return self.__world
##
# Gets the X coordinate of the cell this actor object is into.
#
# @return the x coordinate of this Actor object.
#
def getX(self):
return self.__locX
##
# Gets the Y coordinate of the cell this actor object is into.
#
# @return the y coordinate of this Actor object.
#
def getY(self):
return self.__locY
##
# Return a string with this actor ID and position.
#
def __str__(self):
try:
st = "ID = %d "u'\u2192 '.encode('utf-8') % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
except TypeError:
st = "ID = %d "u'\u2192 ' % self.getID()
st += 'position = (%d, %d)\n' % (self.getX(), self.getY())
return st
|
NAMES_SAML2_PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol"
NAMES_SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion"
NAMEID_FORMAT_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ"
|
class BaseSSO:
async def get_redirect_url(self):
"""Returns redirect url for facebook."""
raise NotImplementedError("Provider not implemented")
async def verify(self, request):
"""
Fetches user details using code received in the request.
:param request: starlette request object
"""
raise NotImplementedError("Provider not implemented")
|
def write(message: str):
print("org.allnix", message)
def read() -> str:
"""Returns a string"""
return "org.allnix"
|
groupSize = input()
groups = list(map(int,input().split(' ')))
tmpArray1 = set()
tmpArray2 = set()
for i in groups:
if i in tmpArray1:
tmpArray2.discard(i)
else:
tmpArray1.add(i)
tmpArray2.add(i)
for i in tmpArray2:
print(i)
|
#1) Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list.
# The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5).
def sublist(input_lst):
out_lst = list()
number = 0
i = 0
print(input_lst)
print(len(input_lst))
length = len(input_lst)
while i<length:
number = input_lst[i]
i+=1
if number==5: break
else : out_lst.append(number)
print(out_lst)
return out_lst
#2) Write a function called check_nums that takes a list as its parameter, and contains a while loop that only stops once the element of the
# list is the number 7. What is returned is a list of all of the numbers up until it reaches 7.def check_nums(input_lst):
def check_nums(input_lst):
out_lst = list()
number = 0
i = 0
print(input_lst)
print(len(input_lst))
length = len(input_lst)
while i<length:
number = input_lst[i]
i+=1
if number==7: break
else : out_lst.append(number)
print(out_lst)
return out_lst
#3) Write a function, sublist, that takes in a list of strings as the parameter. In the function, use a while loop to return a sublist of the input list.
# The sublist should contain the same values of the original list up until it reaches the string “STOP” (it should not contain the string “STOP”).
def sublist(in_lst):
out_list = list()
str = ""
i = 0
while str!="STOP":
str = in_lst[i]
i+=1
if str=="STOP": break
else: out_list.append(str)
return out_list
#4) Write a function called stop_at_z that iterates through a list of strings. Using a while loop, append each string to a new list until the string that
# appears is “z”. The function should return the new list.
def stop_at_z(in_lst):
out_list = list()
str = ""
i = 0
while str!="z":
str = in_lst[i]
i+=1
if str=="z": break
else: out_list.append(str)
return out_list
#5) Below is a for loop that works. Underneath the for loop, rewrite the problem so that it does the same thing, but using a while loop instead of a for loop.
# Assign the accumulated total in the while loop code to the variable sum2. Once complete, sum2 should equal sum1.
lst = [65, 78, 21, 33]
lenght = len(lst)
i = 0
sum2 = 0
while i<lenght:
sum2 += lst[i]
i+=1
#6) Challenge: Write a function called beginning that takes a list as input and contains a while loop that only stops once the element of the list is the string ‘bye’.
# What is returned is a list that contains up to the first 10 strings, regardless of where the loop stops. (i.e., if it stops on the 32nd element, the first 10 are
# returned. If “bye” is the 5th element, the first 4 are returned.) If you want to make this even more of a challenge, do this without slicing
def beginning(in_list):
length = len(in_list)
out_lst = list()
i = 0
str = ""
while i<length:
str = in_list[i]
i+=1
if str=="bye" or i>10:
break
out_lst.append(str)
return out_lst
|
#!/usr/bin/python3
#------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [(root, 0)]
result = []
while stack:
(node, level) = stack.pop(0)
if level == len(result):
result.append([])
result[level].append(node.val)
if node.left: stack.append((node.left, level+1))
if node.right: stack.append((node.right, level+1))
return result
#------------------------------------------------------------------------------
#Testing
|
"""
Your module description
"""
"""
this is my second py code
for my second lecture
"""
#print ('hello world') # this is a single line commment
# this is my second line comment
#print(type("123."))
#print ("Hello World".upper())
#print("Hello World".lower())
#print("hello" + "world" + ".")
#print(2**3)
#my_str = "hello world"
#print(my_str)
#my_str = "Tom"
#print(my_str)
my_int = 2
my_float = 3.0
print(my_int + my_float) |
class Calculations:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
print(self.first + self.second)
def subtract(self):
print(self.first - self.second)
def multiply(self):
print(self.first * self.second)
def divide(self):
if second == 0:
print("Can't divide by zero")
else:
print(self.first / self.second)
def main():
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop = 1
calc=Calculations(a, b)
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division "))
print(chooseop)
if chooseop == 1:
calc.add()
break
elif chooseop == 2:
calc.subtract()
break
elif chooseop == 3:
calc.multiply()
break
elif chooseop == 4:
calc.divide()
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print("Invalid operation number")
if __name__ == "__main__":
main()
|
n, k = map(int, input().split())
w = list(map(int, input().split()))
r = sum(map(lambda x: (x+k-1)//k, w))
print((r+1)//2)
|
# -*- coding: utf-8 -*-
def main():
a = input()
# See:
# https://www.slideshare.net/chokudai/abc007
if a == 'a':
print('-1')
else:
print('a')
if __name__ == '__main__':
main()
|
class Constants(object):
LOGGER_CONF = "common/mapr_conf/logger.yml"
USERNAME = "mapr"
GROUPNAME = "mapr"
USERID = 5000
GROUPID = 5000
ADMIN_USERNAME = "custadmin"
ADMIN_GROUPNAME = "custadmin"
ADMIN_USERID = 7000
ADMIN_GROUPID = 7000
ADMIN_PASS = "mapr"
MYSQL_USER = "admin"
MYSQL_PASS = "mapr"
LDAPADMIN_USER = "admin"
LDAPADMIN_PASS = "mapr"
LDAPBIND_USER = "readonly"
LDAPBIND_PASS = "mapr"
EXAMPLE_LDAP_NAMESPACE = "hpe-ldap"
CSI_REPO = "quay.io/k8scsi"
KDF_REPO = "docker.io/maprtech" #registry.hub.docker.com/maprtech
KUBEFLOW_REPO = "gcr.io/mapr-252711/kf-ecp-5.3.0"
OPERATOR_REPO = "gcr.io/mapr-252711"
KUBELET_DIR = "/var/lib/kubelet"
ECP_KUBELET_DIR = "/var/lib/docker/kubelet"
LOCAL_PATH_PROVISIONER_REPO= ""
KFCTL_HSP_ISTIO_REPO = ""
BUSYBOX_REPO = ""
def enum(**named_values):
return type('Enum', (), named_values)
AUTH_TYPES = enum(CUSTOM_LDAP='customLDAP', RAW_LINUX_USERS='rawLinuxUsers', EXAMPLE_LDAP='exampleLDAP')
# OPEN SSL
OPENSSL = '/usr/bin/openssl'
KEY_SIZE = 1024
DAYS = 3650
CA_CERT = 'ca.cert'
CA_KEY = 'ca.key'
# http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS
X509_EXTRA_ARGS = ()
OPENSSL_CONFIG_TEMPLATE = """
prompt = no
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
C = US
ST = CO
L = Fort Collins
O = HPE
OU = HCP
CN = %(service)s
emailAddress = support@hpe.com
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = %(service)s
DNS.2 = %(service)s.%(namespace)s
DNS.3 = %(service)s.%(namespace)s.svc
"""
|
# 6. Специални числа
# Да се напише програма, която чете едно цяло число N, въведено от потребителя, и генерира всички възможни "специални"
# числа от 1111 до 9999. За да бъде “специално” едно число, то трябва да отговаря на следното условие:
# • N да се дели на всяка една от неговите цифри без остатък.
# Пример: при N = 16, 2418 е специално число:
# • 16 / 2 = 8 без остатък
# • 16 / 4 = 4 без остатък
# • 16 / 1 = 16 без остатък
# • 16 / 8 = 2 без остатък
N = int(input())
for number in range(1111, 9999 + 1):
is_number_special = True
number_as_string = str(number)
# Could also write for index, digit in enumerate(number_as_string): but since we don't need the index we don't need enumerate.
for digit in number_as_string:
if int(digit) == 0 or N % int(digit) != 0:
is_number_special = False
break
if is_number_special:
print(f'{number_as_string}', end = ' ')
|
# input
N, M = map(int, input().split())
Ds = [*map(int, input().split())]
# compute
dp = [False] * (N+1)
for ni in range(N+1):
if ni == 0:
dp[ni] = True
for D in Ds:
if ni >= D:
dp[ni] = dp[ni] or dp[ni-D]
# output
print("Yes" if dp[-1] else "No")
|
# sorting
n=int(input())
array=list(map(int,input().split()))
i=0
count=[]
counter=0
while i<len(array):
min=i
start=i+1
while(start<len(array)):
if array[start]<array[min]:
min=start
start+=1
if i!=min:
array[i],array[min]=array[min],array[i]
count.append(i)
count.append(min)
counter+=1
i+=1
print(counter)
for i in range(0,len(count)):
print(count[i],end=" ")
|
class GeomCombinationSet(APIObject, IDisposable, IEnumerable):
"""
A set that contains GeomCombination objects.
GeomCombinationSet()
"""
def Clear(self):
"""
Clear(self: GeomCombinationSet)
Removes every item GeomCombination the set,rendering it empty.
"""
pass
def Contains(self, item):
"""
Contains(self: GeomCombinationSet,item: GeomCombination) -> bool
Tests for the existence of an GeomCombination within the set.
item: The element to be searched for.
Returns: The Contains method returns True if the GeomCombination is within the set,
otherwise False.
"""
pass
def Dispose(self):
""" Dispose(self: GeomCombinationSet,A_0: bool) """
pass
def Erase(self, item):
"""
Erase(self: GeomCombinationSet,item: GeomCombination) -> int
Removes a specified GeomCombination from the set.
item: The GeomCombination to be erased.
Returns: The number of GeomCombinations that were erased from the set.
"""
pass
def ForwardIterator(self):
"""
ForwardIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def GetEnumerator(self):
"""
GetEnumerator(self: GeomCombinationSet) -> IEnumerator
Retrieve a forward moving iterator to the set.
Returns: Returns a forward moving iterator to the set.
"""
pass
def Insert(self, item):
"""
Insert(self: GeomCombinationSet,item: GeomCombination) -> bool
Insert the specified element into the set.
item: The GeomCombination to be inserted into the set.
Returns: Returns whether the GeomCombination was inserted into the set.
"""
pass
def ReleaseManagedResources(self, *args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: GeomCombinationSet) """
pass
def ReverseIterator(self):
"""
ReverseIterator(self: GeomCombinationSet) -> GeomCombinationSetIterator
Retrieve a backward moving iterator to the set.
Returns: Returns a backward moving iterator to the set.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self, *args):
""" __iter__(self: IEnumerable) -> object """
pass
IsEmpty = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Test to see if the set is empty.
Get: IsEmpty(self: GeomCombinationSet) -> bool
"""
Size = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Returns the number of GeomCombinations that are in the set.
Get: Size(self: GeomCombinationSet) -> int
"""
|
#Basics
a = "hello"
a += " I'm a dog"
print(a)
print(len(a))
print(a[1:]) #Output: ello I'm a dog
print(a[:5]) #Output: hello(index 5 is not included)
print(a[2:5])#Output: llo(index 2 is included)
print(a[::2])#Step size
#string is immutable so you can't assign a[1]= b
x = a.upper()
print(x)
x = a.capitalize()
print(x)
x = a.split('e')
print(x)
x = a.split() #splits the string by space
print(x)
x = a.strip() #removes any whitespace from beginning or the end
print(x)
x = a.replace('l','xxx')
print(x)
x = "Insert another string here: {}".format('insert me!')
x = "Item One: {} Item Two: {}".format('dog', 'cat')
print(x)
x = "Item One: {m} Item Two: {m}".format(m='dog', n='cat')
print(x)
#command-line string input
print("Enter your name:")
x = input()
print("Hello: {}".format(x)) |
#Copyright (c) 2017 Andre Santos
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
###############################################################################
# Language Model
###############################################################################
class CodeEntity(object):
"""Base class for all programming entities.
All code objects have a file name, a line number, a column number,
a programming scope (e.g. the function or code block they belong to)
and a parent object that should have some variable or collection
holding this object.
"""
def __init__(self, scope, parent):
"""Base constructor for code objects.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
self.scope = scope
self.parent = parent
self.file = None
self.line = None
self.column = None
def walk_preorder(self):
"""Iterates the program tree starting from this object, going down."""
yield self
for child in self._children():
for descendant in child.walk_preorder():
yield descendant
def filter(self, cls, recursive=False):
"""Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree.
"""
source = self.walk_preorder if recursive else self._children
return [
codeobj
for codeobj in source()
if isinstance(codeobj, cls)
]
def _afterpass(self):
"""Finalizes the construction of a code entity."""
pass
def _validity_check(self):
"""Check whether this object is a valid construct."""
return True
def _children(self):
"""Yield all direct children of this object."""
# The default implementation has no children, and thus should return
# an empty iterator.
return iter(())
def _lookup_parent(self, cls):
"""Lookup a transitive parent object that is an instance
of a given class."""
codeobj = self.parent
while codeobj is not None and not isinstance(codeobj, cls):
codeobj = codeobj.parent
return codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return (' ' * indent) + self.__str__()
def ast_str(self, indent=0):
"""Return a minimal string to print a tree-like structure.
Kwargs:
indent (int): The number of indentation levels.
"""
line = self.line or 0
col = self.column or 0
name = type(self).__name__
spell = getattr(self, 'name', '[no spelling]')
result = ' ({})'.format(self.result) if hasattr(self, 'result') else ''
prefix = indent * '| '
return '{}[{}:{}] {}{}: {}'.format(prefix, line, col,
name, result, spell)
def __str__(self):
"""Return a string representation of this object."""
return self.__repr__()
def __repr__(self):
"""Return a string representation of this object."""
return '[unknown]'
class CodeStatementGroup(object):
"""This class is meant to provide common utility methods for
objects that group multiple program statements together
(e.g. functions, code blocks).
It is not meant to be instantiated directly, only used for
inheritance purposes.
It defines the length of a statement group, and provides methods
for integer-based indexing of program statements (as if using a list).
"""
def statement(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.body.statement(i)
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
try:
return self.statement(i + 1)
except IndexError as e:
return None
def __getitem__(self, i):
"""Return the *i*-th statement from the object's `body`."""
return self.statement(i)
def __len__(self):
"""Return the length of the statement group."""
return len(self.body)
# ----- Common Entities -------------------------------------------------------
class CodeVariable(CodeEntity):
"""This class represents a program variable.
A variable typically has a name, a type (`result`) and a value
(or `None` for variables without a value or when the value is unknown).
Additionally, a variable has an `id` which uniquely identifies it in
the program (useful to resolve references), a list of references to it
and a list of statements that write new values to the variable.
If the variable is a *member*/*field*/*attribute* of an object,
`member_of` should contain a reference to such object, instead of `None`.
"""
def __init__(self, scope, parent, id, name, result):
"""Constructor for variables.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this variable.
name (str): The name of the variable in the program.
result (str): The type of the variable in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.value = None
self.member_of = None
self.references = []
self.writes = []
@property
def is_definition(self):
return True
@property
def is_local(self):
"""Whether this is a local variable.
In general, a variable is *local* if its containing scope is a
statement (e.g. a block), or a function, given that the variable
is not one of the function's parameters.
"""
return (isinstance(self.scope, CodeStatement)
or (isinstance(self.scope, CodeFunction)
and self not in self.scope.parameters))
@property
def is_global(self):
"""Whether this is a global variable.
In general, a variable is *global* if it is declared directly under
the program's global scope or a namespace.
"""
return isinstance(self.scope, (CodeGlobalScope, CodeNamespace))
@property
def is_parameter(self):
"""Whether this is a function parameter."""
return (isinstance(self.scope, CodeFunction)
and self in self.scope.parameters)
@property
def is_member(self):
"""Whether this is a member/attribute of a class or object."""
return isinstance(self.scope, CodeClass)
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeEntity):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '{}{} {} = {}'.format(' ' * indent, self.result, self.name,
pretty_str(self.value))
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {} = ({})'.format(self.result, self.name, self.value)
class CodeFunction(CodeEntity, CodeStatementGroup):
"""This class represents a program function.
A function typically has a name, a return type (`result`), a list
of parameters and a body (a code block). It also has an unique `id`
that identifies it in the program and a list of references to it.
If a function is a method of some class, its `member_of` should be
set to the corresponding class.
"""
def __init__(self, scope, parent, id, name, result, definition=True):
"""Constructor for functions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this function.
name (str): The name of the function in the program.
result (str): The return type of the function in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.parameters = []
self.body = CodeBlock(self, self, explicit=True)
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a function definition or just a declaration."""
return self._definition is self
@property
def is_constructor(self):
"""Whether this function is a class constructor."""
return self.member_of is not None
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, (CodeStatement, CodeExpression))
self.body._add(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.parameters:
yield codeobj
for codeobj in self.body._children():
yield codeobj
def _afterpass(self):
"""Assign a function-local index to each child object and register
write operations to variables.
This should only be called after the object is fully built.
"""
if hasattr(self, '_fi'):
return
fi = 0
for codeobj in self.walk_preorder():
codeobj._fi = fi
fi += 1
if isinstance(codeobj, CodeOperator) and codeobj.is_assignment:
if codeobj.arguments and isinstance(codeobj.arguments[0],
CodeReference):
var = codeobj.arguments[0].reference
if isinstance(var, CodeVariable):
var.writes.append(codeobj)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
params = ', '.join(map(lambda p: p.result + ' ' + p.name,
self.parameters))
if self.is_constructor:
pretty = '{}{}({}):\n'.format(spaces, self.name, params)
else:
pretty = '{}{} {}({}):\n'.format(spaces, self.result,
self.name, params)
if self._definition is not self:
pretty += spaces + ' [declaration]'
else:
pretty += self.body.pretty_str(indent + 2)
return pretty
def __repr__(self):
"""Return a string representation of this object."""
params = ', '.join(map(str, self.parameters))
return '[{}] {}({})'.format(self.result, self.name, params)
class CodeClass(CodeEntity):
"""This class represents a program class for object-oriented languages.
A class typically has a name, an unique `id`, a list of
members (variables, functions), a list of superclasses, and a list of
references.
If a class is defined within another class (inner class), it should
have its `member_of` set to the corresponding class.
"""
def __init__(self, scope, parent, id_, name, definition=True):
"""Constructor for classes.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this class.
name (str): The name of the class in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.id = id_
self.name = name
self.members = []
self.superclasses = []
self.member_of = None
self.references = []
self._definition = self if definition else None
@property
def is_definition(self):
"""Whether this is a definition or a declaration of the class."""
return self._definition is self
def _add(self, codeobj):
"""Add a child (function, variable, class) to this object."""
assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass))
self.members.append(codeobj)
codeobj.member_of = self
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.members:
yield codeobj
def _afterpass(self):
"""Assign the `member_of` of child members and call
their `_afterpass()`.
This should only be called after the object is fully built.
"""
for codeobj in self.members:
if not codeobj.is_definition:
if not codeobj._definition is None:
codeobj._definition.member_of = self
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'class ' + self.name
if self.superclasses:
superclasses = ', '.join(self.superclasses)
pretty += '(' + superclasses + ')'
pretty += ':\n'
if self.members:
pretty += '\n\n'.join(
c.pretty_str(indent + 2)
for c in self.members
)
else:
pretty += spaces + ' [declaration]'
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[class {}]'.format(self.name)
class CodeNamespace(CodeEntity):
"""This class represents a program namespace.
A namespace is a concept that is explicit in languages such as C++,
but less explicit in many others. In Python, the closest thing should
be a module. In Java, it may be the same as a class, or non-existent.
A namespace typically has a name and a list of children objects
(variables, functions or classes).
"""
def __init__(self, scope, parent, name):
"""Constructor for namespaces.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the namespace in the program.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass,
CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}namespace {}:\n'.format(spaces, self.name)
pretty += '\n\n'.join(c.pretty_str(indent + 2) for c in self.children)
return pretty
def __repr__(self):
"""Return a string representation of this object."""
return '[namespace {}]'.format(self.name)
class CodeGlobalScope(CodeEntity):
"""This class represents the global scope of a program.
The global scope is the root object of a program. If there are no
better candidates, it is the `scope` and `parent` of all other objects.
It is also the only object that does not have a `scope` or `parent`.
"""
def __init__(self):
"""Constructor for global scope objects."""
CodeEntity.__init__(self, None, None)
self.children = []
def _add(self, codeobj):
"""Add a child (namespace, function, variable, class) to this object."""
assert isinstance(codeobj, (CodeNamespace, CodeClass,
CodeFunction, CodeVariable))
self.children.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.children:
yield codeobj
def _afterpass(self):
"""Call the `_afterpass()` of child objects.
This should only be called after the object is fully built.
"""
for codeobj in self.children:
codeobj._afterpass()
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '\n\n'.join(
codeobj.pretty_str(indent=indent)
for codeobj in self.children
)
# ----- Expression Entities ---------------------------------------------------
class CodeExpression(CodeEntity):
"""Base class for expressions within a program.
Expressions can be of many types, including literal values,
operators, references and function calls. This class is meant
to be inherited from, and not instantiated directly.
An expression typically has a name (e.g. the name of the function
in a function call) and a type (`result`). Also, an expression should
indicate whether it is enclosed in parentheses.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for expressions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the expression in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeEntity.__init__(self, scope, parent)
self.name = name
self.result = result
self.parenthesis = paren
@property
def function(self):
"""The function where this expression occurs."""
return self._lookup_parent(CodeFunction)
@property
def statement(self):
"""The statement where this expression occurs."""
return self._lookup_parent(CodeStatement)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return (' ' * indent) + '(' + self.name + ')'
return (' ' * indent) + self.name
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {}'.format(self.result, self.name)
class SomeValue(CodeExpression):
"""This class represents an unknown value for diverse primitive types."""
def __init__(self, result):
"""Constructor for unknown values."""
CodeExpression.__init__(self, None, None, result, result)
def _children(self):
"""Yield all the children of this object, that is no children."""
return iter(())
SomeValue.INTEGER = SomeValue("int")
SomeValue.FLOATING = SomeValue("float")
SomeValue.CHARACTER = SomeValue("char")
SomeValue.STRING = SomeValue("string")
SomeValue.BOOL = SomeValue("bool")
class CodeLiteral(CodeExpression):
"""Base class for literal types not present in Python.
This class is meant to represent a literal whose type is not numeric,
string or boolean, as bare Python literals are used for those.
A literal has a value (e.g. a list `[1, 2, 3]`) and a type (`result`),
and could be enclosed in parentheses. It does not have a name.
"""
def __init__(self, scope, parent, value, result, paren=False):
"""Constructor for literals.
As literals have no name, a constant string is used instead.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (CodeExpression|CodeExpression[]): This literal's value.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, 'literal', result, paren)
self.value = value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.parenthesis:
return '{}({})'.format(' ' * indent, pretty_str(self.value))
return pretty_str(self.value, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {!r}'.format(self.result, self.value)
CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue,
CodeLiteral, CodeExpression)
CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral)
class CodeNull(CodeLiteral):
"""This class represents an indefinite value.
Many programming languages have their own version of this concept:
Java has null references, C/C++ NULL pointers, Python None and so on.
"""
def __init__(self, scope, parent, paren=False):
"""Constructor for null literals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
paren (bool): Whether the null literal is enclosed in parentheses.
"""
CodeLiteral.__init__(self, scope, parent, None, 'null', paren)
def _children(self):
"""Yield all the children of this object, that is no children.
This class inherits from CodeLiteral just for consistency with the
class hierarchy. It should have no children, thus an empty iterator
is returned.
"""
return iter(())
class CodeCompositeLiteral(CodeLiteral):
"""This class represents a composite literal.
A composite literal is any type of literal whose value is compound,
rather than simple. An example present in many programming languages
are list literals, often constructed as `[1, 2, 3]`.
A composite literal has a sequence of values that compose it
(`values`), a type (`result`), and it should indicate whether it is
enclosed in parentheses.
"""
def __init__(self, scope, parent, result, value=(), paren=False):
"""Constructor for a compound literal.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
value (iterable): The initial value sequence in this composition.
result (str): The return type of the literal in the program.
Kwargs:
paren (bool): Whether the literal is enclosed in parentheses.
"""
try:
value = list(value)
except TypeError as te:
raise AssertionError(str(te))
CodeLiteral.__init__(self, scope, parent, value, result, paren)
@property
def values(self):
return tuple(self.value)
def _add_value(self, child):
"""Add a value to the sequence in this composition."""
self.value.append(child)
def _children(self):
"""Yield all direct children of this object."""
for value in self.value:
if isinstance(value, CodeEntity):
yield value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
values = '{{{}}}'.format(', '.join(map(pretty_str, self.value)))
if self.parenthesis:
return '{}({})'.format(indent, values)
return '{}{}'.format(indent, values)
def __repr__(self):
"""Return a string representation of this object."""
return '[{}] {{{}}}'.format(self.result,
', '.join(map(repr, self.value)))
class CodeReference(CodeExpression):
"""This class represents a reference expression (e.g. to a variable).
A reference typically has a name (of what it is referencing),
and a return type.
If the referenced entity is known, `reference` should be set.
If the reference is a field/attribute of an object, `field_of`
should be set to that object.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for references.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the reference in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the reference is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.field_of = None
self.reference = None
def _set_field(self, codeobj):
"""Set the object that contains the attribute this is a reference of."""
assert isinstance(codeobj, CodeExpression)
self.field_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.field_of:
yield self.field_of
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
name = ('{}.{}'.format(self.field_of.pretty_str(), self.name)
if self.field_of else self.name)
return pretty.format(spaces, name)
def __str__(self):
"""Return a string representation of this object."""
return '#' + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.field_of:
return '[{}] ({}).{}'.format(self.result, self.field_of, self.name)
return '[{}] #{}'.format(self.result, self.name)
class CodeOperator(CodeExpression):
"""This class represents an operator expression (e.g. `a + b`).
Operators can be unary or binary, and often return numbers
or booleans. Some languages also support ternary operators.
Do note that assignments are often considered expressions,
and, as such, assignment operators are included here.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
_UNARY_TOKENS = ("+", "-")
_BINARY_TOKENS = ("+", "-", "*", "/", "%", "<", ">", "<=", ">=",
"==", "!=", "&&", "||", "=")
def __init__(self, scope, parent, name, result, args=None, paren=False):
"""Constructor for operators.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the operator in the program.
result (str): The return type of the operator in the program.
Kwargs:
args (tuple): Initial tuple of arguments.
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.arguments = args or ()
@property
def is_unary(self):
"""Whether this is a unary operator."""
return len(self.arguments) == 1
@property
def is_binary(self):
"""Whether this is a binary operator."""
return len(self.arguments) == 2
@property
def is_ternary(self):
"""Whether this is a ternary operator."""
return len(self.arguments) == 3
@property
def is_assignment(self):
"""Whether this is an assignment operator."""
return self.name == "="
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
if self.is_unary:
operator = self.name + pretty_str(self.arguments[0])
else:
operator = '{} {} {}'.format(pretty_str(self.arguments[0]),
self.name,
pretty_str(self.arguments[1]))
return pretty.format(indent, operator)
def __repr__(self):
"""Return a string representation of this object."""
if self.is_unary:
return '[{}] {}({})'.format(self.result, self.name,
self.arguments[0])
if self.is_binary:
return '[{}] ({}){}({})'.format(self.result, self.arguments[0],
self.name, self.arguments[1])
return '[{}] {}'.format(self.result, self.name)
class CodeFunctionCall(CodeExpression):
"""This class represents a function call.
A function call typically has a name (of the called function),
a return type, a tuple of its arguments and a reference to the
called function.
If a call references a class method, its `method_of` should be
set to the object on which a method is being called.
"""
def __init__(self, scope, parent, name, result, paren=False):
"""Constructor for function calls.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the function in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.
"""
CodeExpression.__init__(self, scope, parent, name, result, paren)
self.full_name = name
self.arguments = ()
self.method_of = None
self.reference = None
@property
def is_constructor(self):
"""Whether the called function is a constructor."""
return self.result == self.name
def _add(self, codeobj):
"""Add a child (argument) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.arguments = self.arguments + (codeobj,)
def _set_method(self, codeobj):
"""Set the object on which a method is called."""
assert isinstance(codeobj, CodeExpression)
self.method_of = codeobj
def _children(self):
"""Yield all direct children of this object."""
if self.method_of:
yield self.method_of
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
pretty = '{}({})' if self.parenthesis else '{}{}'
args = ', '.join(map(pretty_str, self.arguments))
if self.method_of:
call = '{}.{}({})'.format(self.method_of.pretty_str(),
self.name, args)
elif self.is_constructor:
call = 'new {}({})'.format(self.name, args)
else:
call = '{}({})'.format(self.name, args)
return pretty.format(indent, call)
def __repr__(self):
"""Return a string representation of this object."""
args = ', '.join(map(str, self.arguments))
if self.is_constructor:
return '[{}] new {}({})'.format(self.result, self.name, args)
if self.method_of:
return '[{}] {}.{}({})'.format(self.result, self.method_of.name,
self.name, args)
return '[{}] {}({})'.format(self.result, self.name, args)
class CodeDefaultArgument(CodeExpression):
"""This class represents a default argument.
Some languages, such as C++, allow function parameters to have
default values when not explicitly provided by the programmer.
This class represents such omitted arguments.
A default argument has only a return type.
"""
def __init__(self, scope, parent, result):
"""Constructor for default arguments.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
result (str): The return type of the argument in the program.
"""
CodeExpression.__init__(self, scope, parent, '(default)', result)
# ----- Statement Entities ----------------------------------------------------
class CodeStatement(CodeEntity):
"""Base class for program statements.
Programming languages often define diverse types of statements
(e.g. return statements, control flow, etc.).
This class provides common functionality for such statements.
In many languages, statements must be contained within a function.
An operator typically has a name (its token), a return type,
and a tuple of its arguments.
"""
def __init__(self, scope, parent):
"""Constructor for statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeEntity.__init__(self, scope, parent)
self._si = -1
@property
def function(self):
"""The function where this statement appears in."""
return self._lookup_parent(CodeFunction)
class CodeJumpStatement(CodeStatement):
"""This class represents a jump statement (e.g. `return`, `break`).
A jump statement has a name. In some cases, it may also have an
associated value (e.g. `return 0`).
"""
def __init__(self, scope, parent, name):
"""Constructor for jump statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.value = None
def _add(self, codeobj):
"""Add a child (value) to this object."""
assert isinstance(codeobj, CodeExpression.TYPES)
self.value = codeobj
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.value, CodeExpression):
yield self.value
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
indent = ' ' * indent
if self.value is not None:
return '{}{} {}'.format(indent, self.name, pretty_str(self.value))
return indent + self.name
def __repr__(self):
"""Return a string representation of this object."""
if self.value is not None:
return '{} {}'.format(self.name, str(self.value))
return self.name
class CodeExpressionStatement(CodeStatement):
"""This class represents an expression statement. It is only a wrapper.
Many programming languages allow expressions to be statements
on their own. A common example is the assignment operator, which
can be a statement on its own, but also returns a value when
contained within a larger expression.
"""
def __init__(self, scope, parent, expression=None):
"""Constructor for expression statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
expression (CodeExpression): The expression of this statement.
"""
CodeStatement.__init__(self, scope, parent)
self.expression = expression
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.expression, CodeExpression):
yield self.expression
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return pretty_str(self.expression, indent=indent)
def __repr__(self):
"""Return a string representation of this object."""
return repr(self.expression)
class CodeBlock(CodeStatement, CodeStatementGroup):
"""This class represents a code block (e.g. `{}` in C, C++, Java, etc.).
Blocks are little more than collections of statements, while being
considered a statement themselves.
Some languages allow blocks to be implicit in some contexts, e.g.
an `if` statement omitting curly braces in C, C++, Java, etc.
This model assumes that control flow branches and functions always
have a block as their body.
"""
def __init__(self, scope, parent, explicit=True):
"""Constructor for code blocks.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
Kwargs:
explicit (bool): Whether the block is explicit in the code.
"""
CodeStatement.__init__(self, scope, parent)
self.body = []
self.explicit = explicit
def statement(self, i):
"""Return the *i*-th statement of this block."""
return self.body[i]
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, CodeStatement)
codeobj._si = len(self.body)
self.body.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.body:
return '\n'.join(stmt.pretty_str(indent) for stmt in self.body)
else:
return (' ' * indent) + '[empty]'
def __repr__(self):
"""Return a string representation of this object."""
return str(self.body)
class CodeDeclaration(CodeStatement):
"""This class represents a declaration statement.
Some languages, such as C, C++ or Java, consider this special
kind of statement for declaring variables within a function,
for instance.
A declaration statement contains a list of all declared variables.
"""
def __init__(self, scope, parent):
"""Constructor for declaration statements.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.variables = []
def _add(self, codeobj):
"""Add a child (variable) to this object."""
assert isinstance(codeobj, CodeVariable)
self.variables.append(codeobj)
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.variables:
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
return spaces + ', '.join(v.pretty_str() for v in self.variables)
def __repr__(self):
"""Return a string representation of this object."""
return str(self.variables)
class CodeControlFlow(CodeStatement, CodeStatementGroup):
"""Base class for control flow structures (e.g. `for` loops).
Control flow statements are assumed to have, at least, one branch
(a boolean condition and a `CodeBlock` that is executed when
the condition is met). Specific implementations may consider
more branches, or default branches (executed when no condition is met).
A control flow statement typically has a name.
"""
def __init__(self, scope, parent, name):
"""Constructor for control flow structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the control flow statement in the program.
"""
CodeStatement.__init__(self, scope, parent)
self.name = name
self.condition = True
self.body = CodeBlock(scope, self, explicit=False)
def get_branches(self):
"""Return a list of branches, where each branch is a pair of
condition and respective body."""
return [(self.condition, self.body)]
def _set_condition(self, condition):
"""Set the condition for this control flow structure."""
assert isinstance(condition, CodeExpression.TYPES)
self.condition = condition
def _set_body(self, body):
"""Set the main body for this control flow structure."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.body = body
else:
self.body._add(body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return '{} {}'.format(self.name, self.get_branches())
class CodeConditional(CodeControlFlow):
"""This class represents a conditional (`if`).
A conditional is allowed to have a default branch (the `else` branch),
besides its mandatory one.
"""
def __init__(self, scope, parent):
"""Constructor for conditionals.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, 'if')
self.else_body = CodeBlock(scope, self, explicit=False)
@property
def then_branch(self):
"""The branch associated with a condition."""
return self.condition, self.body
@property
def else_branch(self):
"""The default branch of the conditional."""
return True, self.else_body
def statement(self, i):
"""Return the *i*-th statement of this block.
Behaves as if the *then* and *else* branches were
concatenated, for indexing purposes.
"""
# ----- This code is just to avoid creating a new list and
# returning a custom exception message.
o = len(self.body)
n = o + len(self.else_body)
if i >= 0 and i < n:
if i < o:
return self.body.statement(i)
return self.else_body.statement(i - o)
elif i < 0 and i >= -n:
if i >= o - n:
return self.else_body.statement(i)
return self.body.statement(i - o + n)
raise IndexError('statement index out of range')
def statement_after(self, i):
"""Return the statement after the *i*-th one, or `None`."""
k = i + 1
o = len(self.body)
n = o + len(self.else_body)
if k > 0:
if k < o:
return self.body.statement(k)
if k > o and k < n:
return self.else_body.statement(k)
if k < 0:
if k < o - n and k > -n:
return self.body.statement(k)
if k > o - n:
return self.else_body.statement(k)
return None
def get_branches(self):
"""Return a list with the conditional branch and the default branch."""
if self.else_branch:
return [self.then_branch, self.else_branch]
return [self.then_branch]
def _add_default_branch(self, body):
"""Add a default body for this conditional (the `else` branch)."""
assert isinstance(body, CodeStatement)
if isinstance(body, CodeBlock):
self.else_body = body
else:
self.else_body._add(body)
def __len__(self):
"""Return the length of both branches combined."""
return len(self.body) + len(self.else_body)
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
for codeobj in self.else_body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}if ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
if self.else_body:
pretty += '\n{}else:\n'.format(spaces)
pretty += self.else_body.pretty_str(indent=indent + 2)
return pretty
class CodeLoop(CodeControlFlow):
"""This class represents a loop (e.g. `while`, `for`).
Some languages allow loops to define local declarations, as well
as an increment statement.
A loop has only a single branch, its condition plus the body
that should be repeated while the condition holds.
"""
def __init__(self, scope, parent, name):
"""Constructor for loops.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the loop statement in the program.
"""
CodeControlFlow.__init__(self, scope, parent, name)
self.declarations = None
self.increment = None
def _set_declarations(self, declarations):
"""Set declarations local to this loop (e.g. `for` variables)."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_increment(self, statement):
"""Set the increment statement for this loop (e.g. in a `for`)."""
assert isinstance(statement, CodeStatement)
self.increment = statement
statement.scope = self.body
def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.body._children():
yield codeobj
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
v = self.declarations.pretty_str() if self.declarations else ''
i = self.increment.pretty_str(indent=1) if self.increment else ''
pretty = '{}for ({}; {}; {}):\n'.format(spaces, v, condition, i)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class CodeSwitch(CodeControlFlow):
"""This class represents a switch statement.
A switch evaluates a value (its `condition`) and then declares
at least one branch (*cases*) that execute when the evaluated value
is equal to the branch value. It may also have a default branch.
Switches are often one of the most complex constructs of programming
languages, so this implementation might be lackluster.
"""
def __init__(self, scope, parent):
"""Constructor for switches.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeControlFlow.__init__(self, scope, parent, "switch")
self.cases = []
self.default_case = None
def _add_branch(self, value, statement):
"""Add a branch/case (value and statement) to this switch."""
self.cases.append((value, statement))
def _add_default_branch(self, statement):
"""Add a default branch to this switch."""
self.default_case = statement
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
condition = pretty_str(self.condition)
pretty = '{}switch ({}):\n'.format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
return pretty
class CodeTryBlock(CodeStatement, CodeStatementGroup):
"""This class represents a try-catch block statement.
`try` blocks have a main body of statements, just like regular blocks.
Multiple `catch` blocks may be defined to handle specific types of
exceptions.
Some languages also allow a `finally` block that is executed after
the other blocks (either the `try` block, or a `catch` block, when
an exception is raised and handled).
"""
def __init__(self, scope, parent):
"""Constructor for try block structures.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
"""
CodeStatement.__init__(self, scope, parent)
self.body = CodeBlock(scope, self, explicit=True)
self.catches = []
self.finally_body = CodeBlock(scope, self, explicit=True)
def _set_body(self, body):
"""Set the main body for try block structure."""
assert isinstance(body, CodeBlock)
self.body = body
def _add_catch(self, catch_block):
"""Add a catch block (exception variable declaration and block)
to this try block structure.
"""
assert isinstance(catch_block, self.CodeCatchBlock)
self.catches.append(catch_block)
def _set_finally_body(self, body):
"""Set the finally body for try block structure."""
assert isinstance(body, CodeBlock)
self.finally_body = body
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.body._children():
yield codeobj
for catch_block in self.catches:
for codeobj in catch_block._children():
yield codeobj
for codeobj in self.finally_body._children():
yield codeobj
def __len__(self):
"""Return the length of all blocks combined."""
n = len(self.body) + len(self.catches) + len(self.finally_body)
n += sum(map(len, self.catches))
return n
def __repr__(self):
"""Return a string representation of this object."""
return 'try {} {} {}'.format(self.body, self.catches,
self.finally_body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'try:\n'
pretty += self.body.pretty_str(indent=indent + 2)
for block in self.catches:
pretty += '\n' + block.pretty_str(indent)
if len(self.finally_body) > 0:
pretty += '\n{}finally:\n'.format(spaces)
pretty += self.finally_body.pretty_str(indent=indent + 2)
return pretty
class CodeCatchBlock(CodeStatement, CodeStatementGroup):
"""Helper class for catch statements within a try-catch block."""
def __init__(self, scope, parent):
"""Constructor for catch block structures."""
CodeStatement.__init__(self, scope, parent)
self.declarations = None
self.body = CodeBlock(scope, self, explicit=True)
def _set_declarations(self, declarations):
"""Set declarations local to this catch block."""
assert isinstance(declarations, CodeStatement)
self.declarations = declarations
declarations.scope = self.body
def _set_body(self, body):
"""Set the main body of the catch block."""
assert isinstance(body, CodeBlock)
self.body = body
def _children(self):
"""Yield all direct children of this object."""
if isinstance(self.declarations, CodeStatement):
yield self.declarations
for codeobj in self.body._children():
yield codeobj
def __repr__(self):
"""Return a string representation of this object."""
return 'catch ({}) {}'.format(self.declarations, self.body)
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
decls = ('...' if self.declarations is None
else self.declarations.pretty_str())
body = self.body.pretty_str(indent=indent + 2)
pretty = '{}catch ({}):\n{}'.format(spaces, decls, body)
return pretty
###############################################################################
# Helpers
###############################################################################
def pretty_str(something, indent=0):
"""Return a human-readable string representation of an object.
Uses `pretty_str` if the given value is an instance of
`CodeEntity` and `repr` otherwise.
Args:
something: Some value to convert.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if isinstance(something, CodeEntity):
return something.pretty_str(indent=indent)
else:
return (' ' * indent) + repr(something)
|
def is_even(i: int) -> bool:
if i == 1:
return False
elif i == 2:
return True
elif i == 3:
return False
elif i == 4:
return True
elif i == 5:
...
# Never do that! Use one of these instead...
is_even = lambda i : i % 2 == 0
is_even = lambda i : not i & 1
is_odd = lambda i : not is_even(i) |
"""
Contains the QuantumCircuit class
boom.
"""
class QuantumCircuit(object): # pylint: disable=useless-object-inheritance
""" Implements a quantum circuit.
- - - WRITE DOCUMENTATION HERE - - -
"""
def __init__(self):
""" Initialise a QuantumCircuit object """
pass
def add_gate(self, gate):
""" Add a gate to the circuit """
pass
def run_circuit(self, register):
""" Run the circuit on a given quantum register """
pass
def __call__(self, register):
""" Run the circuit on a given quantum register """
pass
|
"""
Module: 'ubinascii' on esp32 1.10.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32')
# Stubber: 1.2.0
def a2b_base64():
pass
def b2a_base64():
pass
def crc32():
pass
def hexlify():
pass
def unhexlify():
pass
|
__title__ = 'har2case'
__description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.'
__url__ = 'https://github.com/HttpRunner/har2case'
__version__ = '0.2.0'
__author__ = 'debugtalk'
__author_email__ = 'mail@debugtalk.com'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright 2017 debugtalk' |
def pictureInserter(og,address,list):
j=0
for i in og:
file1 = open(address+'/'+i, "a")
x="\ncover::https://image.tmdb.org/t/p/original/"+list[j]
file1.writelines(x)
file1.close()
j=j+1
|
class Solution:
def removeOuterParentheses(self, s: str) -> str:
ans = []
ct = 0
for ch in s:
if ch == '(':
ct += 1
if ct != 1:
ans.append(ch)
else:
ct -= 1
if ct != 0:
ans.append(ch)
return ''.join(ans)
if __name__ == '__main__':
# s = '(()())(())'
# s = '(()())(())(()(()))'
s = '()()'
ret = Solution().removeOuterParentheses(s)
print(ret)
|
#######################################################################################################################
# Given a string, find the length of the longest substring which has no repeating characters.
#
# Input: String="aabccbb"
# Output: 3
# Explanation: The longest substring without any repeating characters is "abc".
#
# Input: String="abbbb"
# Output: 2
# Explanation: The longest substring without any repeating characters is "ab".
#
# Input: String="abccde"
# Output: 3
# Explanation: Longest substrings without any repeating characters are "abc" & "cde".
#######################################################################################################################
def longest_substring_no_repeating_char(input_str: str) -> int:
window_start = 0
is_present = [None for i in range(26)]
max_window = 0
for i in range(len(input_str)):
char_ord = ord(input_str[i]) - 97
if is_present[char_ord] is not None:
window_start = max(window_start, is_present[char_ord] + 1)
is_present[char_ord] = i
max_window = max(max_window, i - window_start + 1)
return max_window
print(longest_substring_no_repeating_char('aabccbb'))
print(longest_substring_no_repeating_char('abbbb'))
print(longest_substring_no_repeating_char('abccde'))
print(longest_substring_no_repeating_char('abcabcbb'))
print(longest_substring_no_repeating_char('bbbbb'))
print(longest_substring_no_repeating_char('pwwkew'))
|
# -*- coding: UTF-8 -*-
"""
This file is part of Pondus, a personal weight manager.
Copyright (C) 2011 Eike Nicklas <eike@ephys.de>
This program is free software licensed under the MIT license. For details
see LICENSE or http://www.opensource.org/licenses/mit-license.php
"""
__all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend',
'xml_backend_old']
|
"""
The DataHandlers subpackage is designed to manipulate data, by allowing different data types to be opened,
created, saved and updated. The subpackage is further divided into modules grouped by a common theme. Classes for data
that are already on disk normally follows the following pattern:
`instance=ClassName(file_path,**options)`
For Example to
open a XML file that you don't know the model, use
`xml=pyMez.Code.DataHandlers.XMLModels.XMLBase('MyXML.xml')'
or
`xml=XMLBase('MyXML.xml')`
All data models normally have save(), str() and if appropriate show() methods.
Examples
--------
<a href="../../../Examples/How_To_Open_S2p.html"> How to open a s2p file </a>
Import Structure
----------------
DataHandlers typically import from Utils but __NOT__ from Analysis, InstrumentControl or FrontEnds
Help
-----
<a href="../index.html">`pyMez.Code`</a>
<div>
<a href="../../../pyMez_Documentation.html">Documentation Home</a> |
<a href="../../index.html">API Documentation Home</a> |
<a href="../../../Examples/html/Examples_Home.html">Examples</a> |
<a href="../../../Reference_Index.html">Index </a>
</div>
"""
|
class Solution(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
# Find max exponent
base = max(x, y) if x == 1 or y == 1 else min(x, y)
exponent = 1
if base != 1:
while base ** exponent <= bound:
exponent += 1
# Brute force all of the exponent trials
hashset = set()
for i in range(exponent):
for j in range(exponent):
z = x ** i + y ** j
if z <= bound:
hashset.add(z)
return list(hashset) |
# ------------------------------
# Binary Tree Level Order Traversal
#
# Description:
# Given a binary tree, return the level order traversal of its nodes' values. (ie, from
# left to right, level by level).
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its level order traversal as:
# [
# [3],
# [9,20],
# [15,7]
# ]
#
# Version: 2.0
# 11/11/19 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
# BFS
res = []
queue = [root]
while queue:
temp = [] # values of this level of nodes
children = [] # next level of nodes
for node in queue:
temp.append(node.val)
if node.left:
children.append(node.left)
if node.right:
children.append(node.right)
res.append(temp[:]) # actually here can be res.append(temp), res will not change as temp changes
queue = children[:] # here must be children[:] otherwise queue will change as children changes
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Similar BFS solution but use a little more spaces.
# On 102.py, using list.pop(0) actually takes O(n) time because it needs to remap the index
# of values. Use collections.deque instead.
#
# O(N) time O(N) space |
def take_beer(fridge, number=1):
if "beer" not in fridge:
raise Exception("No beer at all:(")
if number > fridge["beer"]:
raise Exception("Not enough beer:(")
fridge["beer"] -= number
if __name__ == "__main__":
fridge = {
"beer": 2,
"milk": 1,
"meat": 3,
}
print("I wanna drink 1 bottle of beer...")
take_beer(fridge)
print("Oooh, great!")
print("I wanna drink 2 bottle of beer...")
try:
take_beer(fridge, 2)
except Exception as e:
print("Error: {}. Let's continue".format(e))
print("Fallback. Try to take 1 bottle of beer...")
take_beer(fridge, 1)
print("Oooh, awesome!")
|
camera_width = 640
camera_height = 480
film_back_width = 1.417
film_back_height = 0.945
x_center = 320
y_center = 240
P_1 = (-0.023, -0.261, 2.376)
p_11 = P_1[0]
p_12 = P_1[1]
p_13 = P_1[2]
P_2 = (0.659, -0.071, 2.082)
p_21 = P_2[0]
p_22 = P_2[1]
p_23 = P_2[2]
p_1_prime = (52, 163)
x_1 = p_1_prime[0]
y_1 = p_1_prime[1]
p_2_prime = (218, 216)
x_2 = p_2_prime[0]
y_2 = p_2_prime[1]
f = 1.378
k_x = camera_width / film_back_width
k_y = camera_height / film_back_height
# f_k_x = f * k_x
f_k_x = f
# f_k_y = f * k_y
f_k_y = f
u_1_prime = (x_1 - x_center) / k_x
v_1_prime = (y_1 - y_center) / k_y
u_2_prime = (x_2 - x_center) / k_x
v_2_prime = (y_2 - y_center) / k_y
c_1_prime = (f_k_x * p_21 + (p_13 - p_23) * u_2_prime - u_2_prime/u_1_prime * f_k_x * p_11) / (f_k_x * (1 - u_2_prime/u_1_prime))
c_2_prime = (f_k_y * p_22 - (p_23 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_2_prime) / f_k_y
c_2_prime_alt = (f_k_y * p_12 - (p_13 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_1_prime) / f_k_y
c_3_prime = p_13 - (f_k_x / u_1_prime) * (p_11 - c_1_prime)
rho_1_prime = p_13 - c_3_prime
rho_2_prime = p_23 - c_3_prime
print(f"C' = ({c_1_prime}, {c_2_prime}, {c_3_prime})")
print(f"c_2_prime_alt = {c_2_prime_alt}")
print(f"rho_1_prime = {rho_1_prime}")
print(f"rho_2_prime = {rho_2_prime}")
print("------------------")
r_11 = f_k_x * (p_11 - c_1_prime)
r_12 = f_k_y * (p_12 - c_2_prime)
r_13 = 1 * (p_13 - c_3_prime)
l_11 = rho_1_prime * u_1_prime
l_12 = rho_1_prime * v_1_prime
l_13 = rho_1_prime * 1
print(f"L: ({l_11}, {l_12}, {l_13})")
print(f"R: ({r_11}, {r_12}, {r_13})")
print("------------------")
r_21 = f_k_x * (p_21 - c_1_prime)
r_22 = f_k_y * (p_22 - c_2_prime)
r_23 = 1 * (p_23 - c_3_prime)
l_21 = rho_2_prime * u_2_prime
l_22 = rho_2_prime * v_2_prime
l_23 = rho_2_prime * 1
print(f"L: ({l_11}, {l_12}, {l_13})")
print(f"R: ({r_11}, {r_12}, {r_13})") |
def main():
val=int(input("input a num"))
if val<10:
print("A")
elif val<20:
print("B")
elif val<30:
print("C")
else:
print("D")
main()
|
__all__ = ['cross_validation',
'metrics',
'datasets',
'recommender']
|
def is_leap(year):
leap=False
if year%400==0:
leap=True
elif year%4==0 and year%100!=0:
leap=True
else:
leap=False
return leap
year = int(input())
|
"""Contains utility functions."""
BIN_MODE_ARGS = {'mode', 'buffering', }
TEXT_MODE_ARGS = {'mode', 'buffering', 'encoding', 'errors', 'newline'}
def split_args(args):
"""Splits args into two groups: open args and other args.
Open args are used by ``open`` function. Other args are used by
``load``/``dump`` functions.
Args:
args: Keyword args to split.
Returns:
open_args: Arguments for ``open``.
other_args: Arguments for ``load``/``dump``.
"""
mode_args = BIN_MODE_ARGS if 'b' in args['mode'] else TEXT_MODE_ARGS
open_args = {}
other_args = {}
for arg, value in args.items():
if arg in mode_args:
open_args[arg] = value
else:
other_args[arg] = value
return open_args, other_args
def read_wrapper(load, **base_kwargs):
"""Wraps ``load`` function to avoid context manager boilerplate.
Args:
load: Function that takes the return of ``open``.
**base_kwargs: Base arguments that ``open``/``load`` take.
Returns:
Wrapper for ``load``.
"""
def wrapped(file, **kwargs):
open_args, load_args = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
return load(f, **load_args)
return wrapped
def write_wrapper(dump, **base_kwargs):
"""Wraps ``dump`` function to avoid context manager boilerplate.
Args:
dump: Function that takes the return of ``open`` and data to dump.
**base_kwargs: Base arguments that ``open``/``dump`` take.
Returns:
Wrapper for ``dump``.
"""
def wrapped(file, obj, **kwargs):
open_args, dump_args = split_args({**base_kwargs, **kwargs})
with open(file, **open_args) as f:
dump(obj, f, **dump_args)
return wrapped
|
print("Press q to quit")
quit = False
while quit is False:
in_val = input("Please enter a positive integer.\n > ")
if in_val is 'q':
quit = True
elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0:
print("FizzBuzz")
elif int(in_val) % 5 == 0:
print("Buzz")
elif int(in_val) % 3 == 0:
print("Fizz")
else:
pass
|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
class DashboardInfo:
MODEL_ID_KEY = "id" # To match Model schema
MODEL_INFO_FILENAME = "model_info.json"
RAI_INSIGHTS_MODEL_ID_KEY = "model_id"
RAI_INSIGHTS_RUN_ID_KEY = "rai_insights_parent_run_id"
RAI_INSIGHTS_PARENT_FILENAME = "rai_insights.json"
class PropertyKeyValues:
# The property to indicate the type of Run
RAI_INSIGHTS_TYPE_KEY = "_azureml.responsibleai.rai_insights.type"
RAI_INSIGHTS_TYPE_CONSTRUCT = "construction"
RAI_INSIGHTS_TYPE_CAUSAL = "causal"
RAI_INSIGHTS_TYPE_COUNTERFACTUAL = "counterfactual"
RAI_INSIGHTS_TYPE_EXPLANATION = "explanation"
RAI_INSIGHTS_TYPE_ERROR_ANALYSIS = "error_analysis"
RAI_INSIGHTS_TYPE_GATHER = "gather"
# Property to point at the model under examination
RAI_INSIGHTS_MODEL_ID_KEY = "_azureml.responsibleai.rai_insights.model_id"
# Property for tool runs to point at their constructor run
RAI_INSIGHTS_CONSTRUCTOR_RUN_ID_KEY = (
"_azureml.responsibleai.rai_insights.constructor_run"
)
# Property to record responsibleai version
RAI_INSIGHTS_RESPONSIBLEAI_VERSION_KEY = (
"_azureml.responsibleai.rai_insights.responsibleai_version"
)
# Property format to indicate presence of a tool
RAI_INSIGHTS_TOOL_KEY_FORMAT = "_azureml.responsibleai.rai_insights.has_{0}"
class RAIToolType:
CAUSAL = "causal"
COUNTERFACTUAL = "counterfactual"
ERROR_ANALYSIS = "error_analysis"
EXPLANATION = "explanation"
|
#4 lines: Fibonacci, tuple assignment
parents, babies = (1, 1)
while babies < 100:
print ('This generation has {0} babies'.format(babies))
parents, babies = (babies, parents + babies) |
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Public definitions for Go rules.
All public Go rules, providers, and other definitions are imported and
re-exported in this file. This allows the real location of definitions
to change for easier maintenance.
Definitions outside this file are private unless otherwise noted, and
may change without notice.
"""
load(
"//go/private:context.bzl",
_go_context = "go_context",
)
load(
"//go/private:providers.bzl",
_GoArchive = "GoArchive",
_GoArchiveData = "GoArchiveData",
_GoLibrary = "GoLibrary",
_GoPath = "GoPath",
_GoSDK = "GoSDK",
_GoSource = "GoSource",
)
load(
"//go/private/rules:sdk.bzl",
_go_sdk = "go_sdk",
)
load(
"//go/private:go_toolchain.bzl",
_declare_toolchains = "declare_toolchains",
_go_toolchain = "go_toolchain",
)
load(
"//go/private/rules:wrappers.bzl",
_go_binary_macro = "go_binary_macro",
_go_library_macro = "go_library_macro",
_go_test_macro = "go_test_macro",
)
load(
"//go/private/rules:source.bzl",
_go_source = "go_source",
)
load(
"//extras:embed_data.bzl",
_go_embed_data = "go_embed_data",
)
load(
"//go/private/tools:path.bzl",
_go_path = "go_path",
)
load(
"//go/private/rules:library.bzl",
_go_tool_library = "go_tool_library",
)
load(
"//go/private/rules:nogo.bzl",
_nogo = "nogo_wrapper",
)
# TOOLS_NOGO is a list of all analysis passes in
# golang.org/x/tools/go/analysis/passes.
# This is not backward compatible, so use caution when depending on this --
# new analyses may discover issues in existing builds.
TOOLS_NOGO = [
"@org_golang_x_tools//go/analysis/passes/asmdecl:go_default_library",
"@org_golang_x_tools//go/analysis/passes/assign:go_default_library",
"@org_golang_x_tools//go/analysis/passes/atomic:go_default_library",
"@org_golang_x_tools//go/analysis/passes/atomicalign:go_default_library",
"@org_golang_x_tools//go/analysis/passes/bools:go_default_library",
"@org_golang_x_tools//go/analysis/passes/buildssa:go_default_library",
"@org_golang_x_tools//go/analysis/passes/buildtag:go_default_library",
# TODO(#2396): pass raw cgo sources to cgocall and re-enable.
# "@org_golang_x_tools//go/analysis/passes/cgocall:go_default_library",
"@org_golang_x_tools//go/analysis/passes/composite:go_default_library",
"@org_golang_x_tools//go/analysis/passes/copylock:go_default_library",
"@org_golang_x_tools//go/analysis/passes/ctrlflow:go_default_library",
"@org_golang_x_tools//go/analysis/passes/deepequalerrors:go_default_library",
"@org_golang_x_tools//go/analysis/passes/errorsas:go_default_library",
"@org_golang_x_tools//go/analysis/passes/findcall:go_default_library",
"@org_golang_x_tools//go/analysis/passes/httpresponse:go_default_library",
"@org_golang_x_tools//go/analysis/passes/ifaceassert:go_default_library",
"@org_golang_x_tools//go/analysis/passes/inspect:go_default_library",
"@org_golang_x_tools//go/analysis/passes/loopclosure:go_default_library",
"@org_golang_x_tools//go/analysis/passes/lostcancel:go_default_library",
"@org_golang_x_tools//go/analysis/passes/nilfunc:go_default_library",
"@org_golang_x_tools//go/analysis/passes/nilness:go_default_library",
"@org_golang_x_tools//go/analysis/passes/pkgfact:go_default_library",
"@org_golang_x_tools//go/analysis/passes/printf:go_default_library",
"@org_golang_x_tools//go/analysis/passes/shadow:go_default_library",
"@org_golang_x_tools//go/analysis/passes/shift:go_default_library",
"@org_golang_x_tools//go/analysis/passes/sortslice:go_default_library",
"@org_golang_x_tools//go/analysis/passes/stdmethods:go_default_library",
"@org_golang_x_tools//go/analysis/passes/stringintconv:go_default_library",
"@org_golang_x_tools//go/analysis/passes/structtag:go_default_library",
"@org_golang_x_tools//go/analysis/passes/testinggoroutine:go_default_library",
"@org_golang_x_tools//go/analysis/passes/tests:go_default_library",
"@org_golang_x_tools//go/analysis/passes/unmarshal:go_default_library",
"@org_golang_x_tools//go/analysis/passes/unreachable:go_default_library",
"@org_golang_x_tools//go/analysis/passes/unsafeptr:go_default_library",
"@org_golang_x_tools//go/analysis/passes/unusedresult:go_default_library",
]
# Current version or next version to be tagged. Gazelle and other tools may
# check this to determine compatibility.
RULES_GO_VERSION = "0.30.0"
declare_toolchains = _declare_toolchains
go_context = _go_context
go_embed_data = _go_embed_data
go_sdk = _go_sdk
go_tool_library = _go_tool_library
go_toolchain = _go_toolchain
nogo = _nogo
# See go/providers.rst#GoLibrary for full documentation.
GoLibrary = _GoLibrary
# See go/providers.rst#GoSource for full documentation.
GoSource = _GoSource
# See go/providers.rst#GoPath for full documentation.
GoPath = _GoPath
# See go/providers.rst#GoArchive for full documentation.
GoArchive = _GoArchive
# See go/providers.rst#GoArchiveData for full documentation.
GoArchiveData = _GoArchiveData
# See go/providers.rst#GoSDK for full documentation.
GoSDK = _GoSDK
# See docs/go/core/rules.md#go_library for full documentation.
go_library = _go_library_macro
# See docs/go/core/rules.md#go_binary for full documentation.
go_binary = _go_binary_macro
# See docs/go/core/rules.md#go_test for full documentation.
go_test = _go_test_macro
# See docs/go/core/rules.md#go_test for full documentation.
go_source = _go_source
# See docs/go/core/rules.md#go_path for full documentation.
go_path = _go_path
def go_vet_test(*args, **kwargs):
fail("The go_vet_test rule has been removed. Please migrate to nogo instead, which supports vet tests.")
def go_rule(**kwargs):
fail("The go_rule function has been removed. Use rule directly instead. See https://github.com/bazelbuild/rules_go/blob/master/go/toolchains.rst#writing-new-go-rules")
def go_rules_dependencies():
_moved("go_rules_dependencies")
def go_register_toolchains(**kwargs):
_moved("go_register_toolchains")
def go_download_sdk(**kwargs):
_moved("go_download_sdk")
def go_host_sdk(**kwargs):
_moved("go_host_sdk")
def go_local_sdk(**kwargs):
_moved("go_local_sdk")
def go_wrap_sdk(**kwargs):
_moved("go_wrap_sdK")
def _moved(name):
fail(name + " has moved. Please load from " +
" @io_bazel_rules_go//go:deps.bzl instead of def.bzl.")
|
# model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='pretrain/vit_base_patch16_224.pth',
backbone=dict(
type='VisionTransformer',
img_size=(224, 224),
patch_size=16,
in_channels=3,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4,
# out_indices=(2, 5, 8, 11),
qkv_bias=True,
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.0,
with_cls_token=True,
norm_cfg=dict(type='LN', eps=1e-6),
act_cfg=dict(type='GELU'),
norm_eval=False,
interpolate_mode='bicubic'),
neck=None,
decode_head=dict(
type='ASPPHead',
in_channels=768,
# in_index=3,
channels=512,
dilations=(1, 6, 12, 18),
dropout_ratio=0.1,
num_classes=21,
contrast=True,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
auxiliary_head=None,
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(mode='whole')) # yapf: disable |
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool_path",
)
all_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
]
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
]
def _impl(ctx):
tool_paths = [
tool_path(
name = "gcc",
path = "/opt/emsdk/upstream/emscripten/emcc",
),
tool_path(
name = "ld",
path = "/opt/emsdk/upstream/emscripten/emcc",
),
tool_path(
name = "ar",
path = "/opt/emsdk/upstream/emscripten/emar",
),
tool_path(
name = "cpp",
path = "/opt/emsdk/upstream/emscripten/em++",
),
tool_path(
name = "gcov",
path = "/bin/false",
),
tool_path(
name = "nm",
path = "/bin/false",
),
tool_path(
name = "objdump",
path = "/bin/false",
),
tool_path(
name = "strip",
path = "/bin/false",
),
]
features = [ # NEW
feature(
name = "default_compile_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = ([
flag_group(
flags = [
"-O3",
"-msimd128",
"-s",
"USE_PTHREADS=0",
"-s",
"ERROR_ON_UNDEFINED_SYMBOLS=0",
"-s",
"STANDALONE_WASM=1",
],
),
]),
),
],
),
feature(
name = "default_linker_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_link_actions,
flag_groups = ([
flag_group(
flags = [
"-O3",
"-msimd128",
"-s",
"USE_PTHREADS=0",
"-s",
"ERROR_ON_UNDEFINED_SYMBOLS=0",
"-s",
"STANDALONE_WASM=1",
"-Wl,--export=__heap_base",
"-Wl,--export=__data_end",
],
),
]),
),
],
),
]
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
features = features, # NEW
cxx_builtin_include_directories = [
"/opt/emsdk/upstream/emscripten/system/include/libcxx",
"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include",
"/opt/emsdk/upstream/emscripten/system/include",
"/opt/emsdk/upstream/emscripten/system/include/libc",
"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten",
"/opt/emsdk/upstream/lib/clang/12.0.0/include/",
],
toolchain_identifier = "wasm-emsdk",
host_system_name = "i686-unknown-linux-gnu",
target_system_name = "wasm32-unknown-emscripten",
target_cpu = "wasm32",
target_libc = "unknown",
compiler = "emsdk",
abi_version = "unknown",
abi_libc_version = "unknown",
tool_paths = tool_paths,
)
emsdk_toolchain_config = rule(
implementation = _impl,
attrs = {},
provides = [CcToolchainConfigInfo],
)
|
def get_index_different_char(chars):
alnum = []
not_alnum = []
for index, char in enumerate(chars):
if str(char).isalnum():
alnum.append(index)
else:
not_alnum.append(index)
result = alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0]
return result
# tests
def test_wrong_char():
inputs = (
['A', 'f', '.', 'Q', 2],
['.', '{', ' ^', '%', 'a'],
[1, '=', 3, 4, 5, 'A', 'b', 'a', 'b', 'c'],
['=', '=', '', '/', '/', 9, ':', ';', '?', '¡'],
list(range(1,9)) + ['}'] + list('abcde'), # noqa E231
)
expected = [2, 4, 1, 5, 8]
for arg, exp in zip(inputs, expected):
err = f'get_index_different_char({arg}) should return index {exp}'
assert get_index_different_char(arg) == exp, err |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Contains core logic for Rainman2
"""
__author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)'
__date__ = 'Wednesday, February 14th 2018, 11:42:09 am'
|
train_data_path = "../data/no_cycle/train.data"
dev_data_path = "../data/no_cycle/dev.data"
test_data_path = "../data/no_cycle/test.data"
word_idx_file_path = "../data/word.idx"
word_embedding_dim = 100
train_batch_size = 32
dev_batch_size = 500
test_batch_size = 500
l2_lambda = 0.000001
learning_rate = 0.001
epochs = 100
encoder_hidden_dim = 200
num_layers_decode = 1
word_size_max = 1
dropout = 0.0
path_embed_method = "lstm" # cnn or lstm or bi-lstm
unknown_word = "<unk>"
PAD = "<PAD>"
GO = "<GO>"
EOS = "<EOS>"
deal_unknown_words = True
seq_max_len = 11
decoder_type = "greedy" # greedy, beam
beam_width = 4
attention = True
num_layers = 1 # 1 or 2
# the following are for the graph encoding method
weight_decay = 0.0000
sample_size_per_layer = 4
sample_layer_size = 4
hidden_layer_dim = 100
feature_max_len = 1
feature_encode_type = "uni"
# graph_encode_method = "max-pooling" # "lstm" or "max-pooling"
graph_encode_direction = "bi" # "single" or "bi"
concat = True
encoder = "gated_gcn" # "gated_gcn" "gcn" "seq"
lstm_in_gcn = "none" # before, after, none
|
class Input(object):
def __init__(self, type, data):
self.__type = type
self.__data = deepcopy(data)
def __repr__(self):
return repr(self.__data)
def __str__(self):
return str(self.__type) + str(self.__data)
|
"""
Utilizando Lambdas
Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja,
funções anónimas.
# Função em Python
def funcao(x):
return 3 * x + 1
print(funcao(4))
print(funcao(7))
# Expressão Lambda
lambda x: 3 * x + 1
# Como utlizar a expressão lambda?
calc = lambda x: 3 * x + 1
print(calc(4))
print(calc(7))
# Podemos ter expressões lambdas com múltiplas entradas
nome_compelto = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()
print(nome_compelto(' paulo', ' SILVA '))
print(nome_compelto(' MARIA ', ' albertina '))
# Em funções Python podemos ter nenhuma ou várias entradas. Em Lambdas também
hello = lambda: 'Hello World!'
uma = lambda x: 3 * x + 1
duas = lambda x, y: (x * y) ** 0.5
tres = lambda x, y, z: 3 / (1 / x + 1 / 7 + 1 / z)
# n = lambda x1, x2, ..., xn: <expressão>
print(hello())
print(uma(6))
print(duas(5, 7))
print(tres(3, 6, 9))
# OBS: Se passarmos mais argumentos do que parâmetros esperados teremos TypeError
# Exemplo
autores = ['Paulo Silva', 'Maria Albertina', 'Luis Marques Nunes', 'Carlos Nunes',
'Ana S. Leitão', 'Inês Garcia', 'Claudia Sofia', 'I. L. Antunes',
'Américo Silva']
print(autores)
# ['Paulo Silva', 'Maria Albertina', 'Luis Marques Nunes', 'Carlos Nunes',
# 'Ana S. Leitão', 'Inês Garcia', 'Claudia Sofia', 'I. L. Antunes', 'Américo Silva']
# Ordenar pelo sobrenome
autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower())
print(autores)
# ['Maria Albertina', 'I. L. Antunes', 'Inês Garcia', 'Ana S. Leitão',
# 'Luis Marques Nunes', 'Carlos Nunes', 'Paulo Silva', 'Américo Silva', 'Claudia Sofia']
"""
# Função Quadrática
# f(x) = a * x ** 2 + b * x + c
# Definindo a função
def geradora_funcao_quadratica(a, b, c):
"""
Retorna a função f(x) = a * x ** 2 + b * x + c
"""
return lambda x: a * x ** 2 + b * x + c
teste = geradora_funcao_quadratica(2, 3, -5)
print(teste(0))
print(teste(1))
print(teste(2))
print(geradora_funcao_quadratica(3, 0, 1)(2))
|
# Lista dentro de dicionário
campeonato = dict()
gol = []
aux = 0
campeonato['Jogador'] = str(input('Digite o nome do jogador: '))
print()
partidas = int(input('Quantas partidas ele jogou? '))
print()
for i in range(0, partidas):
aux = int(input(f'Quantos gols na partida {i + 1}? '))
gol.append(aux)
print()
campeonato['Gols'] = gol[:]
campeonato['Total'] = sum(gol)
print('=' * 55)
print()
print(campeonato)
print()
print('=' * 55)
print()
for k, v in campeonato.items():
print(f'O campo {k} tem o valor: {v}')
print()
print('=' * 55)
print(f'O jogador {campeonato["Jogador"]} jogou {partidas} partidas.')
print()
for i in range(0, partidas):
print(f'Na partida {i + 1} ele fez {gol[i]} gol(s).')
print()
print(f'No total ele fez {campeonato["Total"]} gols.')
print('=' * 55)
|
class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.width=width
self.height=height
self.food=collections.deque(food)
self.position=collections.deque([(0,0)])
self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)}
self.score=0
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
if direction not in self.moveops:
return -1
peak,tail=self.position[0],self.position[-1]
self.position.pop()
idxi,idxj=self.moveops[direction]
newi,newj=peak[0]+idxi,peak[1]+idxj
if (newi,newj) in self.position or \
newi<0 or newi>=self.height or \
newj<0 or newj>=self.width:
return -1
self.position.appendleft((newi,newj))
if self.food and [newi,newj]==self.food[0]:
self.food.popleft()
self.position.append(tail)
self.score+=1
return self.score
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction) |
class Player:
def __init__(self, nickname, vapor_id, player_id, ip):
self.nickname = nickname
self.vapor_id = vapor_id
self.player_id = player_id
self.ip = ip
self.not_joined = True
self.loads_map = True
self.joined_after_change_map = True
class Players:
def __init__(self, main_object, modded, lobby):
self.main = main_object
self.players = []
self.modded = modded
self.map_changed = False
self.lobby = lobby
self.commands = None
def get_commands_object(self, commands_object):
self.commands = commands_object
def _on_map_change(self, map_name):
self.map_changed = map_name
if self.modded and self.players:
for player in self.players:
player.loads_map = True
def check_if_everyone_joined_after_change_map(self):
for player in self.players:
if player.loads_map and not player.joined_after_change_map:
return False
return True
def _on_player_info_ev(self, player_id):
player = [player for player in self.players if player.player_id == player_id][0]
if self.map_changed or hasattr(player, "not_joined"):
if player.loads_map and player.joined_after_change_map:
player.joined_after_change_map = False
elif player.loads_map and not player.joined_after_change_map:
player.loads_map = False
player.joined_after_change_map = True
self.main.on_player_map_change(player, self.map_changed)
if hasattr(player, "not_joined"):
del player.not_joined
self.main.on_client_join(player)
if self.check_if_everyone_joined_after_change_map():
self.map_changed = False
def check_nickname_existence(self, nickname):
for player in self.players:
if nickname == player.nickname:
return True
return False
def get_all_players(self, nicknames, vapor_ids, player_ids, ips):
players_list = [nicknames, vapor_ids, player_ids, ips]
for count in range(len(nicknames)):
self.players.append(Player(*[player[count] for player in players_list]))
def add(self, nickname, vapor_id, player_id, ip):
self.players.append(Player(nickname, vapor_id, player_id, ip))
def remove(self, nickname):
for player in self.players:
if nickname == player.nickname:
self.players.remove(player)
break
if self.lobby and len(self.players) == 0:
self.commands.change_map(self.lobby)
def nickname_change(self, old_nickname, new_nickname):
for player in self.players:
if old_nickname == player.nickname:
player.nickname = new_nickname
break
def all_nicknames(self):
return [player.nickname for player in self.players]
def player_from_nickname(self, nickname):
for player in self.players:
if nickname == player.nickname:
return player
def player_from_vapor_id(self, vapor_id):
for player in self.players:
if vapor_id == player.vapor_id:
return player
def player_from_player_id(self, player_id):
for player in self.players:
if player_id == player.player_id:
return player
def get_all_vapor_ids(self):
return [player.vapor_id for player in self.players]
|
# 377 Combination Sum IV
# Given an integer array with all positive numbers and no duplicates,
# find the number of possible combinations that add up to a positive integer target.
#
# Example:
#
# nums = [1, 2, 3]
# target = 4
#
# The possible combination ways are:
# (1, 1, 1, 1)
# (1, 1, 2)
# (1, 2, 1)
# (1, 3)
# (2, 1, 1)
# (2, 2)
# (3, 1)
#
# Note that different sequences are counted as different combinations.
#
# Therefore the output is 7.
#
# Follow up:
# What if negative numbers are allowed in the given array?
# How does it change the problem?
# What limitation we need to add to the question to allow negative numbers?
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res = [0] * (target + 1)
for i in range(1, len(res)):
for num in nums:
if num > i:
break
elif num == i:
res[i] += 1
else:
res[i] += res[i-num]
return res[target]
# https://www.hrwhisper.me/leetcode-combination-sum-iv/
# dp[i] += dp[i-num]
def combinationSum4(self, nums, target):
dp = [1] + [0] * target
for i in range(1, target+1):
for num in nums:
if i >= num:
dp[i] += dp[i-num]
return dp[target]
print(Solution().combinationSum4([1, 2, 3], 4))
|
# --- Klassendeklaration mit Konstruktor --- #
class PC:
def __init__(self, cpu, gpu, ram):
self.cpu = cpu
self.gpu = gpu
self.__ram = ram
# --- Instanziierung einer Klasse ---#
# --- Ich bevorzuge die Initialisierung mit den Keywords --- #
pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill')
# --- Zugriff auf normale _public_ Attribute --- #
print(pc_instanz.cpu)
print(pc_instanz.gpu)
# --- Zugriff auf ein _privates_ Attribut --- #
# Auskommentiert, da es einen AttributeError schmeißt.
# print(pc_instanz.__ram)
# --- Zugriff auf das Instanz-Dictionary, um die Inhalte jener Instanz zu erhalten. --- #
print(pc_instanz.__dict__)
# --- Zugriff auf das eigentlich _private_ Attribut. --- #
print(pc_instanz._PC__ram)
|
"""
8皇后问题
使用栈实现回溯法
"""
def print_board(n,count):
print(f"------解.{count}------")
print(" ",end="")
for j in range(n):
print(f"{j:<2}" ,end="")
print()
for i in range(1,n+1):
print(f"{i:<2}",end="")
for j in range(1,n+1):
if queens[i] == j:
print("Q ",end="")
else:
print(" ",end="")
print()
def set_flags(i,j,n):
col_flags[j]=1
diag_flags[i+j-1]=1
diag2_flags[n+i-j]=1
def clear_flags(i,j,n):
col_flags[j]=0
diag_flags[i+j-1]=0
diag2_flags[n+i-j]=0
def can_stay(i,j,n):
if col_flags[j]==1:
return False
if diag_flags[i+j-1]==1:
return False
if diag2_flags[n+i-j]==1:
return False
return True
def try_queen(i,n):
global count
i=1
while True:
queens[i]+=1
if queens[i]>n: # backtracking
i-=1
if i<1: # all possible solutions have been tried, quit searching
break
clear_flags(i,queens[i],n)
elif can_stay(i,queens[i],n):
if i==n:
count += 1
print_board(n, count)
else:
set_flags(i, queens[i], n)
i+=1
queens[i] = 0
def queen(n):
try_queen(1,n)
n=int(input("请输入n:"))
queens = [0]*(n+1)
# 列标志
col_flags=[0]*(n+1)
# 主对角线标志
diag_flags = [0]*(2*n)
# 副对角线标志
diag2_flags = [0] * (2*n)
count = 0
queen(n)
print(f"共有{count}种解法\n")
|
#
# PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file://..\DABING-MIB.mib
# Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022
# On host ? platform ? version ? by user ?
# Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)]
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "ModuleIdentity", "IpAddress", "ObjectIdentity", "iso", "Counter32", "Unsigned32", "Bits", "NotificationType", "TimeTicks", "Counter64", "enterprises", "MibIdentifier", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
dabing = ModuleIdentity((1, 3, 6, 1, 4, 1, 55532))
dabing.setRevisions(('2022-03-17 00:00',))
if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z')
if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk')
Parameters = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 1))
Agent = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 2))
Manager = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 3))
Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4))
NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 1))
NotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 2))
channel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess("readonly")
if mibBuilder.loadTexts: channel.setStatus('current')
interval = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess("readonly")
if mibBuilder.loadTexts: interval.setStatus('current')
trapEnabled = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapEnabled.setStatus('current')
agentIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentIdentifier.setStatus('current')
agentLabel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentLabel.setStatus('current')
agentStatus = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentStatus.setStatus('current')
managerHostname = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: managerHostname.setStatus('current')
managerPort = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess("readonly")
if mibBuilder.loadTexts: managerPort.setStatus('current')
genericPayload = MibScalar((1, 3, 6, 1, 4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: genericPayload.setStatus('current')
malfunctionTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 1)).setObjects(("DABING-MIB", "genericPayload"))
if mibBuilder.loadTexts: malfunctionTrap.setStatus('current')
testTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 2)).setObjects(("DABING-MIB", "genericPayload"))
if mibBuilder.loadTexts: testTrap.setStatus('current')
mibBuilder.exportSymbols("DABING-MIB", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing, agentStatus=agentStatus, interval=interval)
|
def solve(polynomial):
"""
input is polynomial
if more than one variable, returns 'too many variables'
looks for formula to apply to coefficients
returns solution or 'I cannot solve yet...'
"""
if len(polynomial.term_matrix[0]) > 2:
return 'too many variables'
elif len(polynomial.term_matrix[0]) == 1:
return polynomial.term_matrix[1][0]
elif len(polynomial.term_matrix[0]) == 2:
degree = polynomial.term_matrix[1][1]
if degree == 1:
if len(polynomial.term_matrix) == 2:
return 0
else:
return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0]
if degree == 2:
ans = quadratic_formula(polynomial)
return ans
if degree > 2:
return Durand_Kerner(polynomial)
def quadratic_formula(polynomial):
"""
input is single-variable polynomial of degree 2
returns zeros
"""
if len(polynomial.term_matrix) == 3:
if polynomial.term_matrix[2][1] == 1:
a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]
return 0, -b/a
a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]
return (-c/a)**.5, -(-c/a)**.5
if len(polynomial.term_matrix) == 2:
a, b, c, = polynomial.term_matrix[1][0], 0, 0
elif len(polynomial.term_matrix) == 3:
a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0
else:
a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0]
ans1 = (-b + (b**2 - 4*a*c)**.5)/2*a
ans2 = (-b - (b**2 - 4*a*c)**.5)/2*a
if ans1 == ans2:
return ans1
return ans1, ans2
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001):
"""
returns boolean whether abs(a-b) is less than abs_total or rel_total*max(a, b)
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def Durand_Kerner(f):
"""
input polynomial
returns numerical approximation of all complex roots
"""
roots = []
for i in range(f.degree()):
roots.append((0.4 + 0.9j)**i)
diff = 1
diff_temp = 0
def iterate():
nonlocal roots
new_roots = roots[:]
for i in range(len(roots)):
q = 1
for j, root in enumerate(roots):
if j != i:
q *= roots[i] - root
new_roots[i] = roots[i] - f(roots[i])/q
nonlocal diff
nonlocal diff_temp
diff_temp = diff
diff = 0
for i in range(len(roots)):
diff += abs(roots[i] - new_roots[i])
roots = new_roots
while diff > .00000001 and not isclose(diff_temp, diff):
iterate()
for i in range(len(roots)):
if isclose(roots[i].real, round(roots[i].real)):
temp = round(roots[i].real)
roots[i] -= roots[i].real
roots[i] += temp
if isclose(roots[i].imag, round(roots[i].imag)):
temp = round(roots[i].imag)
roots[i] -= roots[i].imag*1j
roots[i] += temp*1j
return roots
if __name__ == '__main__':
pass
|
class TreeNode:
def __init__(self, name, data, parent=None):
self.name = name
self.parent = parent
self.data = data
self.childs = {}
def add_child(self, name, data):
self.childs.update({name:(type(self))(name, data, self)})
def rm_branch(self, name, ansistors_n: list = None,):
focus = self.childs
while True:
if ansistors_n == None or ansistors_n == self.name:
del focus[name]
break
elif ansistors_n[0] in focus:
focus = (focus[ansistors_n[0]]).childs
del ansistors_n[0]
elif name in focus and ansistors_n is None:
del focus[name]
break
else:
print(focus)
raise NameError(f"couldn't find branch {ansistors_n[0]}")
def __getitem__(self, item):
return self.childs[item]
def __setitem__(self, key, value):
self.childs[key] = value
def __delitem__(self, key, ansistors_n: list = None):
self.rm_branch(key, ansistors_n)
|
api_key = "9N7hvPP9yFrjBnELpBdthluBjiOWzJZw"
mongo_url = 'mongodb://localhost:27017'
mongo_db = 'CarPopularity'
mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion']
years_data = ['2019', '2018', '2017', '2016', '2015']
test_mode = True |
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return [-1, -1]
low = 0
high = len(nums) - 1
f = 0
while low<=high:
mid = (low+high)//2
if nums[mid] == target:
f = 1
break
elif nums[mid] < target:
low = mid + 1
elif nums[mid] > target:
high = mid - 1
i, j = mid, mid
while i>=1 and nums[i-1] == target:
i = i-1
while j<len(nums)-1 and nums[j+1] == target:
j = j+1
if f == 1:
return [i, j]
else:
return [-1, -1]
|
#
# PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:16:04 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")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "ObjectIdentity", "IpAddress", "Bits", "MibIdentifier", "Integer32", "enterprises", "ModuleIdentity", "TimeTicks", "Counter32", "NotificationType", "iso", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
tecElite = MibIdentifier((1, 3, 6, 1, 4, 1, 217))
meterWorks = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16))
mw501 = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1))
mwMem = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 1))
mwHeap = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 2))
mwMemCeiling = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory')
if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager will allow the agent to use.')
mwMemUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory')
if mibBuilder.loadTexts: mwMemUsed.setDescription("bytes of memory that meterworks has malloc'ed. some of this may be in free pools.")
mwHeapTotal = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory')
if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap manager.')
mwHeapUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory')
if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.')
mibBuilder.exportSymbols("MWORKS-MIB", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501, mwHeapTotal=mwHeapTotal, mwMemUsed=mwMemUsed)
|
# == 1 ==
bar = [1, 2]
def foo(bar):
bar = sum(bar)
return bar
print(foo(bar))
# == 2 ==
bar = [1, 2]
def foo(bar):
bar[0] = 1
return sum(bar)
print(foo(bar))
# == 3 ==
bar = [1, 2]
def foo():
bar = sum(bar)
return bar
print(foo())
# == 4 ==
bar = [1, 2]
def foo(bar):
bar = [1, 2, 3, ]
return sum(bar)
print(foo(bar), bar)
# == 5 ==
bar = [1, 2]
def foo(bar):
bar[:] = [1, 2, 3, ]
return sum(bar)
print(foo(bar), bar)
# == 6 ==
try:
bar = 1 / 0
print(bar)
except ZeroDivisionError as bar:
print(bar)
print(bar)
# == 7 ==
bar = [1, 2]
print(list(bar for bar in bar))
print(bar)
# == 8 ==
bar = [1, 2]
f = lambda: sum(bar)
print(f())
bar = [1, 2, 3, ]
print(f())
# == 9 ==
bar = [1, 2]
def foo(bar):
return lambda: sum(bar)
f = foo(bar)
print(f())
bar = [1, 2, 3, ]
print(f())
# == 10 ==
bar = [1, 2]
foo = []
for i in bar:
foo.append(lambda: i)
print([f() for f in foo])
# == 11 ==
bar = [1, 2]
foo = [
lambda: i
for i in bar
]
print(list(f() for f in foo))
# == 12 ==
bar = [1, 2]
foo = [
lambda: i
for i in bar
]
print(list(f() for f in foo))
bar = [1, 2, 3, ]
print(list(f() for f in foo))
bar[:] = [1, 2, 3, ]
print(list(f() for f in foo))
# == 13 ==
bar = [1, 2]
foo = [
lambda i=i: i
for i in bar
]
print(list(f() for f in foo))
|
# Other solution
# V2
def minWindow(s, t):
need = collections.Counter(t) #hash table to store char frequency
missing = len(t) #total number of chars we care
start, end = 0, 0
i = 0
for j, char in enumerate(s, 1): #index j from 1
if need[char] > 0:
missing -= 1
need[char] -= 1
if missing == 0: #match all chars
while i < j and need[s[i]] < 0: #remove chars to find the real start
need[s[i]] += 1
i += 1
need[s[i]] += 1 #make sure the first appearing char satisfies need[char]>0
missing += 1 #we missed this first char, so add missing by 1
if end == 0 or j-i < end-start: #update window
start, end = i, j
i += 1 #update i to start+1 for next window
return s[start:end]
# Time: O(|S|+|T|)
# Space:O(|S|+|T|)
# Refer from:
# https://leetcode.com/problems/minimum-window-substring/solution/
# Sliding Window
# We start with two pointers, leftleft and rightright initially pointing to the first element of the string S.
# We use the rightright pointer to expand the window until we get a desirable window i.e. a window that contains all of the characters of T.
# Once we have a window with all the characters, we can move the left pointer ahead one by one. If the window is still a desirable one we keep on updating the minimum window size.
# If the window is not desirable any more, we repeat step 2 onwards.
# The current window is s[i:j] and the result window is s[I:J]. In need[c] I store how many times I
# need character c (can be negative) and missing tells how many characters are still missing.
# In the loop, first add the new character to the window. Then, if nothing is missing,
# remove as much as possible from the window start and then update the result.
class Solution:
def minWindow(self, s: str, t: str) -> str:
m = len(s)
n = len(t)
if m < n:
return ''
lt = {}
# put t into dict (lt) and count how many # for each char
for i in t:
if i not in lt:
lt[i] = 1
else:
lt[i] += 1
# missing is to count how many remaining char needed from substring
# finally get candidate substring which satisfy need of t
missing = n
i = I = J = 0
for j, c in enumerate(s, 1):
if c in lt and lt[c] > 0:
missing -= 1
if c in lt:
# lt can be negative
lt[c] -= 1
# i is index of candidate substring, remove as many as char from candidate
while i < j and not missing:
if not J or j-i < J-I:
I, J = i, j
if s[i] not in lt:
i += 1
continue
else:
# if lt contains s[i], then # of s[i] +1, might reach to 0
lt[s[i]] += 1
# if > 0, means we need more, then missing +1
if lt[s[i]] > 0:
missing += 1
i += 1
return s[I:J]
# Time: O(|S|+|T|)
# Space:O(|S|+|T|)
# Optimized Sliding Window
# A small improvement to the above approach can reduce the time complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣),
# where filtered(S) is the string formed from S by removing all the elements not present in T
|
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Class ANY (generic) rdata type classes."""
__all__ = [
'AFSDB',
'AMTRELAY',
'AVC',
'CAA',
'CDNSKEY',
'CDS',
'CERT',
'CNAME',
'CSYNC',
'DLV',
'DNAME',
'DNSKEY',
'DS',
'EUI48',
'EUI64',
'GPOS',
'HINFO',
'HIP',
'ISDN',
'LOC',
'MX',
'NINFO',
'NS',
'NSEC',
'NSEC3',
'NSEC3PARAM',
'OPENPGPKEY',
'OPT',
'PTR',
'RP',
'RRSIG',
'RT',
'SMIMEA',
'SOA',
'SPF',
'SSHFP',
'TKEY',
'TLSA',
'TSIG',
'TXT',
'URI',
'X25',
]
|
n = int(input())
row = 0
for i in range(100):
if 2 ** i <= n <= 2 ** (i + 1) - 1:
row = i
break
def seki(k, n):
for _ in range(n):
k = 4 * k + 2
return k
k = 0
if row % 2 != 0:
k = 2
cri = seki(k, row // 2)
if n < cri:
print("Aoki")
else:
print("Takahashi")
else:
k = 1
cri = seki(k, row // 2)
if n < cri:
print("Takahashi")
else:
print("Aoki")
|
bino = int(input())
cino = int(input())
if (bino+cino)%2==0:
print("Bino")
else:
print("Cino")
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 11:06:59 2019
@author: Paul
"""
def read_data(filename):
"""
Reads csv file into a list, and converts to ints
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip('\n').split(',')
int_data = [int(i) for i in data]
f.close()
return int_data
def run_intcode(program, input_int):
"""
Takes data, list of ints to run int_code on.
Returns list of ints after intcode program has been run.
Running Intcode program looks reads in the integers sequentially in sets of 4:
data[i] == Parameter Mode + Opcode (last two digits)
data[i+1] == Entry 1
data[i+2] == Entry 2
data[i+3] == Entry 3
If Opcode == 1, the value of the opcode at index location = entry 1 and 2
in the program are summed and stored at the index location of entry 3.
If Opcode == 2, the value of the opcode at index location = entry 1 and 2
in the program are multiplied and stored at the index location of entry 3.
If Opcode == 3, the the single integer (input) is saved to the position given
by index 1.
If Opcode == 4, the program outputs the value of its only parameter. E.g. 4,50
would output the value at address 50.
If Opcode == 5 and entry 1 is != 0, the intcode position moves to the index stored
at entry 2. Otherwise it does nothing.
If Opcode == 6 and entry 1 is 0, the intcode postion moves to the index stored
at entry 2. Otherwise it does nothing.
If Opcode == 7 and entry 1> entry 2, store 1 in position given by third param,
otherwise store 0 at position given by third param.
If Opcode == 7 and entry 1 = entry 2, store 1 in position given by third param,
otherwise store 0 at position given by third param.
If Opcode == 99, the program is completed and will stop running.
Parameters are digits to the left of the opcode, read left to right:
Parameter 0 -> Position mode - the entry is treated as an index location
Parameter 1 -> Immediate mode - the entry is treated as a value
"""
data = program[:]
answer = -1
params = [0, 0, 0]
param_modes = ['', '', '']
i = 0
while (i < len(program)):
#print("i = ", i)
# Determine Opcode and parameter codes:
opcode_str = "{:0>5d}".format(data[i])
opcode = int(opcode_str[3:])
param_modes[0] = opcode_str[2]
param_modes[1] = opcode_str[1]
param_modes[2] = opcode_str[0]
#print(opcode_str)
for j in range(2):
if param_modes[j] == '0':
try:
params[j] = data[data[i+j+1]]
except IndexError:
continue
else:
try:
params[j] = data[i+j+1]
except IndexError:
continue
#print(params, param_modes)
# If opcode is 1, add relevant entries:
if opcode == 1:
data[data[i+3]] = params[0] + params[1]
i += 4;
# If opcode is 2, multiply the relevant entries:
elif opcode == 2:
data[data[i+3]] = params[0] * params[1]
i += 4;
# If opcode is 3, store input value at required location.
elif opcode == 3:
data[data[i+1]] = input_int
i += 2;
# If opcode is 4, print out the input stored at specified location.
elif opcode == 4:
answer = data[data[i+1]]
print("Program output: ", data[data[i+1]])
i += 2;
# If the opcode is 5 and the next parameter !=0, jump forward
elif opcode == 5:
if params[0] != 0:
i = params[1]
else:
i += 3
# If the opcode is 6 and next parameter is 0, jump forward
elif opcode == 6:
if params[0] == 0:
i = params[1]
else:
i += 3
# If the opcode is 7, carry out less than comparison and store 1/0 at loc 3
elif opcode == 7:
if params[0] < params[1]:
data[data[i+3]] = 1
else:
data[data[i+3]] = 0
i += 4
# If the opcode is 8, carry out equality comparison and store 1/0 at loc 3
elif opcode == 8:
if params[0] == params[1]:
data[data[i+3]] = 1
else:
data[data[i+3]] = 0
i += 4
# If the opcode is 99, halt the intcode
elif opcode == 99:
print("Program ended by halt code")
break
# If opcode is anything else something has gone wrong!
else:
print("Problem with the Program")
break
return data, answer
program = read_data("day5input.txt")
#print(program)
result1, answer1 = run_intcode(program, 1)
#print(result1)
print("Part 1: Answer is: ", answer1)
result2, answer2 = run_intcode(program, 5)
#print(result2)
print("Part 2: Answer is: ", answer2)
#test_program = [1002,4,3,4,33]
#test_program2 = [3,0,4,0,99]
#test_program3 = [1101,100,-1,4,0]
#test_program4 = [3,9,8,9,10,9,4,9,99,-1,8] # 1 if input = 8, 0 otherwise
#test_program5 = [3,9,7,9,10,9,4,9,99,-1,8] # 1 if input < 8, 0 otherwise
#test_program6 = [3,3,1108,-1,8,3,4,3,99] # 1 if input = 8, 0 otherwise
#test_program7 = [3,3,1107,-1,8,3,4,3,99] # 1 if input < 8, 0 otherwise
#test_program8 = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9] # 0 if input = 0, 1 otherwise
#test_program9 = [3,3,1105,-1,9,1101,0,0,12,4,12,99,1] # 0 if input = 0, 1 otherwise
#test_program10 = [3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,
#36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,
#1105,1,46,98,99] # 999 if input < 8, 1000 if input = 8, 1001 if input > 8
|
class Rectangle:
"""A rectangle shape that can be drawn on a Canvas object"""
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
def draw(self, canvas):
"""Draws itself into the Canvas object"""
# Changes a slice of the array with new values
canvas.data[self.x: self.x + self.height, self.y: self.y + self.width] = self.color
class Square:
"""A square shape that can be drawn on a Canvas object"""
def __init__(self, x, y, side, color):
self.x = x
self.y = y
self.side = side
self.color = color
def draw(self, canvas):
"""Draws itself into the Canvas object"""
# Changes a slice of the array with new values
canvas.data[self.x: self.x + self.side, self.y: self.y + self.side] = self.color
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.