body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
d72e52ed388d13398a86567769cc6bf559d0cf927c6d954ca6613f189ceb38f6
def while_E(): " Upper case Alphabet letter 'E' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or ((row % 3) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'E' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_E
SaikumarS2611/ANSPatterns
0
python
def while_E(): " " row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or ((row % 3) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_E(): " " row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or ((row % 3) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'E' pattern using Python while loop<|endoftext|>
f74f41c2d96fed30274a45eddcb7c59bba387da2de0592b6741e97d9384f232d
def for_F(): " Upper case Alphabet letter 'F' pattern using Python for loop" for row in range(7): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'F' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_F
SaikumarS2611/ANSPatterns
0
python
def for_F(): " " for row in range(7): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') print()
def for_F(): " " for row in range(7): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'F' pattern using Python for loop<|endoftext|>
f1b49a2267db9870dce977bdcf8d3a6838c9f61beb4705450264a83b781b473c
def while_F(): " Upper case Alphabet letter 'F' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'F' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_F
SaikumarS2611/ANSPatterns
0
python
def while_F(): " " row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_F(): " " row = 0 while (row < 7): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (row != 6))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'F' pattern using Python while loop<|endoftext|>
e66e9767c61fd85aab481c51c49ce249b77745dbea890faefaffadbad4765bd0
def for_G(): " Upper case Alphabet letter 'G' pattern using Python for loop" for row in range(7): for col in range(5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'G' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_G
SaikumarS2611/ANSPatterns
0
python
def for_G(): " " for row in range(7): for col in range(5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') print()
def for_G(): " " for row in range(7): for col in range(5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'G' pattern using Python for loop<|endoftext|>
b40cd10e7d20a9a52aad20664afdf535fba4f726d287cb3f318ae644df5f7568
def while_G(): " Upper case Alphabet letter 'G' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'G' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_G
SaikumarS2611/ANSPatterns
0
python
def while_G(): " " row = 0 while (row < 7): col = 0 while (col < 5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_G(): " " row = 0 while (row < 7): col = 0 while (col < 5): if (((col == 0) and (row > 0) and (row < 6)) or (((row % 3) == 0) and (col > 0) and (col < 4) and (row != 3)) or ((row == 3) and (col > 1)) or ((col == 4) and (((row > 2) and (row < 6)) or (row == 1)))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'G' pattern using Python while loop<|endoftext|>
8f73b0962a7f71967de46eb94e85e20dfedf64ef12da020e11e554f0df71cf8e
def for_H(): " Upper case Alphabet letter 'H' pattern using Python for loop" for row in range(7): for col in range(5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'H' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_H
SaikumarS2611/ANSPatterns
0
python
def for_H(): " " for row in range(7): for col in range(5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') print()
def for_H(): " " for row in range(7): for col in range(5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'H' pattern using Python for loop<|endoftext|>
e17e7ec0a4eaad6d979ba97525977ec5efd3102150508b0af77c8215c0a3c2d1
def while_H(): " Upper case Alphabet letter 'H' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'H' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_H
SaikumarS2611/ANSPatterns
0
python
def while_H(): " " row = 0 while (row < 7): col = 0 while (col < 5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_H(): " " row = 0 while (row < 7): col = 0 while (col < 5): if (((col % 4) == 0) or (row == 3)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'H' pattern using Python while loop<|endoftext|>
31c7530be66e08026724df46dac36967b3cc871fd253da170b154fd0981b9ff4
def for_I(): " Upper case Alphabet letter 'I' pattern using Python for loop" for row in range(6): for col in range(5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'I' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_I
SaikumarS2611/ANSPatterns
0
python
def for_I(): " " for row in range(6): for col in range(5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') print()
def for_I(): " " for row in range(6): for col in range(5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'I' pattern using Python for loop<|endoftext|>
f43bacbe0e5a4369fcf42d0b34129e911eca59592c2e9d24c71a190a2744d532
def while_I(): " Upper case Alphabet letter 'I' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'I' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_I
SaikumarS2611/ANSPatterns
0
python
def while_I(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_I(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((row in (0, 5)) or (col == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'I' pattern using Python while loop<|endoftext|>
97fd6b9e6a59d85d748048a369bb2a9b7bc501d779100c785e79913575b0343b
def for_J(): " Upper case Alphabet letter 'J' pattern using Python Python for loop" for row in range(6): for col in range(5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'J' pattern using Python Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_J
SaikumarS2611/ANSPatterns
0
python
def for_J(): " " for row in range(6): for col in range(5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') print()
def for_J(): " " for row in range(6): for col in range(5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'J' pattern using Python Python for loop<|endoftext|>
e97ec7a6a8b9626f97422e042506720e860080822d52657b6042abf2fe95c067
def while_J(): " Upper case Alphabet letter 'J' pattern using Python Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'J' pattern using Python Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_J
SaikumarS2611/ANSPatterns
0
python
def while_J(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_J(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((row == 0) or ((col == 2) and (row < 5)) or (((row + col) == 6) and (col < 3)) or ((col == 0) and (row == 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'J' pattern using Python Python while loop<|endoftext|>
5ef910a54222f9a8ca7035a7175ee2b136cbf5daedd66c081030f7b7586de623
def for_K(): " Upper case Alphabet letter 'K' pattern using Python Python for loop" for row in range(6): for col in range(4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'K' pattern using Python Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_K
SaikumarS2611/ANSPatterns
0
python
def for_K(): " " for row in range(6): for col in range(4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()
def for_K(): " " for row in range(6): for col in range(4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'K' pattern using Python Python for loop<|endoftext|>
59bef891bab8f031ae36fd078d73db4ef40b7bcef163a4cd3326e99f4827b1ff
def while_K(): " Upper case Alphabet letter 'K' pattern using Python Python while loop" row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'K' pattern using Python Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_K
SaikumarS2611/ANSPatterns
0
python
def while_K(): " " row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_K(): " " row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or ((row + col) == 3) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'K' pattern using Python Python while loop<|endoftext|>
3a1d026b1f9dd56c4eded03cd1b0b9e4a0a9f58321121ec8aea98be9da688704
def for_L(): " Upper case Alphabet letter 'L' pattern using Python Python for loop" for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'L' pattern using Python Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_L
SaikumarS2611/ANSPatterns
0
python
def for_L(): " " for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()
def for_L(): " " for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'L' pattern using Python Python for loop<|endoftext|>
f26766bad9fd8170994e0c63b1f73cda4fa28c461fa45ef43ddf96ca6d15f157
def while_L(): " Upper case Alphabet letter 'L' pattern using Python Python while loop" for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'L' pattern using Python Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_L
SaikumarS2611/ANSPatterns
0
python
def while_L(): " " for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()
def while_L(): " " for row in range(6): for col in range(4): if ((col == 0) or (row == 5)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'L' pattern using Python Python while loop<|endoftext|>
7a1ef6f2ae5b915718243f8fab915035c2fb4334ad92e3113e047fb8f586c69d
def for_M(): " Upper case Alphabet letter 'M' pattern using Python Python for loop" for row in range(6): for col in range(5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'M' pattern using Python Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_M
SaikumarS2611/ANSPatterns
0
python
def for_M(): " " for row in range(6): for col in range(5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
def for_M(): " " for row in range(6): for col in range(5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'M' pattern using Python Python for loop<|endoftext|>
1127b51ac869901e6ed4cfc2fc60a4512cedaef3e1717f5014535c9e18c76235
def while_M(): " Upper case Alphabet letter 'M' pattern using Python Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'M' pattern using Python Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_M
SaikumarS2611/ANSPatterns
0
python
def while_M(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_M(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((col in (0, 4)) or ((((row - col) == 0) or ((row + col) == 4)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'M' pattern using Python Python while loop<|endoftext|>
2d12608a844e2d4c52176b90d38391f19527ce78760dc55f8e5804fc29d6c5bf
def for_N(): " Upper case Alphabet letter 'N' pattern using Python Python for loop" for row in range(5): for col in range(5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'N' pattern using Python Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_N
SaikumarS2611/ANSPatterns
0
python
def for_N(): " " for row in range(5): for col in range(5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') print()
def for_N(): " " for row in range(5): for col in range(5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'N' pattern using Python Python for loop<|endoftext|>
efaa4043ac40bb767cd1a03a1bfdbf755384218cd4e4bbecce8f384a858d11cc
def while_N(): " Upper case Alphabet letter 'N' pattern using Python Python while loop" row = 0 while (row < 5): col = 0 while (col < 5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'N' pattern using Python Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_N
SaikumarS2611/ANSPatterns
0
python
def while_N(): " " row = 0 while (row < 5): col = 0 while (col < 5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_N(): " " row = 0 while (row < 5): col = 0 while (col < 5): if ((col in (0, 4)) or ((row - col) == 0)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'N' pattern using Python Python while loop<|endoftext|>
24714367f5ab7e20e7afbe2a09f6fbdf927fd3d8ec84bed74520498672c65e8f
def for_O(): " Upper case Alphabet letter 'O' pattern using Python for loop" for row in range(6): for col in range(5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'O' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_O
SaikumarS2611/ANSPatterns
0
python
def for_O(): " " for row in range(6): for col in range(5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') print()
def for_O(): " " for row in range(6): for col in range(5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'O' pattern using Python for loop<|endoftext|>
259fcbef6e97cbed7a86b775452de439d323cc8cf4d6d9175f563be7b5b6f789
def while_O(): " Upper case Alphabet letter 'O' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'O' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_O
SaikumarS2611/ANSPatterns
0
python
def while_O(): " " row = 0 while (row < 6): col = 0 while (col < 5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_O(): " " row = 0 while (row < 6): col = 0 while (col < 5): if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col in (0, 4)) and (row > 0) and (row < 5))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'O' pattern using Python while loop<|endoftext|>
6bd4255483656b37b08da7509fc1f70eb4b159ed06d020379e647580e5adeff4
def for_P(): " Upper case Alphabet letter 'P' pattern using Python for loop" for row in range(6): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'P' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_P
SaikumarS2611/ANSPatterns
0
python
def for_P(): " " for row in range(6): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
def for_P(): " " for row in range(6): for col in range(4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'P' pattern using Python for loop<|endoftext|>
45efbec993d4bc7e976cbc443820727f5873e8574dbfbe5d0ad9235423015990
def while_P(): " Upper case Alphabet letter 'P' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'P' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_P
SaikumarS2611/ANSPatterns
0
python
def while_P(): " " row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_P(): " " row = 0 while (row < 6): col = 0 while (col < 4): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'P' pattern using Python while loop<|endoftext|>
abe031ea51ea0997468b208a7bd10f4eddc87409ce47a8d4ab3cbbe7ff6e8b19
def for_Q(): " Upper case Alphabet letter 'Q' pattern using Python for loop" for row in range(5): for col in range(5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'Q' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_Q
SaikumarS2611/ANSPatterns
0
python
def for_Q(): " " for row in range(5): for col in range(5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') print()
def for_Q(): " " for row in range(5): for col in range(5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'Q' pattern using Python for loop<|endoftext|>
2d423f96ed63158d15395131617b717d2581ecf73603387e9cf49f2902970098
def while_Q(): " Upper case Alphabet letter 'Q' pattern using Python while loop" row = 0 while (row < 5): col = 0 while (col < 5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'Q' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_Q
SaikumarS2611/ANSPatterns
0
python
def while_Q(): " " row = 0 while (row < 5): col = 0 while (col < 5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_Q(): " " row = 0 while (row < 5): col = 0 while (col < 5): if (((col in (0, 4)) and (row > 0) and (row < 4)) or ((row in (0, 4)) and (col > 0) and (col < 4)) or (((col - row) == 0) and (row > 2))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'Q' pattern using Python while loop<|endoftext|>
27ba3a7c55e512b81efd140e6acbb4fd4db877656f61cc9d67e9339a3d2e7b76
def for_R(): " Upper case Alphabet letter 'R' pattern using Python for loop" for row in range(6): for col in range(5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'R' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_R
SaikumarS2611/ANSPatterns
0
python
def for_R(): " " for row in range(6): for col in range(5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()
def for_R(): " " for row in range(6): for col in range(5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'R' pattern using Python for loop<|endoftext|>
fb92d17cd3b46e0c8ca5de687fbdcdc8c38cfd2b2f68146e48ad3e84f8d89c61
def while_R(): " Upper case Alphabet letter 'R' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'R' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_R
SaikumarS2611/ANSPatterns
0
python
def while_R(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_R(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((col == 0) or (((row % 3) == 0) and (col < 3)) or ((col == 3) and ((row % 3) != 0) and (row < 3)) or ((row - col) == 2)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'R' pattern using Python while loop<|endoftext|>
b469c0d6c9cc052b3022ba2bca657fc8cf05ed5b650a49bc6b35612d346b5a34
def for_S(): " Upper case Alphabet letter 'S' pattern using Python for loop" for row in range(7): for col in range(5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'S' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_S
SaikumarS2611/ANSPatterns
0
python
def for_S(): " " for row in range(7): for col in range(5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') print()
def for_S(): " " for row in range(7): for col in range(5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'S' pattern using Python for loop<|endoftext|>
ffac5489c31a2e897f30d9cdb4d168703dc2ac3f7fd8619faf366004d81944b9
def while_S(): " Upper case Alphabet letter 'S' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'S' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_S
SaikumarS2611/ANSPatterns
0
python
def while_S(): " " row = 0 while (row < 7): col = 0 while (col < 5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_S(): " " row = 0 while (row < 7): col = 0 while (col < 5): if ((((row % 3) == 0) and (col > 0) and (col < 4)) or ((col == 0) and ((row % 3) != 0) and (row < 3)) or ((col == 4) and ((row % 3) != 0) and (row > 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'S' pattern using Python while loop<|endoftext|>
61228693ea8d3fe7c9c94dc7718f93d3b9c7e0cb31bebb12c91072eb92e1b2b8
def for_T(): " Upper case Alphabet letter 'T' pattern using Python for loop" for row in range(5): for col in range(3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'T' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_T
SaikumarS2611/ANSPatterns
0
python
def for_T(): " " for row in range(5): for col in range(3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') print()
def for_T(): " " for row in range(5): for col in range(3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'T' pattern using Python for loop<|endoftext|>
ac586c4dc3c7d55d152ba0e053f1c169dae2705e77a3b391ab17e39cb36cbc4a
def while_T(): " Upper case Alphabet letter 'T' pattern using Python while loop" row = 0 while (row < 5): col = 0 while (col < 3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'T' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_T
SaikumarS2611/ANSPatterns
0
python
def while_T(): " " row = 0 while (row < 5): col = 0 while (col < 3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_T(): " " row = 0 while (row < 5): col = 0 while (col < 3): if ((row == 0) or (col == 1)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'T' pattern using Python while loop<|endoftext|>
805c3302069c78982e962380881781ab7c1dd53223ba3957ab818d45f8f0363a
def for_U(): " Upper case Alphabet letter 'U' pattern using Python for loop" for row in range(6): for col in range(5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'U' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_U
SaikumarS2611/ANSPatterns
0
python
def for_U(): " " for row in range(6): for col in range(5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') print()
def for_U(): " " for row in range(6): for col in range(5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'U' pattern using Python for loop<|endoftext|>
4f886e789731025557cf8d827a8ce6314ecbf94ebf286a5a3b8883b909d9ef97
def while_U(): " Upper case Alphabet letter 'U' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'U' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_U
SaikumarS2611/ANSPatterns
0
python
def while_U(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_U(): " " row = 0 while (row < 6): col = 0 while (col < 5): if ((((col % 4) == 0) and (row < 5)) or ((row == 5) and (col > 0) and (col < 4))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'U' pattern using Python while loop<|endoftext|>
b47df7f78ef53ae5f46954319d49b75e0dda6d0c6893d6647bebb564dcf852eb
def for_V(): " Upper case Alphabet letter 'V' pattern using Python for loop" for row in range(7): for col in range(13): if ((row == col) or ((row + col) == 12)): print('*', end='') else: print(' ', end='') print()
Upper case Alphabet letter 'V' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_V
SaikumarS2611/ANSPatterns
0
python
def for_V(): " " for row in range(7): for col in range(13): if ((row == col) or ((row + col) == 12)): print('*', end=) else: print(' ', end=) print()
def for_V(): " " for row in range(7): for col in range(13): if ((row == col) or ((row + col) == 12)): print('*', end=) else: print(' ', end=) print()<|docstring|>Upper case Alphabet letter 'V' pattern using Python for loop<|endoftext|>
f774b4dccae19d8658bd24268e2e49c4a5dd8617524bbd16b59603947484e9b7
def while_V(): " Upper case Alphabet letter 'V' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 13): if ((row == col) or ((row + col) == 12)): print('*', end=' ') else: print(' ', end='') col += 1 print() row += 1
Upper case Alphabet letter 'V' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_V
SaikumarS2611/ANSPatterns
0
python
def while_V(): " " row = 0 while (row < 7): col = 0 while (col < 13): if ((row == col) or ((row + col) == 12)): print('*', end=' ') else: print(' ', end=) col += 1 print() row += 1
def while_V(): " " row = 0 while (row < 7): col = 0 while (col < 13): if ((row == col) or ((row + col) == 12)): print('*', end=' ') else: print(' ', end=) col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'V' pattern using Python while loop<|endoftext|>
dfb56d1a30cabaddce9097fecf5c216ba2862f15199ce0cce511dc0c1a840f5e
def for_W(): " Upper case Alphabet letter 'W' pattern using Python for loop" for i in range(5): for j in range(27): if ((i == j) or (((i > 1) and ((i + j) == 8)) or ((i + j) == 13)) or ((i == 3) and ((i + j) == 11))): print('*', end='') else: print(' ', end='') print()
Upper case Alphabet letter 'W' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_W
SaikumarS2611/ANSPatterns
0
python
def for_W(): " " for i in range(5): for j in range(27): if ((i == j) or (((i > 1) and ((i + j) == 8)) or ((i + j) == 13)) or ((i == 3) and ((i + j) == 11))): print('*', end=) else: print(' ', end=) print()
def for_W(): " " for i in range(5): for j in range(27): if ((i == j) or (((i > 1) and ((i + j) == 8)) or ((i + j) == 13)) or ((i == 3) and ((i + j) == 11))): print('*', end=) else: print(' ', end=) print()<|docstring|>Upper case Alphabet letter 'W' pattern using Python for loop<|endoftext|>
612d41b71805c082690abffd359109410a777ff603544e0764046675bb9f7a19
def while_W(): " Upper case Alphabet letter 'W' pattern using Python while loop" row = 0 while (row < 5): col = 0 while (col < 27): if ((row == col) or ((row > 1) and ((row + col) == 8)) or ((row + col) == 13) or ((row == 3) and ((row + col) == 11))): print('*', end='') else: print(' ', end='') col += 1 print() row += 1
Upper case Alphabet letter 'W' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_W
SaikumarS2611/ANSPatterns
0
python
def while_W(): " " row = 0 while (row < 5): col = 0 while (col < 27): if ((row == col) or ((row > 1) and ((row + col) == 8)) or ((row + col) == 13) or ((row == 3) and ((row + col) == 11))): print('*', end=) else: print(' ', end=) col += 1 print() row += 1
def while_W(): " " row = 0 while (row < 5): col = 0 while (col < 27): if ((row == col) or ((row > 1) and ((row + col) == 8)) or ((row + col) == 13) or ((row == 3) and ((row + col) == 11))): print('*', end=) else: print(' ', end=) col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'W' pattern using Python while loop<|endoftext|>
d9066864a118d81175f3ec80b88ad43906ae30bc5a36edd63d76bfaf9de5a70c
def for_X(): " Upper case Alphabet letter 'X' pattern using Python for loop" for row in range(5): for col in range(6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'X' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_X
SaikumarS2611/ANSPatterns
0
python
def for_X(): " " for row in range(5): for col in range(6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') print()
def for_X(): " " for row in range(5): for col in range(6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'X' pattern using Python for loop<|endoftext|>
4f9201a11531d5066d8bb21a79ede139c829d8961844cc9fe40b2776f5355aed
def while_X(): " Upper case Alphabet letter 'X' pattern using Python while loop" row = 0 while (row < 5): col = 0 while (col < 6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'X' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_X
SaikumarS2611/ANSPatterns
0
python
def while_X(): " " row = 0 while (row < 5): col = 0 while (col < 6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_X(): " " row = 0 while (row < 5): col = 0 while (col < 6): if (((row - col) == 0) or ((row + col) == 4)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'X' pattern using Python while loop<|endoftext|>
ed0a347dbb2612d65fcf79e21d1f435fcc938899bd75f9bfc2d5e2e372519322
def for_Y(): " Upper case Alphabet letter 'Y' pattern using Python for loop" for row in range(7): for col in range(7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'Y' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_Y
SaikumarS2611/ANSPatterns
0
python
def for_Y(): " " for row in range(7): for col in range(7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()
def for_Y(): " " for row in range(7): for col in range(7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'Y' pattern using Python for loop<|endoftext|>
319efd9dc32b56425f07e9f7aa10f92804a7bd7772cb3935b809f408a33c65e3
def while_Y(): " Upper case Alphabet letter 'Y' pattern using Python while loop" row = 0 while (row < 7): col = 0 while (col < 7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'Y' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_Y
SaikumarS2611/ANSPatterns
0
python
def while_Y(): " " row = 0 while (row < 7): col = 0 while (col < 7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_Y(): " " row = 0 while (row < 7): col = 0 while (col < 7): if (((col == 3) and (row > 2)) or ((((row - col) == 0) or ((row + col) == 6)) and (row < 3))): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'Y' pattern using Python while loop<|endoftext|>
022690237bcee5f58a4818449f023d84b73dbad3397b1e357407841baf225192
def for_Z(): " Upper case Alphabet letter 'Z' pattern using Python for loop" for row in range(6): for col in range(6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') print()
Upper case Alphabet letter 'Z' pattern using Python for loop
ANSPatterns/uppercase_alphabets/ualp.py
for_Z
SaikumarS2611/ANSPatterns
0
python
def for_Z(): " " for row in range(6): for col in range(6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') print()
def for_Z(): " " for row in range(6): for col in range(6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') print()<|docstring|>Upper case Alphabet letter 'Z' pattern using Python for loop<|endoftext|>
18706947bc8fea85648396ecef7d19fe70cc2f8a0d835b4687cdd36448a00e82
def while_Z(): " Upper case Alphabet letter 'Z' pattern using Python while loop" row = 0 while (row < 6): col = 0 while (col < 6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
Upper case Alphabet letter 'Z' pattern using Python while loop
ANSPatterns/uppercase_alphabets/ualp.py
while_Z
SaikumarS2611/ANSPatterns
0
python
def while_Z(): " " row = 0 while (row < 6): col = 0 while (col < 6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
def while_Z(): " " row = 0 while (row < 6): col = 0 while (col < 6): if ((row in (0, 5)) or ((row + col) == 5)): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1<|docstring|>Upper case Alphabet letter 'Z' pattern using Python while loop<|endoftext|>
13fa701129d7f1a50b7dd075765c046bb323511075f07a03a9409bafb364f324
def daemonize(self): 'Deamonize class. UNIX double fork mechanism.' try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #1 failed: {0}\n'.format(err)) sys.exit(1) os.chdir('/') os.setsid() os.umask(0) try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #2 failed: {0}\n'.format(err)) sys.exit(1) sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as f: f.write((pid + '\n'))
Deamonize class. UNIX double fork mechanism.
modules/kif/files/kif.py
daemonize
jennyb2911/infrastructure-puppet
1
python
def daemonize(self): try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #1 failed: {0}\n'.format(err)) sys.exit(1) os.chdir('/') os.setsid() os.umask(0) try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #2 failed: {0}\n'.format(err)) sys.exit(1) sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as f: f.write((pid + '\n'))
def daemonize(self): try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #1 failed: {0}\n'.format(err)) sys.exit(1) os.chdir('/') os.setsid() os.umask(0) try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as err: sys.stderr.write('fork #2 failed: {0}\n'.format(err)) sys.exit(1) sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as f: f.write((pid + '\n'))<|docstring|>Deamonize class. UNIX double fork mechanism.<|endoftext|>
08fd4ca027b4fbb087e168ad5445af106093c02c013f70c9922e12c1acbe5f0a
def start(self, args): 'Start the daemon.' try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if pid: message = ('pidfile {0} already exist. ' + 'Daemon already running?\n') sys.stderr.write(message.format(self.pidfile)) sys.exit(1) self.daemonize() self.run(args)
Start the daemon.
modules/kif/files/kif.py
start
jennyb2911/infrastructure-puppet
1
python
def start(self, args): try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if pid: message = ('pidfile {0} already exist. ' + 'Daemon already running?\n') sys.stderr.write(message.format(self.pidfile)) sys.exit(1) self.daemonize() self.run(args)
def start(self, args): try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if pid: message = ('pidfile {0} already exist. ' + 'Daemon already running?\n') sys.stderr.write(message.format(self.pidfile)) sys.exit(1) self.daemonize() self.run(args)<|docstring|>Start the daemon.<|endoftext|>
50d41e4383e0141fd6d74b79db8b444d30368614e7783a711fe2d063bcc60c84
def stop(self): 'Stop the daemon.' try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if (not pid): message = ('pidfile {0} does not exist. ' + 'Daemon not running?\n') sys.stderr.write(message.format(self.pidfile)) return try: while 1: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: e = str(err.args) if (e.find('No such process') > 0): if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print(str(err.args)) sys.exit(1)
Stop the daemon.
modules/kif/files/kif.py
stop
jennyb2911/infrastructure-puppet
1
python
def stop(self): try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if (not pid): message = ('pidfile {0} does not exist. ' + 'Daemon not running?\n') sys.stderr.write(message.format(self.pidfile)) return try: while 1: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: e = str(err.args) if (e.find('No such process') > 0): if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print(str(err.args)) sys.exit(1)
def stop(self): try: with open(self.pidfile, 'r') as pf: pid = int(pf.read().strip()) except IOError: pid = None if (not pid): message = ('pidfile {0} does not exist. ' + 'Daemon not running?\n') sys.stderr.write(message.format(self.pidfile)) return try: while 1: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: e = str(err.args) if (e.find('No such process') > 0): if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print(str(err.args)) sys.exit(1)<|docstring|>Stop the daemon.<|endoftext|>
fa02a2f0e5a5d60699c1b9a991b00aef9570dbbaf012ba5e983d63775b7663e3
def restart(self): 'Restart the daemon.' self.stop() self.start()
Restart the daemon.
modules/kif/files/kif.py
restart
jennyb2911/infrastructure-puppet
1
python
def restart(self): self.stop() self.start()
def restart(self): self.stop() self.start()<|docstring|>Restart the daemon.<|endoftext|>
11cecd60d91e6412d44e2f7fbb4390041c38383ad5f0c23cab023e26ac2d49b2
def run(self): 'You should override this method when you subclass Daemon.\n\n It will be called after the process has been daemonized by\n start() or restart().'
You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().
modules/kif/files/kif.py
run
jennyb2911/infrastructure-puppet
1
python
def run(self): 'You should override this method when you subclass Daemon.\n\n It will be called after the process has been daemonized by\n start() or restart().'
def run(self): 'You should override this method when you subclass Daemon.\n\n It will be called after the process has been daemonized by\n start() or restart().'<|docstring|>You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().<|endoftext|>
ef51dea034adb4b64976c2f8c77106ad63782a762b58905f2441236f14665b83
def log_mean_exp(mtx): '\n Возвращает логарифм среднего по каждому столбцу от экспоненты данной матрицы.\n Вход: Tensor - матрица размера n x k.\n Выход: Tensor, вектор длины n.\n ' (m, _) = torch.max(mtx, dim=1, keepdim=True) outputs = (m + (mtx - m).exp().mean(dim=1, keepdim=True).log()) outputs = outputs.squeeze(1) return outputs
Возвращает логарифм среднего по каждому столбцу от экспоненты данной матрицы. Вход: Tensor - матрица размера n x k. Выход: Tensor, вектор длины n.
zo/log_likelihood.py
log_mean_exp
severilov/zo
1
python
def log_mean_exp(mtx): '\n Возвращает логарифм среднего по каждому столбцу от экспоненты данной матрицы.\n Вход: Tensor - матрица размера n x k.\n Выход: Tensor, вектор длины n.\n ' (m, _) = torch.max(mtx, dim=1, keepdim=True) outputs = (m + (mtx - m).exp().mean(dim=1, keepdim=True).log()) outputs = outputs.squeeze(1) return outputs
def log_mean_exp(mtx): '\n Возвращает логарифм среднего по каждому столбцу от экспоненты данной матрицы.\n Вход: Tensor - матрица размера n x k.\n Выход: Tensor, вектор длины n.\n ' (m, _) = torch.max(mtx, dim=1, keepdim=True) outputs = (m + (mtx - m).exp().mean(dim=1, keepdim=True).log()) outputs = outputs.squeeze(1) return outputs<|docstring|>Возвращает логарифм среднего по каждому столбцу от экспоненты данной матрицы. Вход: Tensor - матрица размера n x k. Выход: Tensor, вектор длины n.<|endoftext|>
6a7a2ea54322a152e6f0bcc0d28ab15da9b9c5ab0ae44b6856cc833ea3b64e73
def log_likelihood(generated_set, validation_set, test_set): '\n Возвращает оценку логарифма правдоподобия модели GAN методом\n Парзеновского окна со стандартным нормальным ядром.\n Вход: generated_set - сэмплы из генеративной модели.\n validation_set - валидационная выборка.\n test_set - тестовая выборка.\n Выход: float - оценка логарифма правдоподобия.\n ' M = generated_set.shape[0] N = validation_set.shape[0] D = generated_set.shape[1] validation_tensor = validation_set.unsqueeze(1).repeat(1, M, 1) test_tensor = test_set.unsqueeze(1).repeat(1, M, 1) generated_tensor = generated_set.unsqueeze(0).repeat(N, 1, 1) sigma_space = np.logspace((- 4), 4, 100) grid_ll = np.zeros_like(sigma_space) for (i, sigma) in enumerate(sigma_space): mtx = ((- ((validation_tensor - generated_tensor) ** 2)) / (2 * (sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * sigma)))) ll = ll_vector.mean().item() grid_ll[i] = ll best_sigma = sigma_space[np.argmax(grid_ll)] mtx = ((- ((test_tensor - generated_tensor) ** 2)) / (2 * (best_sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * best_sigma)))) ll = ll_vector.mean().item() return ll
Возвращает оценку логарифма правдоподобия модели GAN методом Парзеновского окна со стандартным нормальным ядром. Вход: generated_set - сэмплы из генеративной модели. validation_set - валидационная выборка. test_set - тестовая выборка. Выход: float - оценка логарифма правдоподобия.
zo/log_likelihood.py
log_likelihood
severilov/zo
1
python
def log_likelihood(generated_set, validation_set, test_set): '\n Возвращает оценку логарифма правдоподобия модели GAN методом\n Парзеновского окна со стандартным нормальным ядром.\n Вход: generated_set - сэмплы из генеративной модели.\n validation_set - валидационная выборка.\n test_set - тестовая выборка.\n Выход: float - оценка логарифма правдоподобия.\n ' M = generated_set.shape[0] N = validation_set.shape[0] D = generated_set.shape[1] validation_tensor = validation_set.unsqueeze(1).repeat(1, M, 1) test_tensor = test_set.unsqueeze(1).repeat(1, M, 1) generated_tensor = generated_set.unsqueeze(0).repeat(N, 1, 1) sigma_space = np.logspace((- 4), 4, 100) grid_ll = np.zeros_like(sigma_space) for (i, sigma) in enumerate(sigma_space): mtx = ((- ((validation_tensor - generated_tensor) ** 2)) / (2 * (sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * sigma)))) ll = ll_vector.mean().item() grid_ll[i] = ll best_sigma = sigma_space[np.argmax(grid_ll)] mtx = ((- ((test_tensor - generated_tensor) ** 2)) / (2 * (best_sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * best_sigma)))) ll = ll_vector.mean().item() return ll
def log_likelihood(generated_set, validation_set, test_set): '\n Возвращает оценку логарифма правдоподобия модели GAN методом\n Парзеновского окна со стандартным нормальным ядром.\n Вход: generated_set - сэмплы из генеративной модели.\n validation_set - валидационная выборка.\n test_set - тестовая выборка.\n Выход: float - оценка логарифма правдоподобия.\n ' M = generated_set.shape[0] N = validation_set.shape[0] D = generated_set.shape[1] validation_tensor = validation_set.unsqueeze(1).repeat(1, M, 1) test_tensor = test_set.unsqueeze(1).repeat(1, M, 1) generated_tensor = generated_set.unsqueeze(0).repeat(N, 1, 1) sigma_space = np.logspace((- 4), 4, 100) grid_ll = np.zeros_like(sigma_space) for (i, sigma) in enumerate(sigma_space): mtx = ((- ((validation_tensor - generated_tensor) ** 2)) / (2 * (sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * sigma)))) ll = ll_vector.mean().item() grid_ll[i] = ll best_sigma = sigma_space[np.argmax(grid_ll)] mtx = ((- ((test_tensor - generated_tensor) ** 2)) / (2 * (best_sigma ** 2))) mtx = mtx.sum(dim=2) ll_vector = (log_mean_exp(mtx) - (D * np.log((((2 * np.pi) ** 0.5) * best_sigma)))) ll = ll_vector.mean().item() return ll<|docstring|>Возвращает оценку логарифма правдоподобия модели GAN методом Парзеновского окна со стандартным нормальным ядром. Вход: generated_set - сэмплы из генеративной модели. validation_set - валидационная выборка. test_set - тестовая выборка. Выход: float - оценка логарифма правдоподобия.<|endoftext|>
5eea38de7ed8b777023fd4e94c94181a21dda9e2ebd89da1e618bb056b044850
def config_cam(azimuth, elevation, dist, tilt=0): '\n Author: Amit Raj\n Utility function to generate camera location and rotation Vectors \n Parameters:\n azimuth: float\n Azimuth angle in radians\n elevation: float\n Elevation angle in radians\n dist : float\n Distance of viewing sphere\n tilt : float\n In Plane rotation in radians \n Returns:\n location : mathutils.Vector\n Camera location setting\n rotation : mathutils.Vector\n Camera rotation setting\n ' z = (dist * np.sin(elevation)) y = (((- dist) * np.cos(azimuth)) * np.cos(elevation)) x = ((dist * np.sin(azimuth)) * np.cos(elevation)) location = Vector((x, y, z)) xr = ((np.pi / 2) - elevation) yr = tilt zr = azimuth rotation = Vector((xr, yr, zr)) return (location, rotation)
Author: Amit Raj Utility function to generate camera location and rotation Vectors Parameters: azimuth: float Azimuth angle in radians elevation: float Elevation angle in radians dist : float Distance of viewing sphere tilt : float In Plane rotation in radians Returns: location : mathutils.Vector Camera location setting rotation : mathutils.Vector Camera rotation setting
image_generation/render_images_custom.py
config_cam
swarrier246/clevr-dataset-gen
0
python
def config_cam(azimuth, elevation, dist, tilt=0): '\n Author: Amit Raj\n Utility function to generate camera location and rotation Vectors \n Parameters:\n azimuth: float\n Azimuth angle in radians\n elevation: float\n Elevation angle in radians\n dist : float\n Distance of viewing sphere\n tilt : float\n In Plane rotation in radians \n Returns:\n location : mathutils.Vector\n Camera location setting\n rotation : mathutils.Vector\n Camera rotation setting\n ' z = (dist * np.sin(elevation)) y = (((- dist) * np.cos(azimuth)) * np.cos(elevation)) x = ((dist * np.sin(azimuth)) * np.cos(elevation)) location = Vector((x, y, z)) xr = ((np.pi / 2) - elevation) yr = tilt zr = azimuth rotation = Vector((xr, yr, zr)) return (location, rotation)
def config_cam(azimuth, elevation, dist, tilt=0): '\n Author: Amit Raj\n Utility function to generate camera location and rotation Vectors \n Parameters:\n azimuth: float\n Azimuth angle in radians\n elevation: float\n Elevation angle in radians\n dist : float\n Distance of viewing sphere\n tilt : float\n In Plane rotation in radians \n Returns:\n location : mathutils.Vector\n Camera location setting\n rotation : mathutils.Vector\n Camera rotation setting\n ' z = (dist * np.sin(elevation)) y = (((- dist) * np.cos(azimuth)) * np.cos(elevation)) x = ((dist * np.sin(azimuth)) * np.cos(elevation)) location = Vector((x, y, z)) xr = ((np.pi / 2) - elevation) yr = tilt zr = azimuth rotation = Vector((xr, yr, zr)) return (location, rotation)<|docstring|>Author: Amit Raj Utility function to generate camera location and rotation Vectors Parameters: azimuth: float Azimuth angle in radians elevation: float Elevation angle in radians dist : float Distance of viewing sphere tilt : float In Plane rotation in radians Returns: location : mathutils.Vector Camera location setting rotation : mathutils.Vector Camera rotation setting<|endoftext|>
56927aa5ae98c711e11d32427b354548c19547ebca8d070db1975aaafe55d00f
def convert_to_array(matrix_obj): ' Input: 3x3 matrix from mathutils\n Output: Array type, for bpy rotate function\n ' array = np.array(np.vstack([matrix_obj[i] for i in range(len(matrix_obj))])) print(array) return array
Input: 3x3 matrix from mathutils Output: Array type, for bpy rotate function
image_generation/render_images_custom.py
convert_to_array
swarrier246/clevr-dataset-gen
0
python
def convert_to_array(matrix_obj): ' Input: 3x3 matrix from mathutils\n Output: Array type, for bpy rotate function\n ' array = np.array(np.vstack([matrix_obj[i] for i in range(len(matrix_obj))])) print(array) return array
def convert_to_array(matrix_obj): ' Input: 3x3 matrix from mathutils\n Output: Array type, for bpy rotate function\n ' array = np.array(np.vstack([matrix_obj[i] for i in range(len(matrix_obj))])) print(array) return array<|docstring|>Input: 3x3 matrix from mathutils Output: Array type, for bpy rotate function<|endoftext|>
40e5efddb769e345cdaa65b5aeb7019bc7191f9baf8df9628a8fd3805cb3b232
def add_random_objects(scene_struct, num_objects, args, camera): '\n Add random objects to the current blender scene\n ' with open(args.properties_json, 'r') as f: properties = json.load(f) color_name_to_rgba = {} for (name, rgb) in properties['colors'].items(): rgba = ([(float(c) / 255.0) for c in rgb] + [1.0]) color_name_to_rgba[name] = rgba material_mapping = [(v, k) for (k, v) in properties['materials'].items()] object_mapping = [(v, k) for (k, v) in properties['shapes'].items()] leaf_disk = False leaf_properties = properties['shapes'].copy() leaf_properties.pop('sphere') leaf_obj_mapping = [(v, k) for (k, v) in leaf_properties.items()] size_mapping = list(properties['sizes'].items()) print('size mapping: ', size_mapping) shape_color_combos = None if (args.shape_color_combos_json is not None): with open(args.shape_color_combos_json, 'r') as f: shape_color_combos = list(json.load(f).items()) positions = [] objects = [] blender_objects = [] init_rot = 0 (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) "\n WORKFLOW: First select nb of rows - 1 being bottom-most\n For each row, select nb of leaves - each row has a tilt angle that's a function of the row\n For each leaf, select angular position of leaf around z-axis. ensure leaves don't fully overlap\n " nb_rows = random.randint(1, 3) size_map_sorted = sorted(size_mapping, key=(lambda x: x[1])) size_map_sorted.reverse() x = 0.0 y = 0.0 for row in range(nb_rows): nb_leaves_per_row = random.randint(3, 7) for i in range(nb_leaves_per_row): theta = ((math.pi * random.choice(list(np.arange((row * 20), ((row + 1) * 20), 0.5)))) / 180) (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) if (not positions): z = r obj_name_out = str('sphere') obj_name = properties['shapes']['sphere'] else: z = 0.0 if (leaf_disk == True): (obj_name, obj_name_out) = random.choice(leaf_obj_mapping) else: obj_name_out = str('leaf') obj_name = str('leaf') utils.add_object(args.shape_dir, obj_name, r, (x, y, z), theta=theta) obj = bpy.context.object blender_objects.append(obj) positions.append((x, y, r)) print('theta: ', theta, ' for obj: ', obj) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) pixel_coords = utils.get_camera_coords(camera, obj.location) objects.append({'shape': obj_name_out, 'size': size_name, 'material': mat_name_out, '3d_coords': tuple(obj.location), 'rotation': theta, 'pixel_coords': pixel_coords, 'color': color_name}) parent_object = blender_objects[0] bpy.context.object.rotation_mode = 'XYZ' if ((len(positions) > 1) and (obj.type == 'MESH')): obj.select = True parent_object.select = True obj.parent = parent_object obj.matrix_parent_inverse = parent_object.matrix_world.inverted() rot_angle_deg = (360.0 / float((nb_leaves_per_row - 1))) rot_angle = ((3.14159 * rot_angle_deg) / 180) init_rot = rot_angle bpy.context.scene.objects.active = bpy.data.objects[parent_object.name] bpy.context.object.rotation_euler[2] = (bpy.context.object.rotation_euler[2] + rot_angle) parent_object.select = False obj.select = False bpy.ops.object.select_all(action='DESELECT') all_visible = check_visibility(blender_objects, args.min_pixels_per_object) return (objects, blender_objects)
Add random objects to the current blender scene
image_generation/render_images_custom.py
add_random_objects
swarrier246/clevr-dataset-gen
0
python
def add_random_objects(scene_struct, num_objects, args, camera): '\n \n ' with open(args.properties_json, 'r') as f: properties = json.load(f) color_name_to_rgba = {} for (name, rgb) in properties['colors'].items(): rgba = ([(float(c) / 255.0) for c in rgb] + [1.0]) color_name_to_rgba[name] = rgba material_mapping = [(v, k) for (k, v) in properties['materials'].items()] object_mapping = [(v, k) for (k, v) in properties['shapes'].items()] leaf_disk = False leaf_properties = properties['shapes'].copy() leaf_properties.pop('sphere') leaf_obj_mapping = [(v, k) for (k, v) in leaf_properties.items()] size_mapping = list(properties['sizes'].items()) print('size mapping: ', size_mapping) shape_color_combos = None if (args.shape_color_combos_json is not None): with open(args.shape_color_combos_json, 'r') as f: shape_color_combos = list(json.load(f).items()) positions = [] objects = [] blender_objects = [] init_rot = 0 (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) "\n WORKFLOW: First select nb of rows - 1 being bottom-most\n For each row, select nb of leaves - each row has a tilt angle that's a function of the row\n For each leaf, select angular position of leaf around z-axis. ensure leaves don't fully overlap\n " nb_rows = random.randint(1, 3) size_map_sorted = sorted(size_mapping, key=(lambda x: x[1])) size_map_sorted.reverse() x = 0.0 y = 0.0 for row in range(nb_rows): nb_leaves_per_row = random.randint(3, 7) for i in range(nb_leaves_per_row): theta = ((math.pi * random.choice(list(np.arange((row * 20), ((row + 1) * 20), 0.5)))) / 180) (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) if (not positions): z = r obj_name_out = str('sphere') obj_name = properties['shapes']['sphere'] else: z = 0.0 if (leaf_disk == True): (obj_name, obj_name_out) = random.choice(leaf_obj_mapping) else: obj_name_out = str('leaf') obj_name = str('leaf') utils.add_object(args.shape_dir, obj_name, r, (x, y, z), theta=theta) obj = bpy.context.object blender_objects.append(obj) positions.append((x, y, r)) print('theta: ', theta, ' for obj: ', obj) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) pixel_coords = utils.get_camera_coords(camera, obj.location) objects.append({'shape': obj_name_out, 'size': size_name, 'material': mat_name_out, '3d_coords': tuple(obj.location), 'rotation': theta, 'pixel_coords': pixel_coords, 'color': color_name}) parent_object = blender_objects[0] bpy.context.object.rotation_mode = 'XYZ' if ((len(positions) > 1) and (obj.type == 'MESH')): obj.select = True parent_object.select = True obj.parent = parent_object obj.matrix_parent_inverse = parent_object.matrix_world.inverted() rot_angle_deg = (360.0 / float((nb_leaves_per_row - 1))) rot_angle = ((3.14159 * rot_angle_deg) / 180) init_rot = rot_angle bpy.context.scene.objects.active = bpy.data.objects[parent_object.name] bpy.context.object.rotation_euler[2] = (bpy.context.object.rotation_euler[2] + rot_angle) parent_object.select = False obj.select = False bpy.ops.object.select_all(action='DESELECT') all_visible = check_visibility(blender_objects, args.min_pixels_per_object) return (objects, blender_objects)
def add_random_objects(scene_struct, num_objects, args, camera): '\n \n ' with open(args.properties_json, 'r') as f: properties = json.load(f) color_name_to_rgba = {} for (name, rgb) in properties['colors'].items(): rgba = ([(float(c) / 255.0) for c in rgb] + [1.0]) color_name_to_rgba[name] = rgba material_mapping = [(v, k) for (k, v) in properties['materials'].items()] object_mapping = [(v, k) for (k, v) in properties['shapes'].items()] leaf_disk = False leaf_properties = properties['shapes'].copy() leaf_properties.pop('sphere') leaf_obj_mapping = [(v, k) for (k, v) in leaf_properties.items()] size_mapping = list(properties['sizes'].items()) print('size mapping: ', size_mapping) shape_color_combos = None if (args.shape_color_combos_json is not None): with open(args.shape_color_combos_json, 'r') as f: shape_color_combos = list(json.load(f).items()) positions = [] objects = [] blender_objects = [] init_rot = 0 (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) "\n WORKFLOW: First select nb of rows - 1 being bottom-most\n For each row, select nb of leaves - each row has a tilt angle that's a function of the row\n For each leaf, select angular position of leaf around z-axis. ensure leaves don't fully overlap\n " nb_rows = random.randint(1, 3) size_map_sorted = sorted(size_mapping, key=(lambda x: x[1])) size_map_sorted.reverse() x = 0.0 y = 0.0 for row in range(nb_rows): nb_leaves_per_row = random.randint(3, 7) for i in range(nb_leaves_per_row): theta = ((math.pi * random.choice(list(np.arange((row * 20), ((row + 1) * 20), 0.5)))) / 180) (size_name, r) = random.choice(size_mapping) (color_name, rgba) = random.choice(list(color_name_to_rgba.items())) if (not positions): z = r obj_name_out = str('sphere') obj_name = properties['shapes']['sphere'] else: z = 0.0 if (leaf_disk == True): (obj_name, obj_name_out) = random.choice(leaf_obj_mapping) else: obj_name_out = str('leaf') obj_name = str('leaf') utils.add_object(args.shape_dir, obj_name, r, (x, y, z), theta=theta) obj = bpy.context.object blender_objects.append(obj) positions.append((x, y, r)) print('theta: ', theta, ' for obj: ', obj) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) (mat_name, mat_name_out) = random.choice(material_mapping) utils.add_material(mat_name, Color=rgba) pixel_coords = utils.get_camera_coords(camera, obj.location) objects.append({'shape': obj_name_out, 'size': size_name, 'material': mat_name_out, '3d_coords': tuple(obj.location), 'rotation': theta, 'pixel_coords': pixel_coords, 'color': color_name}) parent_object = blender_objects[0] bpy.context.object.rotation_mode = 'XYZ' if ((len(positions) > 1) and (obj.type == 'MESH')): obj.select = True parent_object.select = True obj.parent = parent_object obj.matrix_parent_inverse = parent_object.matrix_world.inverted() rot_angle_deg = (360.0 / float((nb_leaves_per_row - 1))) rot_angle = ((3.14159 * rot_angle_deg) / 180) init_rot = rot_angle bpy.context.scene.objects.active = bpy.data.objects[parent_object.name] bpy.context.object.rotation_euler[2] = (bpy.context.object.rotation_euler[2] + rot_angle) parent_object.select = False obj.select = False bpy.ops.object.select_all(action='DESELECT') all_visible = check_visibility(blender_objects, args.min_pixels_per_object) return (objects, blender_objects)<|docstring|>Add random objects to the current blender scene<|endoftext|>
edd2f9e54e51ba45b197fd362c040615b67aac261e3ca2a25f99f8e275476fe6
def compute_all_relationships(scene_struct, eps=0.2): "\n Computes relationships between all pairs of objects in the scene.\n \n Returns a dictionary mapping string relationship names to lists of lists of\n integers, where output[rel][i] gives a list of object indices that have the\n relationship rel with object i. For example if j is in output['left'][i] then\n object j is left of object i.\n " all_relationships = {} for (name, direction_vec) in scene_struct['directions'].items(): if ((name == 'above') or (name == 'below')): continue all_relationships[name] = [] for (i, obj1) in enumerate(scene_struct['objects']): coords1 = obj1['3d_coords'] related = set() for (j, obj2) in enumerate(scene_struct['objects']): if (obj1 == obj2): continue coords2 = obj2['3d_coords'] diff = [(coords2[k] - coords1[k]) for k in [0, 1, 2]] dot = sum(((diff[k] * direction_vec[k]) for k in [0, 1, 2])) if (dot > eps): related.add(j) all_relationships[name].append(sorted(list(related))) return all_relationships
Computes relationships between all pairs of objects in the scene. Returns a dictionary mapping string relationship names to lists of lists of integers, where output[rel][i] gives a list of object indices that have the relationship rel with object i. For example if j is in output['left'][i] then object j is left of object i.
image_generation/render_images_custom.py
compute_all_relationships
swarrier246/clevr-dataset-gen
0
python
def compute_all_relationships(scene_struct, eps=0.2): "\n Computes relationships between all pairs of objects in the scene.\n \n Returns a dictionary mapping string relationship names to lists of lists of\n integers, where output[rel][i] gives a list of object indices that have the\n relationship rel with object i. For example if j is in output['left'][i] then\n object j is left of object i.\n " all_relationships = {} for (name, direction_vec) in scene_struct['directions'].items(): if ((name == 'above') or (name == 'below')): continue all_relationships[name] = [] for (i, obj1) in enumerate(scene_struct['objects']): coords1 = obj1['3d_coords'] related = set() for (j, obj2) in enumerate(scene_struct['objects']): if (obj1 == obj2): continue coords2 = obj2['3d_coords'] diff = [(coords2[k] - coords1[k]) for k in [0, 1, 2]] dot = sum(((diff[k] * direction_vec[k]) for k in [0, 1, 2])) if (dot > eps): related.add(j) all_relationships[name].append(sorted(list(related))) return all_relationships
def compute_all_relationships(scene_struct, eps=0.2): "\n Computes relationships between all pairs of objects in the scene.\n \n Returns a dictionary mapping string relationship names to lists of lists of\n integers, where output[rel][i] gives a list of object indices that have the\n relationship rel with object i. For example if j is in output['left'][i] then\n object j is left of object i.\n " all_relationships = {} for (name, direction_vec) in scene_struct['directions'].items(): if ((name == 'above') or (name == 'below')): continue all_relationships[name] = [] for (i, obj1) in enumerate(scene_struct['objects']): coords1 = obj1['3d_coords'] related = set() for (j, obj2) in enumerate(scene_struct['objects']): if (obj1 == obj2): continue coords2 = obj2['3d_coords'] diff = [(coords2[k] - coords1[k]) for k in [0, 1, 2]] dot = sum(((diff[k] * direction_vec[k]) for k in [0, 1, 2])) if (dot > eps): related.add(j) all_relationships[name].append(sorted(list(related))) return all_relationships<|docstring|>Computes relationships between all pairs of objects in the scene. Returns a dictionary mapping string relationship names to lists of lists of integers, where output[rel][i] gives a list of object indices that have the relationship rel with object i. For example if j is in output['left'][i] then object j is left of object i.<|endoftext|>
e6beb8d362a000944aa5c0ed440e6988088ad4555a000783d6b332fa8b95a9df
def check_visibility(blender_objects, min_pixels_per_object): '\n Check whether all objects in the scene have some minimum number of visible\n pixels; to accomplish this we assign random (but distinct) colors to all\n objects, and render using no lighting or shading or antialiasing; this\n ensures that each object is just a solid uniform color. We can then count\n the number of pixels of each color in the output image to check the visibility\n of each object.\n\n Returns True if all objects are visible and False otherwise.\n ' (f, path) = tempfile.mkstemp(suffix='.png') object_colors = render_shadeless(blender_objects, path=path) img = bpy.data.images.load(path) p = list(img.pixels) color_count = Counter(((p[i], p[(i + 1)], p[(i + 2)], p[(i + 3)]) for i in range(0, len(p), 4))) os.remove(path) if (len(color_count) != (len(blender_objects) + 1)): return False for (_, count) in color_count.most_common(): if (count < min_pixels_per_object): return False return True
Check whether all objects in the scene have some minimum number of visible pixels; to accomplish this we assign random (but distinct) colors to all objects, and render using no lighting or shading or antialiasing; this ensures that each object is just a solid uniform color. We can then count the number of pixels of each color in the output image to check the visibility of each object. Returns True if all objects are visible and False otherwise.
image_generation/render_images_custom.py
check_visibility
swarrier246/clevr-dataset-gen
0
python
def check_visibility(blender_objects, min_pixels_per_object): '\n Check whether all objects in the scene have some minimum number of visible\n pixels; to accomplish this we assign random (but distinct) colors to all\n objects, and render using no lighting or shading or antialiasing; this\n ensures that each object is just a solid uniform color. We can then count\n the number of pixels of each color in the output image to check the visibility\n of each object.\n\n Returns True if all objects are visible and False otherwise.\n ' (f, path) = tempfile.mkstemp(suffix='.png') object_colors = render_shadeless(blender_objects, path=path) img = bpy.data.images.load(path) p = list(img.pixels) color_count = Counter(((p[i], p[(i + 1)], p[(i + 2)], p[(i + 3)]) for i in range(0, len(p), 4))) os.remove(path) if (len(color_count) != (len(blender_objects) + 1)): return False for (_, count) in color_count.most_common(): if (count < min_pixels_per_object): return False return True
def check_visibility(blender_objects, min_pixels_per_object): '\n Check whether all objects in the scene have some minimum number of visible\n pixels; to accomplish this we assign random (but distinct) colors to all\n objects, and render using no lighting or shading or antialiasing; this\n ensures that each object is just a solid uniform color. We can then count\n the number of pixels of each color in the output image to check the visibility\n of each object.\n\n Returns True if all objects are visible and False otherwise.\n ' (f, path) = tempfile.mkstemp(suffix='.png') object_colors = render_shadeless(blender_objects, path=path) img = bpy.data.images.load(path) p = list(img.pixels) color_count = Counter(((p[i], p[(i + 1)], p[(i + 2)], p[(i + 3)]) for i in range(0, len(p), 4))) os.remove(path) if (len(color_count) != (len(blender_objects) + 1)): return False for (_, count) in color_count.most_common(): if (count < min_pixels_per_object): return False return True<|docstring|>Check whether all objects in the scene have some minimum number of visible pixels; to accomplish this we assign random (but distinct) colors to all objects, and render using no lighting or shading or antialiasing; this ensures that each object is just a solid uniform color. We can then count the number of pixels of each color in the output image to check the visibility of each object. Returns True if all objects are visible and False otherwise.<|endoftext|>
3d520c2ede4b11bf5e3df43a6522910df686127b897cbd1251b85052ffb24479
def render_shadeless(blender_objects, path='flat.png'): '\n Render a version of the scene with shading disabled and unique materials\n assigned to all objects, and return a set of all colors that should be in the\n rendered image. The image itself is written to path. This is used to ensure\n that all objects will be visible in the final rendered scene.\n ' render_args = bpy.context.scene.render old_filepath = render_args.filepath old_engine = render_args.engine old_use_antialiasing = render_args.use_antialiasing render_args.filepath = path render_args.engine = 'BLENDER_RENDER' render_args.use_antialiasing = False utils.set_layer(bpy.data.objects['Lamp_Key'], 2) utils.set_layer(bpy.data.objects['Lamp_Fill'], 2) utils.set_layer(bpy.data.objects['Lamp_Back'], 2) utils.set_layer(bpy.data.objects['Ground'], 2) object_colors = set() old_materials = [] for (i, obj) in enumerate(blender_objects): old_materials.append(obj.data.materials[0]) bpy.ops.material.new() mat = bpy.data.materials['Material'] mat.name = ('Material_%d' % i) while True: (r, g, b) = [random.random() for _ in range(3)] if ((r, g, b) not in object_colors): break object_colors.add((r, g, b)) mat.diffuse_color = [r, g, b] mat.use_shadeless = True obj.data.materials[0] = mat bpy.ops.render.render(write_still=True) for (mat, obj) in zip(old_materials, blender_objects): obj.data.materials[0] = mat utils.set_layer(bpy.data.objects['Lamp_Key'], 0) utils.set_layer(bpy.data.objects['Lamp_Fill'], 0) utils.set_layer(bpy.data.objects['Lamp_Back'], 0) utils.set_layer(bpy.data.objects['Ground'], 0) render_args.filepath = old_filepath render_args.engine = old_engine render_args.use_antialiasing = old_use_antialiasing return object_colors
Render a version of the scene with shading disabled and unique materials assigned to all objects, and return a set of all colors that should be in the rendered image. The image itself is written to path. This is used to ensure that all objects will be visible in the final rendered scene.
image_generation/render_images_custom.py
render_shadeless
swarrier246/clevr-dataset-gen
0
python
def render_shadeless(blender_objects, path='flat.png'): '\n Render a version of the scene with shading disabled and unique materials\n assigned to all objects, and return a set of all colors that should be in the\n rendered image. The image itself is written to path. This is used to ensure\n that all objects will be visible in the final rendered scene.\n ' render_args = bpy.context.scene.render old_filepath = render_args.filepath old_engine = render_args.engine old_use_antialiasing = render_args.use_antialiasing render_args.filepath = path render_args.engine = 'BLENDER_RENDER' render_args.use_antialiasing = False utils.set_layer(bpy.data.objects['Lamp_Key'], 2) utils.set_layer(bpy.data.objects['Lamp_Fill'], 2) utils.set_layer(bpy.data.objects['Lamp_Back'], 2) utils.set_layer(bpy.data.objects['Ground'], 2) object_colors = set() old_materials = [] for (i, obj) in enumerate(blender_objects): old_materials.append(obj.data.materials[0]) bpy.ops.material.new() mat = bpy.data.materials['Material'] mat.name = ('Material_%d' % i) while True: (r, g, b) = [random.random() for _ in range(3)] if ((r, g, b) not in object_colors): break object_colors.add((r, g, b)) mat.diffuse_color = [r, g, b] mat.use_shadeless = True obj.data.materials[0] = mat bpy.ops.render.render(write_still=True) for (mat, obj) in zip(old_materials, blender_objects): obj.data.materials[0] = mat utils.set_layer(bpy.data.objects['Lamp_Key'], 0) utils.set_layer(bpy.data.objects['Lamp_Fill'], 0) utils.set_layer(bpy.data.objects['Lamp_Back'], 0) utils.set_layer(bpy.data.objects['Ground'], 0) render_args.filepath = old_filepath render_args.engine = old_engine render_args.use_antialiasing = old_use_antialiasing return object_colors
def render_shadeless(blender_objects, path='flat.png'): '\n Render a version of the scene with shading disabled and unique materials\n assigned to all objects, and return a set of all colors that should be in the\n rendered image. The image itself is written to path. This is used to ensure\n that all objects will be visible in the final rendered scene.\n ' render_args = bpy.context.scene.render old_filepath = render_args.filepath old_engine = render_args.engine old_use_antialiasing = render_args.use_antialiasing render_args.filepath = path render_args.engine = 'BLENDER_RENDER' render_args.use_antialiasing = False utils.set_layer(bpy.data.objects['Lamp_Key'], 2) utils.set_layer(bpy.data.objects['Lamp_Fill'], 2) utils.set_layer(bpy.data.objects['Lamp_Back'], 2) utils.set_layer(bpy.data.objects['Ground'], 2) object_colors = set() old_materials = [] for (i, obj) in enumerate(blender_objects): old_materials.append(obj.data.materials[0]) bpy.ops.material.new() mat = bpy.data.materials['Material'] mat.name = ('Material_%d' % i) while True: (r, g, b) = [random.random() for _ in range(3)] if ((r, g, b) not in object_colors): break object_colors.add((r, g, b)) mat.diffuse_color = [r, g, b] mat.use_shadeless = True obj.data.materials[0] = mat bpy.ops.render.render(write_still=True) for (mat, obj) in zip(old_materials, blender_objects): obj.data.materials[0] = mat utils.set_layer(bpy.data.objects['Lamp_Key'], 0) utils.set_layer(bpy.data.objects['Lamp_Fill'], 0) utils.set_layer(bpy.data.objects['Lamp_Back'], 0) utils.set_layer(bpy.data.objects['Ground'], 0) render_args.filepath = old_filepath render_args.engine = old_engine render_args.use_antialiasing = old_use_antialiasing return object_colors<|docstring|>Render a version of the scene with shading disabled and unique materials assigned to all objects, and return a set of all colors that should be in the rendered image. The image itself is written to path. This is used to ensure that all objects will be visible in the final rendered scene.<|endoftext|>
3236ba4085ae0b06e4ff0fb885a29282ed47a7ae85ba8fbe17eab8795a6e8353
def minimumTotal(self, triangle): '\n https://shenjie1993.gitbooks.io/leetcode-python/120%20Triangle.html\n\n 典型的动态规划问题,先将问题转化一下,把每一行的数列都左对齐,如下:\n [\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n ]\n 可以看出来,其实上一行到下一行就两个选择,横坐标不变或加一。\n dp[i]表示从底层到这一层的第i个元素所有路径中最小的和。\n 递推关系就是 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]),\n 即下一行与它相邻的两个节点中和比较小的再加上它自己的值。\n\n :type triangle: List[List[int]]\n :rtype: int\n ' n = len(triangle) dp = triangle[(- 1)] for i in range((n - 2), (- 1), (- 1)): for j in range((i + 1)): dp[j] = (triangle[i][j] + min(dp[j], dp[(j + 1)])) return dp[0]
https://shenjie1993.gitbooks.io/leetcode-python/120%20Triangle.html 典型的动态规划问题,先将问题转化一下,把每一行的数列都左对齐,如下: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 可以看出来,其实上一行到下一行就两个选择,横坐标不变或加一。 dp[i]表示从底层到这一层的第i个元素所有路径中最小的和。 递推关系就是 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]), 即下一行与它相邻的两个节点中和比较小的再加上它自己的值。 :type triangle: List[List[int]] :rtype: int
120_triangle.py
minimumTotal
gengwg/leetcode
2
python
def minimumTotal(self, triangle): '\n https://shenjie1993.gitbooks.io/leetcode-python/120%20Triangle.html\n\n 典型的动态规划问题,先将问题转化一下,把每一行的数列都左对齐,如下:\n [\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n ]\n 可以看出来,其实上一行到下一行就两个选择,横坐标不变或加一。\n dp[i]表示从底层到这一层的第i个元素所有路径中最小的和。\n 递推关系就是 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]),\n 即下一行与它相邻的两个节点中和比较小的再加上它自己的值。\n\n :type triangle: List[List[int]]\n :rtype: int\n ' n = len(triangle) dp = triangle[(- 1)] for i in range((n - 2), (- 1), (- 1)): for j in range((i + 1)): dp[j] = (triangle[i][j] + min(dp[j], dp[(j + 1)])) return dp[0]
def minimumTotal(self, triangle): '\n https://shenjie1993.gitbooks.io/leetcode-python/120%20Triangle.html\n\n 典型的动态规划问题,先将问题转化一下,把每一行的数列都左对齐,如下:\n [\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n ]\n 可以看出来,其实上一行到下一行就两个选择,横坐标不变或加一。\n dp[i]表示从底层到这一层的第i个元素所有路径中最小的和。\n 递推关系就是 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]),\n 即下一行与它相邻的两个节点中和比较小的再加上它自己的值。\n\n :type triangle: List[List[int]]\n :rtype: int\n ' n = len(triangle) dp = triangle[(- 1)] for i in range((n - 2), (- 1), (- 1)): for j in range((i + 1)): dp[j] = (triangle[i][j] + min(dp[j], dp[(j + 1)])) return dp[0]<|docstring|>https://shenjie1993.gitbooks.io/leetcode-python/120%20Triangle.html 典型的动态规划问题,先将问题转化一下,把每一行的数列都左对齐,如下: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 可以看出来,其实上一行到下一行就两个选择,横坐标不变或加一。 dp[i]表示从底层到这一层的第i个元素所有路径中最小的和。 递推关系就是 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]), 即下一行与它相邻的两个节点中和比较小的再加上它自己的值。 :type triangle: List[List[int]] :rtype: int<|endoftext|>
dee3bee4467402447b3cc6c3b7a418435f390c639dcd17e96f36bedcde7fe333
def forward(self, sk_feat, im_feat, bs, bi): '\n :param sk_feat: features of sketches. bs * m.\n :param im_feat: features of images. bs * m.\n :param bs: hash codes of sketches. bs * m.\n :param bi: hash codes of images. bs * m.\n :return: loss\n ' return (torch.mean(((self.d(sk_feat, bs) ** 2) + (self.d(im_feat, bi) ** 2))) * self.gamma)
:param sk_feat: features of sketches. bs * m. :param im_feat: features of images. bs * m. :param bs: hash codes of sketches. bs * m. :param bi: hash codes of images. bs * m. :return: loss
src/package/loss/dsh_loss.py
forward
Jiangtong-Li/ZHSIR
8
python
def forward(self, sk_feat, im_feat, bs, bi): '\n :param sk_feat: features of sketches. bs * m.\n :param im_feat: features of images. bs * m.\n :param bs: hash codes of sketches. bs * m.\n :param bi: hash codes of images. bs * m.\n :return: loss\n ' return (torch.mean(((self.d(sk_feat, bs) ** 2) + (self.d(im_feat, bi) ** 2))) * self.gamma)
def forward(self, sk_feat, im_feat, bs, bi): '\n :param sk_feat: features of sketches. bs * m.\n :param im_feat: features of images. bs * m.\n :param bs: hash codes of sketches. bs * m.\n :param bi: hash codes of images. bs * m.\n :return: loss\n ' return (torch.mean(((self.d(sk_feat, bs) ** 2) + (self.d(im_feat, bi) ** 2))) * self.gamma)<|docstring|>:param sk_feat: features of sketches. bs * m. :param im_feat: features of images. bs * m. :param bs: hash codes of sketches. bs * m. :param bi: hash codes of images. bs * m. :return: loss<|endoftext|>
2642e37e0731c0921e6c0f300f1bf1eee5a2fcdf1c5666aaf5cef9b7b96e027f
@nb.vectorize('float64(float64, float64, float64)') def norm_pdf(x, mu, sigma): '\n Return probability density of normal distribution.\n ' z = ((x - mu) / sigma) c = (1.0 / np.sqrt((2 * np.pi))) return ((np.exp(((- 0.5) * (z ** 2))) * c) / sigma)
Return probability density of normal distribution.
numba_stats/stats.py
norm_pdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def norm_pdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) c = (1.0 / np.sqrt((2 * np.pi))) return ((np.exp(((- 0.5) * (z ** 2))) * c) / sigma)
@nb.vectorize('float64(float64, float64, float64)') def norm_pdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) c = (1.0 / np.sqrt((2 * np.pi))) return ((np.exp(((- 0.5) * (z ** 2))) * c) / sigma)<|docstring|>Return probability density of normal distribution.<|endoftext|>
96d57aecada5803e4b120e9a2a522a1d6f9e35a0f2390d397956e882861fa747
@nb.vectorize('float64(float64, float64, float64)') def norm_cdf(x, mu, sigma): '\n Evaluate cumulative distribution function of normal distribution.\n ' z = ((x - mu) / sigma) z *= (1.0 / np.sqrt(2)) return (0.5 * (1.0 + erf(z)))
Evaluate cumulative distribution function of normal distribution.
numba_stats/stats.py
norm_cdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def norm_cdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) z *= (1.0 / np.sqrt(2)) return (0.5 * (1.0 + erf(z)))
@nb.vectorize('float64(float64, float64, float64)') def norm_cdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) z *= (1.0 / np.sqrt(2)) return (0.5 * (1.0 + erf(z)))<|docstring|>Evaluate cumulative distribution function of normal distribution.<|endoftext|>
cc2dd1e2ef46b2b22adffd8f40e048b7f367baad1724eed82904057f99ce048e
@nb.vectorize('float64(float64, float64, float64)') def norm_ppf(p, mu, sigma): '\n Return quantile of normal distribution for given probability.\n ' z = (np.sqrt(2) * erfinv(((2 * p) - 1))) return ((sigma * z) + mu)
Return quantile of normal distribution for given probability.
numba_stats/stats.py
norm_ppf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def norm_ppf(p, mu, sigma): '\n \n ' z = (np.sqrt(2) * erfinv(((2 * p) - 1))) return ((sigma * z) + mu)
@nb.vectorize('float64(float64, float64, float64)') def norm_ppf(p, mu, sigma): '\n \n ' z = (np.sqrt(2) * erfinv(((2 * p) - 1))) return ((sigma * z) + mu)<|docstring|>Return quantile of normal distribution for given probability.<|endoftext|>
5aba5ce6efb5e99ab7441bf13942f10a84926ac58ac4be412f1b6a6b43ecc0f6
@nb.vectorize('float64(intp, float64)') def poisson_pmf(k, mu): '\n Return probability mass for Poisson distribution.\n ' logp = ((xlogy(k, mu) - gammaln((k + 1.0))) - mu) return np.exp(logp)
Return probability mass for Poisson distribution.
numba_stats/stats.py
poisson_pmf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(intp, float64)') def poisson_pmf(k, mu): '\n \n ' logp = ((xlogy(k, mu) - gammaln((k + 1.0))) - mu) return np.exp(logp)
@nb.vectorize('float64(intp, float64)') def poisson_pmf(k, mu): '\n \n ' logp = ((xlogy(k, mu) - gammaln((k + 1.0))) - mu) return np.exp(logp)<|docstring|>Return probability mass for Poisson distribution.<|endoftext|>
e437ca191bc622b37562bda9c6c5846c6a80e5adda6cf6a16c6d7f5d8c85e5ad
@nb.vectorize('float64(intp, float64)') def poisson_cdf(x, mu): '\n Evaluate cumulative distribution function of Poisson distribution.\n ' k = np.floor(x) return pdtr(k, mu)
Evaluate cumulative distribution function of Poisson distribution.
numba_stats/stats.py
poisson_cdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(intp, float64)') def poisson_cdf(x, mu): '\n \n ' k = np.floor(x) return pdtr(k, mu)
@nb.vectorize('float64(intp, float64)') def poisson_cdf(x, mu): '\n \n ' k = np.floor(x) return pdtr(k, mu)<|docstring|>Evaluate cumulative distribution function of Poisson distribution.<|endoftext|>
5731ab5869d85ed93318f848d3b12a821bd23c6a935b91cd37d0ebbd7f8d5ee5
@nb.vectorize('float64(float64, float64, float64)') def expon_pdf(x, mu, sigma): '\n Return probability density of exponential distribution.\n ' z = ((x - mu) / sigma) return (np.exp((- z)) / sigma)
Return probability density of exponential distribution.
numba_stats/stats.py
expon_pdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def expon_pdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) return (np.exp((- z)) / sigma)
@nb.vectorize('float64(float64, float64, float64)') def expon_pdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) return (np.exp((- z)) / sigma)<|docstring|>Return probability density of exponential distribution.<|endoftext|>
21de248762798f310a220372bba66cb43fbac5a118bedc8fe934eda0807ec895
@nb.vectorize('float64(float64, float64, float64)') def expon_cdf(x, mu, sigma): '\n Evaluate cumulative distribution function of exponential distribution.\n ' z = ((x - mu) / sigma) return (- expm1((- z)))
Evaluate cumulative distribution function of exponential distribution.
numba_stats/stats.py
expon_cdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def expon_cdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) return (- expm1((- z)))
@nb.vectorize('float64(float64, float64, float64)') def expon_cdf(x, mu, sigma): '\n \n ' z = ((x - mu) / sigma) return (- expm1((- z)))<|docstring|>Evaluate cumulative distribution function of exponential distribution.<|endoftext|>
f5f8d4c408a6474b038b9a91563d41b4563a5cc2faa184c967938575d6af278c
@nb.vectorize('float64(float64, float64, float64)') def expon_ppf(p, mu, sigma): '\n Return quantile of exponential distribution for given probability.\n ' z = (- log1p((- p))) x = ((z * sigma) + mu) return x
Return quantile of exponential distribution for given probability.
numba_stats/stats.py
expon_ppf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64)') def expon_ppf(p, mu, sigma): '\n \n ' z = (- log1p((- p))) x = ((z * sigma) + mu) return x
@nb.vectorize('float64(float64, float64, float64)') def expon_ppf(p, mu, sigma): '\n \n ' z = (- log1p((- p))) x = ((z * sigma) + mu) return x<|docstring|>Return quantile of exponential distribution for given probability.<|endoftext|>
48322bdd46b1c3838ef714e11118a3d1ed21953a2f3a96b8356611dc8595012b
@nb.vectorize('float64(float64, float64, float64, float64)') def t_pdf(x, df, mu, sigma): "\n Return probability density of student's distribution.\n " z = ((x - mu) / sigma) k = (0.5 * (df + 1)) p = np.exp((gammaln(k) - gammaln((0.5 * df)))) p /= (np.sqrt((df * np.pi)) * ((1 + ((z ** 2) / df)) ** k)) return (p / sigma)
Return probability density of student's distribution.
numba_stats/stats.py
t_pdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64, float64)') def t_pdf(x, df, mu, sigma): "\n \n " z = ((x - mu) / sigma) k = (0.5 * (df + 1)) p = np.exp((gammaln(k) - gammaln((0.5 * df)))) p /= (np.sqrt((df * np.pi)) * ((1 + ((z ** 2) / df)) ** k)) return (p / sigma)
@nb.vectorize('float64(float64, float64, float64, float64)') def t_pdf(x, df, mu, sigma): "\n \n " z = ((x - mu) / sigma) k = (0.5 * (df + 1)) p = np.exp((gammaln(k) - gammaln((0.5 * df)))) p /= (np.sqrt((df * np.pi)) * ((1 + ((z ** 2) / df)) ** k)) return (p / sigma)<|docstring|>Return probability density of student's distribution.<|endoftext|>
4cdf7082e5d73424f2da0140b6616f0d4a3055910c28d7f576f5c000e768ea00
@nb.vectorize('float64(float64, float64, float64, float64)') def t_cdf(x, df, mu, sigma): "\n Return probability density of student's distribution.\n " z = ((x - mu) / sigma) return stdtr(df, z)
Return probability density of student's distribution.
numba_stats/stats.py
t_cdf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64, float64)') def t_cdf(x, df, mu, sigma): "\n \n " z = ((x - mu) / sigma) return stdtr(df, z)
@nb.vectorize('float64(float64, float64, float64, float64)') def t_cdf(x, df, mu, sigma): "\n \n " z = ((x - mu) / sigma) return stdtr(df, z)<|docstring|>Return probability density of student's distribution.<|endoftext|>
74c7d252fba03647c1d98a49803b4009dca8ca875705ffc99da88e97886f2f3c
@nb.vectorize('float64(float64, float64, float64, float64)') def t_ppf(p, df, mu, sigma): "\n Return probability density of student's distribution.\n " if (p == 0): return (- np.inf) elif (p == 1): return np.inf z = stdtrit(df, p) return ((sigma * z) + mu)
Return probability density of student's distribution.
numba_stats/stats.py
t_ppf
chrisburr/numba-stats
0
python
@nb.vectorize('float64(float64, float64, float64, float64)') def t_ppf(p, df, mu, sigma): "\n \n " if (p == 0): return (- np.inf) elif (p == 1): return np.inf z = stdtrit(df, p) return ((sigma * z) + mu)
@nb.vectorize('float64(float64, float64, float64, float64)') def t_ppf(p, df, mu, sigma): "\n \n " if (p == 0): return (- np.inf) elif (p == 1): return np.inf z = stdtrit(df, p) return ((sigma * z) + mu)<|docstring|>Return probability density of student's distribution.<|endoftext|>
da678a55fd2a6051c9cb8f9322639177a4dec3552119f461020841aac3982d39
def main(): 'Go Main Go' nt = network.Table('AWOS') qdict = loadqc() pgconn = get_dbconn('iem', user='nobody') icursor = pgconn.cursor() now12z = datetime.datetime.utcnow() now12z = now12z.replace(hour=12, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) today6z = now12z.replace(hour=6) today0z = now12z.replace(hour=0) yesterday6z = (today6z - datetime.timedelta(days=1)) yesterday12z = (now12z - datetime.timedelta(days=1)) fmt = '%-6s:%-19s: %3s / %3s / %5s / %4s / %2s\n' shef_fn = '/tmp/awos_rtp.shef' out = open(shef_fn, 'w') out.write(('\n\n\n.BR DMX %s Z DH06/TAIRVX/DH12/TAIRVP/PPDRVZ/SFDRVZ/SDIRVZ\n: IOWA AWOS RTP FIRST GUESS PROCESSED BY THE IEM\n: 06Z to 06Z HIGH TEMPERATURE FOR %s\n: 00Z TO 12Z TODAY LOW TEMPERATURE\n: 12Z YESTERDAY TO 12Z TODAY RAINFALL\n: ...BASED ON REPORTED OBS...\n' % (now12z.strftime('%m%d'), yesterday6z.strftime('%d %b %Y').upper()))) highs = {} sql = "SELECT id,\n round(max(tmpf)::numeric,0) as max_tmpf,\n count(tmpf) as obs FROM current_log c, stations t\n WHERE t.iemid = c.iemid and t.network = 'AWOS' and valid >= %s\n and valid < %s\n and tmpf > -99 GROUP by id " args = (yesterday6z, today6z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue highs[row[0]] = row[1] pcpn = {} sql = "\n select id, sum(precip) from\n (select id, extract(hour from valid) as hour,\n max(phour) as precip from current_log c, stations t\n WHERE t.network = 'AWOS' and t.iemid = c.iemid\n and valid >= %s and valid < %s\n GROUP by id, hour) as foo\n GROUP by id\n " args = (yesterday12z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('precip'): continue pcpn[row[0]] = ('%5.2f' % (row[1],)) lows = {} sql = "\n SELECT id, round(min(tmpf)::numeric,0) as min_tmpf,\n count(tmpf) as obs FROM\n current_log c JOIN stations t on (t.iemid = c.iemid)\n WHERE t.network = 'AWOS' and valid >= %s\n and valid < %s and tmpf > -99 GROUP by id\n " args = (today0z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue lows[row[0]] = row[1] ids = list(nt.sts.keys()) ids.sort() for myid in ids: out.write((fmt % (myid, nt.sts[myid]['name'], highs.get(myid, 'M'), lows.get(myid, 'M'), pcpn.get(myid, 'M'), 'M', 'M'))) out.write('.END\n') out.close() cmd = ("/home/ldm/bin/pqinsert -p 'plot ac %s0000 awos_rtp.shef awos_rtp.shef shef' %s" % (now12z.strftime('%Y%m%d'), shef_fn)) subprocess.call(cmd, shell=True) os.unlink(shef_fn)
Go Main Go
scripts/12z/awos_rtp.py
main
trentford/iem
1
python
def main(): nt = network.Table('AWOS') qdict = loadqc() pgconn = get_dbconn('iem', user='nobody') icursor = pgconn.cursor() now12z = datetime.datetime.utcnow() now12z = now12z.replace(hour=12, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) today6z = now12z.replace(hour=6) today0z = now12z.replace(hour=0) yesterday6z = (today6z - datetime.timedelta(days=1)) yesterday12z = (now12z - datetime.timedelta(days=1)) fmt = '%-6s:%-19s: %3s / %3s / %5s / %4s / %2s\n' shef_fn = '/tmp/awos_rtp.shef' out = open(shef_fn, 'w') out.write(('\n\n\n.BR DMX %s Z DH06/TAIRVX/DH12/TAIRVP/PPDRVZ/SFDRVZ/SDIRVZ\n: IOWA AWOS RTP FIRST GUESS PROCESSED BY THE IEM\n: 06Z to 06Z HIGH TEMPERATURE FOR %s\n: 00Z TO 12Z TODAY LOW TEMPERATURE\n: 12Z YESTERDAY TO 12Z TODAY RAINFALL\n: ...BASED ON REPORTED OBS...\n' % (now12z.strftime('%m%d'), yesterday6z.strftime('%d %b %Y').upper()))) highs = {} sql = "SELECT id,\n round(max(tmpf)::numeric,0) as max_tmpf,\n count(tmpf) as obs FROM current_log c, stations t\n WHERE t.iemid = c.iemid and t.network = 'AWOS' and valid >= %s\n and valid < %s\n and tmpf > -99 GROUP by id " args = (yesterday6z, today6z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue highs[row[0]] = row[1] pcpn = {} sql = "\n select id, sum(precip) from\n (select id, extract(hour from valid) as hour,\n max(phour) as precip from current_log c, stations t\n WHERE t.network = 'AWOS' and t.iemid = c.iemid\n and valid >= %s and valid < %s\n GROUP by id, hour) as foo\n GROUP by id\n " args = (yesterday12z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('precip'): continue pcpn[row[0]] = ('%5.2f' % (row[1],)) lows = {} sql = "\n SELECT id, round(min(tmpf)::numeric,0) as min_tmpf,\n count(tmpf) as obs FROM\n current_log c JOIN stations t on (t.iemid = c.iemid)\n WHERE t.network = 'AWOS' and valid >= %s\n and valid < %s and tmpf > -99 GROUP by id\n " args = (today0z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue lows[row[0]] = row[1] ids = list(nt.sts.keys()) ids.sort() for myid in ids: out.write((fmt % (myid, nt.sts[myid]['name'], highs.get(myid, 'M'), lows.get(myid, 'M'), pcpn.get(myid, 'M'), 'M', 'M'))) out.write('.END\n') out.close() cmd = ("/home/ldm/bin/pqinsert -p 'plot ac %s0000 awos_rtp.shef awos_rtp.shef shef' %s" % (now12z.strftime('%Y%m%d'), shef_fn)) subprocess.call(cmd, shell=True) os.unlink(shef_fn)
def main(): nt = network.Table('AWOS') qdict = loadqc() pgconn = get_dbconn('iem', user='nobody') icursor = pgconn.cursor() now12z = datetime.datetime.utcnow() now12z = now12z.replace(hour=12, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) today6z = now12z.replace(hour=6) today0z = now12z.replace(hour=0) yesterday6z = (today6z - datetime.timedelta(days=1)) yesterday12z = (now12z - datetime.timedelta(days=1)) fmt = '%-6s:%-19s: %3s / %3s / %5s / %4s / %2s\n' shef_fn = '/tmp/awos_rtp.shef' out = open(shef_fn, 'w') out.write(('\n\n\n.BR DMX %s Z DH06/TAIRVX/DH12/TAIRVP/PPDRVZ/SFDRVZ/SDIRVZ\n: IOWA AWOS RTP FIRST GUESS PROCESSED BY THE IEM\n: 06Z to 06Z HIGH TEMPERATURE FOR %s\n: 00Z TO 12Z TODAY LOW TEMPERATURE\n: 12Z YESTERDAY TO 12Z TODAY RAINFALL\n: ...BASED ON REPORTED OBS...\n' % (now12z.strftime('%m%d'), yesterday6z.strftime('%d %b %Y').upper()))) highs = {} sql = "SELECT id,\n round(max(tmpf)::numeric,0) as max_tmpf,\n count(tmpf) as obs FROM current_log c, stations t\n WHERE t.iemid = c.iemid and t.network = 'AWOS' and valid >= %s\n and valid < %s\n and tmpf > -99 GROUP by id " args = (yesterday6z, today6z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue highs[row[0]] = row[1] pcpn = {} sql = "\n select id, sum(precip) from\n (select id, extract(hour from valid) as hour,\n max(phour) as precip from current_log c, stations t\n WHERE t.network = 'AWOS' and t.iemid = c.iemid\n and valid >= %s and valid < %s\n GROUP by id, hour) as foo\n GROUP by id\n " args = (yesterday12z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('precip'): continue pcpn[row[0]] = ('%5.2f' % (row[1],)) lows = {} sql = "\n SELECT id, round(min(tmpf)::numeric,0) as min_tmpf,\n count(tmpf) as obs FROM\n current_log c JOIN stations t on (t.iemid = c.iemid)\n WHERE t.network = 'AWOS' and valid >= %s\n and valid < %s and tmpf > -99 GROUP by id\n " args = (today0z, now12z) icursor.execute(sql, args) for row in icursor: if qdict.get(row[0], {}).get('tmpf'): continue lows[row[0]] = row[1] ids = list(nt.sts.keys()) ids.sort() for myid in ids: out.write((fmt % (myid, nt.sts[myid]['name'], highs.get(myid, 'M'), lows.get(myid, 'M'), pcpn.get(myid, 'M'), 'M', 'M'))) out.write('.END\n') out.close() cmd = ("/home/ldm/bin/pqinsert -p 'plot ac %s0000 awos_rtp.shef awos_rtp.shef shef' %s" % (now12z.strftime('%Y%m%d'), shef_fn)) subprocess.call(cmd, shell=True) os.unlink(shef_fn)<|docstring|>Go Main Go<|endoftext|>
6d65e209e9115ba9f407418946ae556769f722a826586d7e48375d9ef1094015
def doc2opt(doc, user_input=True): '\n doc : str, document to parse\n user_input : bool, optional.\n [default: True] for only options requiring user input\n ' RE = (RE_OPT_INPUT if user_input else RE_OPT) return (('--' + i) for i in RE.findall(doc))
doc : str, document to parse user_input : bool, optional. [default: True] for only options requiring user input
.meta/mkcompletion.py
doc2opt
moble/tqdm
22,617
python
def doc2opt(doc, user_input=True): '\n doc : str, document to parse\n user_input : bool, optional.\n [default: True] for only options requiring user input\n ' RE = (RE_OPT_INPUT if user_input else RE_OPT) return (('--' + i) for i in RE.findall(doc))
def doc2opt(doc, user_input=True): '\n doc : str, document to parse\n user_input : bool, optional.\n [default: True] for only options requiring user input\n ' RE = (RE_OPT_INPUT if user_input else RE_OPT) return (('--' + i) for i in RE.findall(doc))<|docstring|>doc : str, document to parse user_input : bool, optional. [default: True] for only options requiring user input<|endoftext|>
647a9581cbbc7c5b6fa509b4f0162e1f5e020777f5a25bc04af9908f39382601
def __init__(self, num_inputs, num_hidden, num_context, num_outputs): '\n Initializes the network.\n\n Args:\n num_inputs (int): Number of neurons in the input layer.\n num_hidden (int): Number of neurons in the hidden layer.\n num_context (int): Number of context units.\n num_outputs (int): Number of output units.\n ' assert (num_hidden >= num_context), 'Context units exceed hidden' self.num_inputs = num_inputs self.num_hidden = num_hidden self.num_context = num_context self.num_outputs = num_outputs self.weights_input = np.random.normal(size=(self.num_hidden, (self.num_inputs + self.num_context))) self.bias_input = np.random.normal(size=(self.num_hidden, 1)) self.weights_hidden = np.random.normal(size=(self.num_outputs, self.num_hidden)) self.bias_hidden = np.random.normal(size=(self.num_outputs, 1))
Initializes the network. Args: num_inputs (int): Number of neurons in the input layer. num_hidden (int): Number of neurons in the hidden layer. num_context (int): Number of context units. num_outputs (int): Number of output units.
recurrent_neural_networks/elman_network.py
__init__
sgalella/RecurrentNeuralNetworks
0
python
def __init__(self, num_inputs, num_hidden, num_context, num_outputs): '\n Initializes the network.\n\n Args:\n num_inputs (int): Number of neurons in the input layer.\n num_hidden (int): Number of neurons in the hidden layer.\n num_context (int): Number of context units.\n num_outputs (int): Number of output units.\n ' assert (num_hidden >= num_context), 'Context units exceed hidden' self.num_inputs = num_inputs self.num_hidden = num_hidden self.num_context = num_context self.num_outputs = num_outputs self.weights_input = np.random.normal(size=(self.num_hidden, (self.num_inputs + self.num_context))) self.bias_input = np.random.normal(size=(self.num_hidden, 1)) self.weights_hidden = np.random.normal(size=(self.num_outputs, self.num_hidden)) self.bias_hidden = np.random.normal(size=(self.num_outputs, 1))
def __init__(self, num_inputs, num_hidden, num_context, num_outputs): '\n Initializes the network.\n\n Args:\n num_inputs (int): Number of neurons in the input layer.\n num_hidden (int): Number of neurons in the hidden layer.\n num_context (int): Number of context units.\n num_outputs (int): Number of output units.\n ' assert (num_hidden >= num_context), 'Context units exceed hidden' self.num_inputs = num_inputs self.num_hidden = num_hidden self.num_context = num_context self.num_outputs = num_outputs self.weights_input = np.random.normal(size=(self.num_hidden, (self.num_inputs + self.num_context))) self.bias_input = np.random.normal(size=(self.num_hidden, 1)) self.weights_hidden = np.random.normal(size=(self.num_outputs, self.num_hidden)) self.bias_hidden = np.random.normal(size=(self.num_outputs, 1))<|docstring|>Initializes the network. Args: num_inputs (int): Number of neurons in the input layer. num_hidden (int): Number of neurons in the hidden layer. num_context (int): Number of context units. num_outputs (int): Number of output units.<|endoftext|>
42bebc9747551d6c02f446f6bba786a56879497d6374a5d2c626095e7e1ac15b
def __repr__(self): 'Visualizes the network parameters when printing' return f'ElmanNetwork(Inputs={self.num_inputs}, Hidden={self.num_hidden}, Contextual={self.num_context}, Outputs={self.num_outputs})'
Visualizes the network parameters when printing
recurrent_neural_networks/elman_network.py
__repr__
sgalella/RecurrentNeuralNetworks
0
python
def __repr__(self): return f'ElmanNetwork(Inputs={self.num_inputs}, Hidden={self.num_hidden}, Contextual={self.num_context}, Outputs={self.num_outputs})'
def __repr__(self): return f'ElmanNetwork(Inputs={self.num_inputs}, Hidden={self.num_hidden}, Contextual={self.num_context}, Outputs={self.num_outputs})'<|docstring|>Visualizes the network parameters when printing<|endoftext|>
e842978103f2b8cbd041b2c567fc99b1355cc4517e9def8be51a0702b2f740f2
def sigmoid(self, a): 'Computes the sigmoid activation on a' return (1 / (1 + np.exp((- a))))
Computes the sigmoid activation on a
recurrent_neural_networks/elman_network.py
sigmoid
sgalella/RecurrentNeuralNetworks
0
python
def sigmoid(self, a): return (1 / (1 + np.exp((- a))))
def sigmoid(self, a): return (1 / (1 + np.exp((- a))))<|docstring|>Computes the sigmoid activation on a<|endoftext|>
b86ffb63c2c46b4d62aebc6a9b14d922c142d5908ed0ebd20bc8953db8084f51
def forward_pass(self, X): '\n Computes the forward pass on the network.\n\n Args:\n X (np.array): Vector containing the inputs and context units.\n ' self.H1 = self.sigmoid((np.dot(self.weights_input, X) + self.bias_input)) self.y_pred = self.sigmoid((np.dot(self.weights_hidden, self.H1) + self.bias_hidden)) if (self.y_pred.shape == (1, 1)): self.y_pred = self.y_pred[0][0] return self.y_pred
Computes the forward pass on the network. Args: X (np.array): Vector containing the inputs and context units.
recurrent_neural_networks/elman_network.py
forward_pass
sgalella/RecurrentNeuralNetworks
0
python
def forward_pass(self, X): '\n Computes the forward pass on the network.\n\n Args:\n X (np.array): Vector containing the inputs and context units.\n ' self.H1 = self.sigmoid((np.dot(self.weights_input, X) + self.bias_input)) self.y_pred = self.sigmoid((np.dot(self.weights_hidden, self.H1) + self.bias_hidden)) if (self.y_pred.shape == (1, 1)): self.y_pred = self.y_pred[0][0] return self.y_pred
def forward_pass(self, X): '\n Computes the forward pass on the network.\n\n Args:\n X (np.array): Vector containing the inputs and context units.\n ' self.H1 = self.sigmoid((np.dot(self.weights_input, X) + self.bias_input)) self.y_pred = self.sigmoid((np.dot(self.weights_hidden, self.H1) + self.bias_hidden)) if (self.y_pred.shape == (1, 1)): self.y_pred = self.y_pred[0][0] return self.y_pred<|docstring|>Computes the forward pass on the network. Args: X (np.array): Vector containing the inputs and context units.<|endoftext|>
1c8801e40a1aef3009d3b92297fa366c814fce67f0e024efc0fce255228fe061
def backpropagation(self, X, y, learning_rate): '\n Computes the backpropagation algorithm in the network.\n\n Args:\n X (np.array): Vector containing the input and context units.\n y (np.array, float): Contains the output prediciton.\n learning_rate (float): Learning rate for upadting weights and biases.\n\n ' error = (self.y_pred - y) delta_output = ((error * self.y_pred) * (1 - self.y_pred)) self.weights_hidden -= (learning_rate * np.dot(delta_output, self.H1.T)) self.bias_hidden -= (learning_rate * delta_output) delta_input = ((np.dot(self.weights_hidden.T, delta_output) * self.H1) * (1 - self.H1)) self.weights_input -= (learning_rate * np.dot(delta_input, X.T)) self.bias_input -= (learning_rate * delta_input)
Computes the backpropagation algorithm in the network. Args: X (np.array): Vector containing the input and context units. y (np.array, float): Contains the output prediciton. learning_rate (float): Learning rate for upadting weights and biases.
recurrent_neural_networks/elman_network.py
backpropagation
sgalella/RecurrentNeuralNetworks
0
python
def backpropagation(self, X, y, learning_rate): '\n Computes the backpropagation algorithm in the network.\n\n Args:\n X (np.array): Vector containing the input and context units.\n y (np.array, float): Contains the output prediciton.\n learning_rate (float): Learning rate for upadting weights and biases.\n\n ' error = (self.y_pred - y) delta_output = ((error * self.y_pred) * (1 - self.y_pred)) self.weights_hidden -= (learning_rate * np.dot(delta_output, self.H1.T)) self.bias_hidden -= (learning_rate * delta_output) delta_input = ((np.dot(self.weights_hidden.T, delta_output) * self.H1) * (1 - self.H1)) self.weights_input -= (learning_rate * np.dot(delta_input, X.T)) self.bias_input -= (learning_rate * delta_input)
def backpropagation(self, X, y, learning_rate): '\n Computes the backpropagation algorithm in the network.\n\n Args:\n X (np.array): Vector containing the input and context units.\n y (np.array, float): Contains the output prediciton.\n learning_rate (float): Learning rate for upadting weights and biases.\n\n ' error = (self.y_pred - y) delta_output = ((error * self.y_pred) * (1 - self.y_pred)) self.weights_hidden -= (learning_rate * np.dot(delta_output, self.H1.T)) self.bias_hidden -= (learning_rate * delta_output) delta_input = ((np.dot(self.weights_hidden.T, delta_output) * self.H1) * (1 - self.H1)) self.weights_input -= (learning_rate * np.dot(delta_input, X.T)) self.bias_input -= (learning_rate * delta_input)<|docstring|>Computes the backpropagation algorithm in the network. Args: X (np.array): Vector containing the input and context units. y (np.array, float): Contains the output prediciton. learning_rate (float): Learning rate for upadting weights and biases.<|endoftext|>
f7bdb97b2b12743198976455f6682664fdb0963263add123d99ed1d2d32e6bcf
def train(self, inputs, outputs, learning_rate, passes): '\n Trains the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n learning_rate (float): Learning rate for upadting weights and biases.\n passes (int): Number of epochs.\n\n ' for _ in tqdm(range(passes)): X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for (x, y) in zip(inputs, outputs): x = x.reshape(self.num_inputs, 1) y = y.reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) self.backpropagation(X, y, learning_rate) X[self.num_inputs:] = self.H1
Trains the network. Args; inputs (np.array): Vector containing the input units at each time step. outputs (np.arary): Vector containing the solutions for the inputs. learning_rate (float): Learning rate for upadting weights and biases. passes (int): Number of epochs.
recurrent_neural_networks/elman_network.py
train
sgalella/RecurrentNeuralNetworks
0
python
def train(self, inputs, outputs, learning_rate, passes): '\n Trains the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n learning_rate (float): Learning rate for upadting weights and biases.\n passes (int): Number of epochs.\n\n ' for _ in tqdm(range(passes)): X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for (x, y) in zip(inputs, outputs): x = x.reshape(self.num_inputs, 1) y = y.reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) self.backpropagation(X, y, learning_rate) X[self.num_inputs:] = self.H1
def train(self, inputs, outputs, learning_rate, passes): '\n Trains the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n learning_rate (float): Learning rate for upadting weights and biases.\n passes (int): Number of epochs.\n\n ' for _ in tqdm(range(passes)): X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for (x, y) in zip(inputs, outputs): x = x.reshape(self.num_inputs, 1) y = y.reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) self.backpropagation(X, y, learning_rate) X[self.num_inputs:] = self.H1<|docstring|>Trains the network. Args; inputs (np.array): Vector containing the input units at each time step. outputs (np.arary): Vector containing the solutions for the inputs. learning_rate (float): Learning rate for upadting weights and biases. passes (int): Number of epochs.<|endoftext|>
56c4085bddad60ed41001089b9473d9cae707f4339569b678da32f84266621f1
def predict(self, inputs, outputs): '\n Tests the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n ' squared_error = np.zeros((1, len(outputs))) X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for i in range(len(outputs)): x = inputs[i].reshape(self.num_inputs, 1) y = outputs[i].reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) X[self.num_inputs:] = self.H1 squared_error[(0, i)] = ((self.y_pred - y) ** 2) return squared_error
Tests the network. Args; inputs (np.array): Vector containing the input units at each time step. outputs (np.arary): Vector containing the solutions for the inputs.
recurrent_neural_networks/elman_network.py
predict
sgalella/RecurrentNeuralNetworks
0
python
def predict(self, inputs, outputs): '\n Tests the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n ' squared_error = np.zeros((1, len(outputs))) X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for i in range(len(outputs)): x = inputs[i].reshape(self.num_inputs, 1) y = outputs[i].reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) X[self.num_inputs:] = self.H1 squared_error[(0, i)] = ((self.y_pred - y) ** 2) return squared_error
def predict(self, inputs, outputs): '\n Tests the network.\n\n Args;\n inputs (np.array): Vector containing the input units at each time step.\n outputs (np.arary): Vector containing the solutions for the inputs.\n ' squared_error = np.zeros((1, len(outputs))) X = (0.5 * np.ones(((self.num_inputs + self.num_context), 1))) for i in range(len(outputs)): x = inputs[i].reshape(self.num_inputs, 1) y = outputs[i].reshape(self.num_outputs, 1) X[:self.num_inputs] = x self.forward_pass(X) X[self.num_inputs:] = self.H1 squared_error[(0, i)] = ((self.y_pred - y) ** 2) return squared_error<|docstring|>Tests the network. Args; inputs (np.array): Vector containing the input units at each time step. outputs (np.arary): Vector containing the solutions for the inputs.<|endoftext|>
cadb534bf149809497317f70eb5cc596a5d4f0b37894b5ca6e9f81a633b09815
def __init__(self, description=None, domain_names=None, ip=None): 'Constructor for the HostEntry class' self.description = description self.domain_names = domain_names self.ip = ip
Constructor for the HostEntry class
cohesity_management_sdk/models/host_entry.py
__init__
nick6655/management-sdk-python
18
python
def __init__(self, description=None, domain_names=None, ip=None): self.description = description self.domain_names = domain_names self.ip = ip
def __init__(self, description=None, domain_names=None, ip=None): self.description = description self.domain_names = domain_names self.ip = ip<|docstring|>Constructor for the HostEntry class<|endoftext|>
f73ac23a52dfc7ed25ef6f3581db1c06c5b71dc0a135969971362ec19ff7c38d
@classmethod def from_dictionary(cls, dictionary): "Creates an instance of this model from a dictionary\n\n Args:\n dictionary (dictionary): A dictionary representation of the object as\n obtained from the deserialization of the server's response. The keys\n MUST match property names in the API description.\n\n Returns:\n object: An instance of this structure class.\n\n " if (dictionary is None): return None description = dictionary.get('description') domain_names = dictionary.get('domainNames') ip = dictionary.get('ip') return cls(description, domain_names, ip)
Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.
cohesity_management_sdk/models/host_entry.py
from_dictionary
nick6655/management-sdk-python
18
python
@classmethod def from_dictionary(cls, dictionary): "Creates an instance of this model from a dictionary\n\n Args:\n dictionary (dictionary): A dictionary representation of the object as\n obtained from the deserialization of the server's response. The keys\n MUST match property names in the API description.\n\n Returns:\n object: An instance of this structure class.\n\n " if (dictionary is None): return None description = dictionary.get('description') domain_names = dictionary.get('domainNames') ip = dictionary.get('ip') return cls(description, domain_names, ip)
@classmethod def from_dictionary(cls, dictionary): "Creates an instance of this model from a dictionary\n\n Args:\n dictionary (dictionary): A dictionary representation of the object as\n obtained from the deserialization of the server's response. The keys\n MUST match property names in the API description.\n\n Returns:\n object: An instance of this structure class.\n\n " if (dictionary is None): return None description = dictionary.get('description') domain_names = dictionary.get('domainNames') ip = dictionary.get('ip') return cls(description, domain_names, ip)<|docstring|>Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.<|endoftext|>
11c1fd20e556c2fa9d3e1cf22830d5db785803e86bd72c529e33ffc16df220fc
def __init__(self, th_ratio: float, dur_multi: float, logger: Logger=NULL_LOGGER): 'Spectrogram based analysis method. This method looks at features of 2 adjacent timesteps and\n removes segments, for which the difference is small, thus reducing redundance in the signal.\n This method will remove silence and prolongations of sounds, syllables, words, or phrases.\n\n Args:\n th_ratio (float): Threshold ratio: greater value = more aggresive cuts\n dur_multi (float): Duration multiplier of segments selected for removal\n logger (Logger, optional): Logger for messages. Defaults to NULL_LOGGER.\n ' super().__init__('Spectrogram Analysis', [AnalysisDomain.AUDIO], logger) self.th_ratio = th_ratio self.dur_multi = dur_multi self.logger = logger
Spectrogram based analysis method. This method looks at features of 2 adjacent timesteps and removes segments, for which the difference is small, thus reducing redundance in the signal. This method will remove silence and prolongations of sounds, syllables, words, or phrases. Args: th_ratio (float): Threshold ratio: greater value = more aggresive cuts dur_multi (float): Duration multiplier of segments selected for removal logger (Logger, optional): Logger for messages. Defaults to NULL_LOGGER.
src/speechless/processing/analysis/spectrogram.py
__init__
Exepp/SpeechLess
1
python
def __init__(self, th_ratio: float, dur_multi: float, logger: Logger=NULL_LOGGER): 'Spectrogram based analysis method. This method looks at features of 2 adjacent timesteps and\n removes segments, for which the difference is small, thus reducing redundance in the signal.\n This method will remove silence and prolongations of sounds, syllables, words, or phrases.\n\n Args:\n th_ratio (float): Threshold ratio: greater value = more aggresive cuts\n dur_multi (float): Duration multiplier of segments selected for removal\n logger (Logger, optional): Logger for messages. Defaults to NULL_LOGGER.\n ' super().__init__('Spectrogram Analysis', [AnalysisDomain.AUDIO], logger) self.th_ratio = th_ratio self.dur_multi = dur_multi self.logger = logger
def __init__(self, th_ratio: float, dur_multi: float, logger: Logger=NULL_LOGGER): 'Spectrogram based analysis method. This method looks at features of 2 adjacent timesteps and\n removes segments, for which the difference is small, thus reducing redundance in the signal.\n This method will remove silence and prolongations of sounds, syllables, words, or phrases.\n\n Args:\n th_ratio (float): Threshold ratio: greater value = more aggresive cuts\n dur_multi (float): Duration multiplier of segments selected for removal\n logger (Logger, optional): Logger for messages. Defaults to NULL_LOGGER.\n ' super().__init__('Spectrogram Analysis', [AnalysisDomain.AUDIO], logger) self.th_ratio = th_ratio self.dur_multi = dur_multi self.logger = logger<|docstring|>Spectrogram based analysis method. This method looks at features of 2 adjacent timesteps and removes segments, for which the difference is small, thus reducing redundance in the signal. This method will remove silence and prolongations of sounds, syllables, words, or phrases. Args: th_ratio (float): Threshold ratio: greater value = more aggresive cuts dur_multi (float): Duration multiplier of segments selected for removal logger (Logger, optional): Logger for messages. Defaults to NULL_LOGGER.<|endoftext|>
05d483014b1872aada5658b1a9317d9befb5a1146950fd4e357168919b49376f
@staticmethod def setup_arg_parser(parser: ArgumentParser) -> ArgumentParser: 'Sets up a CLI argument parser for this submodule\n\n Returns:\n ArgumentParser: Configured parser\n ' parser.add_argument('-tr', f'--{CLI.ARG_TH_RATIO}', help='Threshold ratio: greater value = more aggresive cuts', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_TH_RATIO]) parser.add_argument('-m', f'--{CLI.ARG_DUR_MULTI}', help='Duration multiplier of segments selected for removal', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_DUR_MULTI]) parser.set_defaults(**{ARG_PREPARE_METHOD_FN: CLI.prepare_method})
Sets up a CLI argument parser for this submodule Returns: ArgumentParser: Configured parser
src/speechless/processing/analysis/spectrogram.py
setup_arg_parser
Exepp/SpeechLess
1
python
@staticmethod def setup_arg_parser(parser: ArgumentParser) -> ArgumentParser: 'Sets up a CLI argument parser for this submodule\n\n Returns:\n ArgumentParser: Configured parser\n ' parser.add_argument('-tr', f'--{CLI.ARG_TH_RATIO}', help='Threshold ratio: greater value = more aggresive cuts', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_TH_RATIO]) parser.add_argument('-m', f'--{CLI.ARG_DUR_MULTI}', help='Duration multiplier of segments selected for removal', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_DUR_MULTI]) parser.set_defaults(**{ARG_PREPARE_METHOD_FN: CLI.prepare_method})
@staticmethod def setup_arg_parser(parser: ArgumentParser) -> ArgumentParser: 'Sets up a CLI argument parser for this submodule\n\n Returns:\n ArgumentParser: Configured parser\n ' parser.add_argument('-tr', f'--{CLI.ARG_TH_RATIO}', help='Threshold ratio: greater value = more aggresive cuts', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_TH_RATIO]) parser.add_argument('-m', f'--{CLI.ARG_DUR_MULTI}', help='Duration multiplier of segments selected for removal', type=float, action='store', default=CLI.DEFAULT_ARGS[CLI.ARG_DUR_MULTI]) parser.set_defaults(**{ARG_PREPARE_METHOD_FN: CLI.prepare_method})<|docstring|>Sets up a CLI argument parser for this submodule Returns: ArgumentParser: Configured parser<|endoftext|>
a21b09ac46902489a5691409a1d9fe5b30c57ab3622c9354e0e484592842c5df
def list(self, resource_group_name, account_name, **kwargs): 'List snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either SnapshotPoliciesList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.netapp.models.SnapshotPoliciesList]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('SnapshotPoliciesList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
List snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SnapshotPoliciesList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.netapp.models.SnapshotPoliciesList] :raises: ~azure.core.exceptions.HttpResponseError
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
list
casperlehmann/azure-sdk-for-python
1
python
def list(self, resource_group_name, account_name, **kwargs): 'List snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either SnapshotPoliciesList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.netapp.models.SnapshotPoliciesList]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('SnapshotPoliciesList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
def list(self, resource_group_name, account_name, **kwargs): 'List snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either SnapshotPoliciesList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.netapp.models.SnapshotPoliciesList]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('SnapshotPoliciesList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)<|docstring|>List snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SnapshotPoliciesList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.netapp.models.SnapshotPoliciesList] :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
6dad3b267b64d48c6b63a99325c8197af49f06ffdea9fd7d8899bd6d3054b840
def get(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get a snapshot Policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.get.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Get a snapshot Policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
get
casperlehmann/azure-sdk-for-python
1
python
def get(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get a snapshot Policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.get.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
def get(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get a snapshot Policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.get.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Get a snapshot Policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
aa2135dc6f7aff20accf5040dbed1f5fac52313330393af58bf51fe28514cb6c
def create(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Create a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicy\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.create.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicy') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200, 201]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if (response.status_code == 200): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if (response.status_code == 201): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Create a snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :param body: Snapshot policy object supplied in the body of the operation. :type body: ~azure.mgmt.netapp.models.SnapshotPolicy :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
create
casperlehmann/azure-sdk-for-python
1
python
def create(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Create a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicy\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.create.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicy') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200, 201]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if (response.status_code == 200): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if (response.status_code == 201): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
def create(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Create a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicy\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.create.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicy') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200, 201]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if (response.status_code == 200): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if (response.status_code == 201): deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Create a snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :param body: Snapshot policy object supplied in the body of the operation. :type body: ~azure.mgmt.netapp.models.SnapshotPolicy :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
71b2a6c5799ddbfd324bd5118f366aa9c2060a58ba97296cc7e688314684904a
def update(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Patch a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicyPatch\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.update.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicyPatch') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Patch a snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :param body: Snapshot policy object supplied in the body of the operation. :type body: ~azure.mgmt.netapp.models.SnapshotPolicyPatch :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
update
casperlehmann/azure-sdk-for-python
1
python
def update(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Patch a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicyPatch\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.update.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicyPatch') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
def update(self, resource_group_name, account_name, snapshot_policy_name, body, **kwargs): 'Patch a snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :param body: Snapshot policy object supplied in the body of the operation.\n :type body: ~azure.mgmt.netapp.models.SnapshotPolicyPatch\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicy, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' content_type = kwargs.pop('content_type', 'application/json') accept = 'application/json' url = self.update.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str') header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(body, 'SnapshotPolicyPatch') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Patch a snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :param body: Snapshot policy object supplied in the body of the operation. :type body: ~azure.mgmt.netapp.models.SnapshotPolicyPatch :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicy, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicy :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
9e1e2c3f05586208237a2f62b690e3201916fd96c217aa4c1735fbd4da343082
def begin_delete(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Delete snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :keyword str continuation_token: A continuation token to restart a poller from a saved state.\n :keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n :paramtype polling: bool or ~azure.core.polling.PollingMethod\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n :return: An instance of LROPoller that returns either None or the result of cls(response)\n :rtype: ~azure.core.polling.LROPoller[None]\n :raises ~azure.core.exceptions.HttpResponseError:\n ' polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop('polling_interval', self._config.polling_interval) cont_token = kwargs.pop('continuation_token', None) if (cont_token is None): raw_result = self._delete_initial(resource_group_name=resource_group_name, account_name=account_name, snapshot_policy_name=snapshot_policy_name, cls=(lambda x, y, z: x), **kwargs) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} if (polling is True): polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif (polling is False): polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token(polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
Delete snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError:
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
begin_delete
casperlehmann/azure-sdk-for-python
1
python
def begin_delete(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Delete snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :keyword str continuation_token: A continuation token to restart a poller from a saved state.\n :keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n :paramtype polling: bool or ~azure.core.polling.PollingMethod\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n :return: An instance of LROPoller that returns either None or the result of cls(response)\n :rtype: ~azure.core.polling.LROPoller[None]\n :raises ~azure.core.exceptions.HttpResponseError:\n ' polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop('polling_interval', self._config.polling_interval) cont_token = kwargs.pop('continuation_token', None) if (cont_token is None): raw_result = self._delete_initial(resource_group_name=resource_group_name, account_name=account_name, snapshot_policy_name=snapshot_policy_name, cls=(lambda x, y, z: x), **kwargs) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} if (polling is True): polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif (polling is False): polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token(polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
def begin_delete(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Delete snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :keyword str continuation_token: A continuation token to restart a poller from a saved state.\n :keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n :paramtype polling: bool or ~azure.core.polling.PollingMethod\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n :return: An instance of LROPoller that returns either None or the result of cls(response)\n :rtype: ~azure.core.polling.LROPoller[None]\n :raises ~azure.core.exceptions.HttpResponseError:\n ' polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop('polling_interval', self._config.polling_interval) cont_token = kwargs.pop('continuation_token', None) if (cont_token is None): raw_result = self._delete_initial(resource_group_name=resource_group_name, account_name=account_name, snapshot_policy_name=snapshot_policy_name, cls=(lambda x, y, z: x), **kwargs) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} if (polling is True): polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif (polling is False): polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token(polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method)<|docstring|>Delete snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError:<|endoftext|>
9e0db87b8dee5e80a4f311fc86870ecb9fc0b70da70a5345044acb9231f654af
def list_volumes(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get volumes associated with snapshot policy.\n\n Get volumes associated with snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicyVolumeList, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicyVolumeList\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.list_volumes.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicyVolumeList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Get volumes associated with snapshot policy. Get volumes associated with snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicyVolumeList, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicyVolumeList :raises: ~azure.core.exceptions.HttpResponseError
sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_snapshot_policies_operations.py
list_volumes
casperlehmann/azure-sdk-for-python
1
python
def list_volumes(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get volumes associated with snapshot policy.\n\n Get volumes associated with snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicyVolumeList, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicyVolumeList\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.list_volumes.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicyVolumeList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
def list_volumes(self, resource_group_name, account_name, snapshot_policy_name, **kwargs): 'Get volumes associated with snapshot policy.\n\n Get volumes associated with snapshot policy.\n\n :param resource_group_name: The name of the resource group.\n :type resource_group_name: str\n :param account_name: The name of the NetApp account.\n :type account_name: str\n :param snapshot_policy_name: The name of the snapshot policy target.\n :type snapshot_policy_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: SnapshotPolicyVolumeList, or the result of cls(response)\n :rtype: ~azure.mgmt.netapp.models.SnapshotPolicyVolumeList\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-08-01' accept = 'application/json' url = self.list_volumes.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url('account_name', account_name, 'str'), 'snapshotPolicyName': self._serialize.url('snapshot_policy_name', snapshot_policy_name, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('SnapshotPolicyVolumeList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Get volumes associated with snapshot policy. Get volumes associated with snapshot policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the NetApp account. :type account_name: str :param snapshot_policy_name: The name of the snapshot policy target. :type snapshot_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SnapshotPolicyVolumeList, or the result of cls(response) :rtype: ~azure.mgmt.netapp.models.SnapshotPolicyVolumeList :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
04a64dee480ba6ebb5aefa7dcf4927d07f0793aca63921d2837e8b7048ad5fc2
@classmethod def parse_json(cls, body): '\n Get an instance from JSON string\n ' json_dict = json.loads(body) if ('message' in json_dict): text = json_dict['message']['result']['translatedText'] source = json_dict['message']['result']['srcLangType'] return Response(text=text, source=source) else: return Response(code=json_dict.get('errorCode'), message=json_dict.get('errorMessage'))
Get an instance from JSON string
papago/response.py
parse_json
anktdshmkh/papago_Example
27
python
@classmethod def parse_json(cls, body): '\n \n ' json_dict = json.loads(body) if ('message' in json_dict): text = json_dict['message']['result']['translatedText'] source = json_dict['message']['result']['srcLangType'] return Response(text=text, source=source) else: return Response(code=json_dict.get('errorCode'), message=json_dict.get('errorMessage'))
@classmethod def parse_json(cls, body): '\n \n ' json_dict = json.loads(body) if ('message' in json_dict): text = json_dict['message']['result']['translatedText'] source = json_dict['message']['result']['srcLangType'] return Response(text=text, source=source) else: return Response(code=json_dict.get('errorCode'), message=json_dict.get('errorMessage'))<|docstring|>Get an instance from JSON string<|endoftext|>
a5a6dd87d9d8d34841305bef2cd623158fe0c4eb139a5dea7ab7608a6c542572
def test_initial_state() -> None: 'It should set the initial state.' subject = CommandStore() assert (subject.state == CommandState(queue_status=QueueStatus.IMPLICITLY_ACTIVE, is_hardware_stopped=False, is_door_blocking=False, run_result=None, running_command_id=None, queued_command_ids=OrderedSet(), all_command_ids=[], commands_by_id=OrderedDict(), errors_by_id={}))
It should set the initial state.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_initial_state
Opentrons/labware
2
python
def test_initial_state() -> None: subject = CommandStore() assert (subject.state == CommandState(queue_status=QueueStatus.IMPLICITLY_ACTIVE, is_hardware_stopped=False, is_door_blocking=False, run_result=None, running_command_id=None, queued_command_ids=OrderedSet(), all_command_ids=[], commands_by_id=OrderedDict(), errors_by_id={}))
def test_initial_state() -> None: subject = CommandStore() assert (subject.state == CommandState(queue_status=QueueStatus.IMPLICITLY_ACTIVE, is_hardware_stopped=False, is_door_blocking=False, run_result=None, running_command_id=None, queued_command_ids=OrderedSet(), all_command_ids=[], commands_by_id=OrderedDict(), errors_by_id={}))<|docstring|>It should set the initial state.<|endoftext|>
3ec85301c7a7a04c995e87c316b60ccc89a702274a6b5516587fc928c1e5bc80
@pytest.mark.parametrize(QueueCommandSpec._fields, [QueueCommandSpec(command_request=commands.AspirateCreate(params=commands.AspirateParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Aspirate), QueueCommandSpec(command_request=commands.DispenseCreate(params=commands.DispenseParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Dispense), QueueCommandSpec(command_request=commands.DropTipCreate(params=commands.DropTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.DropTip), QueueCommandSpec(command_request=commands.LoadLabwareCreate(params=commands.LoadLabwareParams(location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1), loadName='load-name', namespace='namespace', version=42)), expected_cls=commands.LoadLabware), QueueCommandSpec(command_request=commands.LoadPipetteCreate(params=commands.LoadPipetteParams(mount=MountType.LEFT, pipetteName=PipetteName.P300_SINGLE)), expected_cls=commands.LoadPipette), QueueCommandSpec(command_request=commands.PickUpTipCreate(params=commands.PickUpTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.PickUpTip), QueueCommandSpec(command_request=commands.MoveToWellCreate(params=commands.MoveToWellParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.MoveToWell), QueueCommandSpec(command_request=commands.PauseCreate(params=commands.PauseParams(message='hello world')), expected_cls=commands.Pause)]) def test_command_store_queues_commands(command_request: commands.CommandCreate, expected_cls: Type[commands.Command], created_at: datetime, command_id: str, command_key: str) -> None: 'It should add a command to the store.' action = QueueCommandAction(request=command_request, created_at=created_at, command_id=command_id, command_key=command_key) expected_command = expected_cls(id=command_id, key=command_key, createdAt=created_at, status=commands.CommandStatus.QUEUED, params=command_request.params) subject = CommandStore() subject.handle_action(action) assert (subject.state.commands_by_id == {'command-id': CommandEntry(index=0, command=expected_command)}) assert (subject.state.all_command_ids == ['command-id']) assert (subject.state.queued_command_ids == OrderedSet(['command-id']))
It should add a command to the store.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_queues_commands
Opentrons/labware
2
python
@pytest.mark.parametrize(QueueCommandSpec._fields, [QueueCommandSpec(command_request=commands.AspirateCreate(params=commands.AspirateParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Aspirate), QueueCommandSpec(command_request=commands.DispenseCreate(params=commands.DispenseParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Dispense), QueueCommandSpec(command_request=commands.DropTipCreate(params=commands.DropTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.DropTip), QueueCommandSpec(command_request=commands.LoadLabwareCreate(params=commands.LoadLabwareParams(location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1), loadName='load-name', namespace='namespace', version=42)), expected_cls=commands.LoadLabware), QueueCommandSpec(command_request=commands.LoadPipetteCreate(params=commands.LoadPipetteParams(mount=MountType.LEFT, pipetteName=PipetteName.P300_SINGLE)), expected_cls=commands.LoadPipette), QueueCommandSpec(command_request=commands.PickUpTipCreate(params=commands.PickUpTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.PickUpTip), QueueCommandSpec(command_request=commands.MoveToWellCreate(params=commands.MoveToWellParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.MoveToWell), QueueCommandSpec(command_request=commands.PauseCreate(params=commands.PauseParams(message='hello world')), expected_cls=commands.Pause)]) def test_command_store_queues_commands(command_request: commands.CommandCreate, expected_cls: Type[commands.Command], created_at: datetime, command_id: str, command_key: str) -> None: action = QueueCommandAction(request=command_request, created_at=created_at, command_id=command_id, command_key=command_key) expected_command = expected_cls(id=command_id, key=command_key, createdAt=created_at, status=commands.CommandStatus.QUEUED, params=command_request.params) subject = CommandStore() subject.handle_action(action) assert (subject.state.commands_by_id == {'command-id': CommandEntry(index=0, command=expected_command)}) assert (subject.state.all_command_ids == ['command-id']) assert (subject.state.queued_command_ids == OrderedSet(['command-id']))
@pytest.mark.parametrize(QueueCommandSpec._fields, [QueueCommandSpec(command_request=commands.AspirateCreate(params=commands.AspirateParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Aspirate), QueueCommandSpec(command_request=commands.DispenseCreate(params=commands.DispenseParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name', volume=42, wellLocation=WellLocation())), expected_cls=commands.Dispense), QueueCommandSpec(command_request=commands.DropTipCreate(params=commands.DropTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.DropTip), QueueCommandSpec(command_request=commands.LoadLabwareCreate(params=commands.LoadLabwareParams(location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1), loadName='load-name', namespace='namespace', version=42)), expected_cls=commands.LoadLabware), QueueCommandSpec(command_request=commands.LoadPipetteCreate(params=commands.LoadPipetteParams(mount=MountType.LEFT, pipetteName=PipetteName.P300_SINGLE)), expected_cls=commands.LoadPipette), QueueCommandSpec(command_request=commands.PickUpTipCreate(params=commands.PickUpTipParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.PickUpTip), QueueCommandSpec(command_request=commands.MoveToWellCreate(params=commands.MoveToWellParams(pipetteId='pipette-id', labwareId='labware-id', wellName='well-name')), expected_cls=commands.MoveToWell), QueueCommandSpec(command_request=commands.PauseCreate(params=commands.PauseParams(message='hello world')), expected_cls=commands.Pause)]) def test_command_store_queues_commands(command_request: commands.CommandCreate, expected_cls: Type[commands.Command], created_at: datetime, command_id: str, command_key: str) -> None: action = QueueCommandAction(request=command_request, created_at=created_at, command_id=command_id, command_key=command_key) expected_command = expected_cls(id=command_id, key=command_key, createdAt=created_at, status=commands.CommandStatus.QUEUED, params=command_request.params) subject = CommandStore() subject.handle_action(action) assert (subject.state.commands_by_id == {'command-id': CommandEntry(index=0, command=expected_command)}) assert (subject.state.all_command_ids == ['command-id']) assert (subject.state.queued_command_ids == OrderedSet(['command-id']))<|docstring|>It should add a command to the store.<|endoftext|>
d98e31f6f79d182126b4d8b0914be05e4041d15906346302181bd970fb577b27
def test_command_queue_and_unqueue() -> None: 'It should queue on QueueCommandAction and dequeue on UpdateCommandAction.' queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2022, month=2, day=2), command_id='command-id-2', command_key='command-key-2') update_1 = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) update_2 = UpdateCommandAction(command=create_running_command(command_id='command-id-2')) subject = CommandStore() subject.handle_action(queue_1) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(queue_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1', 'command-id-2'])) subject.handle_action(update_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(update_1) assert (subject.state.queued_command_ids == OrderedSet())
It should queue on QueueCommandAction and dequeue on UpdateCommandAction.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_queue_and_unqueue
Opentrons/labware
2
python
def test_command_queue_and_unqueue() -> None: queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2022, month=2, day=2), command_id='command-id-2', command_key='command-key-2') update_1 = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) update_2 = UpdateCommandAction(command=create_running_command(command_id='command-id-2')) subject = CommandStore() subject.handle_action(queue_1) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(queue_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1', 'command-id-2'])) subject.handle_action(update_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(update_1) assert (subject.state.queued_command_ids == OrderedSet())
def test_command_queue_and_unqueue() -> None: queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2022, month=2, day=2), command_id='command-id-2', command_key='command-key-2') update_1 = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) update_2 = UpdateCommandAction(command=create_running_command(command_id='command-id-2')) subject = CommandStore() subject.handle_action(queue_1) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(queue_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1', 'command-id-2'])) subject.handle_action(update_2) assert (subject.state.queued_command_ids == OrderedSet(['command-id-1'])) subject.handle_action(update_1) assert (subject.state.queued_command_ids == OrderedSet())<|docstring|>It should queue on QueueCommandAction and dequeue on UpdateCommandAction.<|endoftext|>
df625953201478cfd152c92824a0482cf29aedd5229830e1ba42710db19c9410
def test_running_command_id() -> None: "It should update the running command ID through a command's lifecycle." queue = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(queue) assert (subject.state.running_command_id is None) subject.handle_action(running_update) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.running_command_id is None)
It should update the running command ID through a command's lifecycle.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_running_command_id
Opentrons/labware
2
python
def test_running_command_id() -> None: queue = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(queue) assert (subject.state.running_command_id is None) subject.handle_action(running_update) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.running_command_id is None)
def test_running_command_id() -> None: queue = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(queue) assert (subject.state.running_command_id is None) subject.handle_action(running_update) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.running_command_id is None)<|docstring|>It should update the running command ID through a command's lifecycle.<|endoftext|>
91d3c78b358b940e4b92a8fa71e7b9c5fa89fd779a81b53d9344118f144b2cd8
def test_running_command_no_queue() -> None: 'It should add a running command to state, even if there was no queue action.' running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(running_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id is None)
It should add a running command to state, even if there was no queue action.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_running_command_no_queue
Opentrons/labware
2
python
def test_running_command_no_queue() -> None: running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(running_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id is None)
def test_running_command_no_queue() -> None: running_update = UpdateCommandAction(command=create_running_command(command_id='command-id-1')) completed_update = UpdateCommandAction(command=create_succeeded_command(command_id='command-id-1')) subject = CommandStore() subject.handle_action(running_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id == 'command-id-1') subject.handle_action(completed_update) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.running_command_id is None)<|docstring|>It should add a running command to state, even if there was no queue action.<|endoftext|>
c2324c01fb281279c567c69c96cc15d92009640c135d3942d85215e75915bb5c
def test_command_failure_clears_queue() -> None: 'It should clear the command queue on command failure.' queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-2', command_key='command-key-2') running_1 = UpdateCommandAction(command=commands.Pause(id='command-id-1', key='command-key-1', createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), params=commands.PauseParams(), status=commands.CommandStatus.RUNNING)) fail_1 = FailCommandAction(command_id='command-id-1', error_id='error-id', failed_at=datetime(year=2023, month=3, day=3), error=errors.ProtocolEngineError('oh no')) expected_failed_1 = commands.Pause(id='command-id-1', key='command-key-1', error=errors.ErrorOccurrence(id='error-id', errorType='ProtocolEngineError', detail='oh no', createdAt=datetime(year=2023, month=3, day=3)), createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) expected_failed_2 = commands.Pause(id='command-id-2', key='command-key-2', error=None, createdAt=datetime(year=2021, month=1, day=1), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) subject = CommandStore() subject.handle_action(queue_1) subject.handle_action(queue_2) subject.handle_action(running_1) subject.handle_action(fail_1) assert (subject.state.running_command_id is None) assert (subject.state.queued_command_ids == OrderedSet()) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=expected_failed_1), 'command-id-2': CommandEntry(index=1, command=expected_failed_2)})
It should clear the command queue on command failure.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_failure_clears_queue
Opentrons/labware
2
python
def test_command_failure_clears_queue() -> None: queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-2', command_key='command-key-2') running_1 = UpdateCommandAction(command=commands.Pause(id='command-id-1', key='command-key-1', createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), params=commands.PauseParams(), status=commands.CommandStatus.RUNNING)) fail_1 = FailCommandAction(command_id='command-id-1', error_id='error-id', failed_at=datetime(year=2023, month=3, day=3), error=errors.ProtocolEngineError('oh no')) expected_failed_1 = commands.Pause(id='command-id-1', key='command-key-1', error=errors.ErrorOccurrence(id='error-id', errorType='ProtocolEngineError', detail='oh no', createdAt=datetime(year=2023, month=3, day=3)), createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) expected_failed_2 = commands.Pause(id='command-id-2', key='command-key-2', error=None, createdAt=datetime(year=2021, month=1, day=1), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) subject = CommandStore() subject.handle_action(queue_1) subject.handle_action(queue_2) subject.handle_action(running_1) subject.handle_action(fail_1) assert (subject.state.running_command_id is None) assert (subject.state.queued_command_ids == OrderedSet()) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=expected_failed_1), 'command-id-2': CommandEntry(index=1, command=expected_failed_2)})
def test_command_failure_clears_queue() -> None: queue_1 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-1', command_key='command-key-1') queue_2 = QueueCommandAction(request=commands.PauseCreate(params=commands.PauseParams()), created_at=datetime(year=2021, month=1, day=1), command_id='command-id-2', command_key='command-key-2') running_1 = UpdateCommandAction(command=commands.Pause(id='command-id-1', key='command-key-1', createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), params=commands.PauseParams(), status=commands.CommandStatus.RUNNING)) fail_1 = FailCommandAction(command_id='command-id-1', error_id='error-id', failed_at=datetime(year=2023, month=3, day=3), error=errors.ProtocolEngineError('oh no')) expected_failed_1 = commands.Pause(id='command-id-1', key='command-key-1', error=errors.ErrorOccurrence(id='error-id', errorType='ProtocolEngineError', detail='oh no', createdAt=datetime(year=2023, month=3, day=3)), createdAt=datetime(year=2021, month=1, day=1), startedAt=datetime(year=2022, month=2, day=2), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) expected_failed_2 = commands.Pause(id='command-id-2', key='command-key-2', error=None, createdAt=datetime(year=2021, month=1, day=1), completedAt=datetime(year=2023, month=3, day=3), params=commands.PauseParams(), status=commands.CommandStatus.FAILED) subject = CommandStore() subject.handle_action(queue_1) subject.handle_action(queue_2) subject.handle_action(running_1) subject.handle_action(fail_1) assert (subject.state.running_command_id is None) assert (subject.state.queued_command_ids == OrderedSet()) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=expected_failed_1), 'command-id-2': CommandEntry(index=1, command=expected_failed_2)})<|docstring|>It should clear the command queue on command failure.<|endoftext|>
9020979be205d366f659d4606fb1a88eee76b05274617eace7b0228f3e24b1d3
def test_command_store_preserves_handle_order() -> None: 'It should store commands in the order they are handled.' command_a = create_queued_command(command_id='command-id-1') command_b = create_running_command(command_id='command-id-2') command_c = create_succeeded_command(command_id='command-id-1') subject = CommandStore() subject.handle_action(UpdateCommandAction(command=command_a)) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a)}) subject.handle_action(UpdateCommandAction(command=command_b)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a), 'command-id-2': CommandEntry(index=1, command=command_b)}) subject.handle_action(UpdateCommandAction(command=command_c)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_c), 'command-id-2': CommandEntry(index=1, command=command_b)})
It should store commands in the order they are handled.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_preserves_handle_order
Opentrons/labware
2
python
def test_command_store_preserves_handle_order() -> None: command_a = create_queued_command(command_id='command-id-1') command_b = create_running_command(command_id='command-id-2') command_c = create_succeeded_command(command_id='command-id-1') subject = CommandStore() subject.handle_action(UpdateCommandAction(command=command_a)) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a)}) subject.handle_action(UpdateCommandAction(command=command_b)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a), 'command-id-2': CommandEntry(index=1, command=command_b)}) subject.handle_action(UpdateCommandAction(command=command_c)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_c), 'command-id-2': CommandEntry(index=1, command=command_b)})
def test_command_store_preserves_handle_order() -> None: command_a = create_queued_command(command_id='command-id-1') command_b = create_running_command(command_id='command-id-2') command_c = create_succeeded_command(command_id='command-id-1') subject = CommandStore() subject.handle_action(UpdateCommandAction(command=command_a)) assert (subject.state.all_command_ids == ['command-id-1']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a)}) subject.handle_action(UpdateCommandAction(command=command_b)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_a), 'command-id-2': CommandEntry(index=1, command=command_b)}) subject.handle_action(UpdateCommandAction(command=command_c)) assert (subject.state.all_command_ids == ['command-id-1', 'command-id-2']) assert (subject.state.commands_by_id == {'command-id-1': CommandEntry(index=0, command=command_c), 'command-id-2': CommandEntry(index=1, command=command_b)})<|docstring|>It should store commands in the order they are handled.<|endoftext|>
bb3b93daf59b779190a52b5f0b53056cbbe2a46c09941a5ec80108b7fc5568e1
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_pause_action(pause_source: PauseSource) -> None: 'It should clear the running flag on pause.' subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
It should clear the running flag on pause.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_handles_pause_action
Opentrons/labware
2
python
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_pause_action(pause_source: PauseSource) -> None: subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_pause_action(pause_source: PauseSource) -> None: subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))<|docstring|>It should clear the running flag on pause.<|endoftext|>
db7c66a40686c4f1d8e62201ed7e70496dcf666162fc4dc44c449a87fb91d099
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_play_action(pause_source: PauseSource) -> None: 'It should set the running flag on play.' subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
It should set the running flag on play.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_handles_play_action
Opentrons/labware
2
python
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_play_action(pause_source: PauseSource) -> None: subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
@pytest.mark.parametrize('pause_source', PauseSource) def test_command_store_handles_play_action(pause_source: PauseSource) -> None: subject = CommandStore() subject.handle_action(PauseAction(source=pause_source)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))<|docstring|>It should set the running flag on play.<|endoftext|>
feac61b123e0d31074f108fdb7235bd82ac86745ab54f990911952f703d93370
def test_command_store_handles_play_according_to_door_state() -> None: 'It should inactivate/activate command queue according to door state.' subject = CommandStore(is_door_blocking=True) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=True, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={})) door_close_event = DoorStateNotification(new_state=DoorState.CLOSED, blocking=False) subject.handle_action(HardwareEventAction(event=door_close_event)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
It should inactivate/activate command queue according to door state.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_handles_play_according_to_door_state
Opentrons/labware
2
python
def test_command_store_handles_play_according_to_door_state() -> None: subject = CommandStore(is_door_blocking=True) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=True, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={})) door_close_event = DoorStateNotification(new_state=DoorState.CLOSED, blocking=False) subject.handle_action(HardwareEventAction(event=door_close_event)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
def test_command_store_handles_play_according_to_door_state() -> None: subject = CommandStore(is_door_blocking=True) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=True, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={})) door_close_event = DoorStateNotification(new_state=DoorState.CLOSED, blocking=False) subject.handle_action(HardwareEventAction(event=door_close_event)) subject.handle_action(PlayAction()) assert (subject.state == CommandState(queue_status=QueueStatus.ACTIVE, run_result=None, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))<|docstring|>It should inactivate/activate command queue according to door state.<|endoftext|>
1e2ec55f774132b63a505549ee95411e7f49a58d17e63260ef167cf3d7ef15ad
def test_command_store_handles_finish_action() -> None: 'It should change to a succeeded state with FinishAction.' subject = CommandStore() subject.handle_action(PlayAction()) subject.handle_action(FinishAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=RunResult.SUCCEEDED, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
It should change to a succeeded state with FinishAction.
api/tests/opentrons/protocol_engine/state/test_command_store.py
test_command_store_handles_finish_action
Opentrons/labware
2
python
def test_command_store_handles_finish_action() -> None: subject = CommandStore() subject.handle_action(PlayAction()) subject.handle_action(FinishAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=RunResult.SUCCEEDED, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))
def test_command_store_handles_finish_action() -> None: subject = CommandStore() subject.handle_action(PlayAction()) subject.handle_action(FinishAction()) assert (subject.state == CommandState(queue_status=QueueStatus.INACTIVE, run_result=RunResult.SUCCEEDED, is_hardware_stopped=False, is_door_blocking=False, running_command_id=None, all_command_ids=[], queued_command_ids=OrderedSet(), commands_by_id=OrderedDict(), errors_by_id={}))<|docstring|>It should change to a succeeded state with FinishAction.<|endoftext|>