hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
248
max_stars_repo_name
stringlengths
5
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
248
max_issues_repo_name
stringlengths
5
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
248
max_forks_repo_name
stringlengths
5
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
2.06M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.03M
alphanum_fraction
float64
0
1
count_classes
int64
0
1.6M
score_classes
float64
0
1
count_generators
int64
0
651k
score_generators
float64
0
1
count_decorators
int64
0
990k
score_decorators
float64
0
1
count_async_functions
int64
0
235k
score_async_functions
float64
0
1
count_documentation
int64
0
1.04M
score_documentation
float64
0
1
16f050092210b638486f36ba124add5847de3ce7
9,390
py
Python
test/cpython/test_base64.py
aisk/pyston
ac69cfef0621dbc8901175e84fa2b5cb5781a646
[ "BSD-2-Clause", "Apache-2.0" ]
1
2020-02-06T14:28:45.000Z
2020-02-06T14:28:45.000Z
test/cpython/test_base64.py
aisk/pyston
ac69cfef0621dbc8901175e84fa2b5cb5781a646
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
test/cpython/test_base64.py
aisk/pyston
ac69cfef0621dbc8901175e84fa2b5cb5781a646
[ "BSD-2-Clause", "Apache-2.0" ]
1
2020-02-06T14:29:00.000Z
2020-02-06T14:29:00.000Z
import unittest from test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") eq(base64.encodestring("a"), "YQ==\n") eq(base64.encodestring("ab"), "YWI=\n") eq(base64.encodestring("abc"), "YWJj\n") eq(base64.encodestring(""), "") eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}"), "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\n') def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org") eq(base64.decodestring("YQ==\n"), "a") eq(base64.decodestring("YWI=\n"), "ab") eq(base64.decodestring("YWJj\n"), "abc") eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray("YWJj\n")), "abc") def test_encode(self): eq = self.assertEqual from cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n') def test_decode(self): from cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test default alphabet eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") eq(base64.b64encode('\x00'), 'AA==') eq(base64.b64encode("a"), "YQ==") eq(base64.b64encode("ab"), "YWI=") eq(base64.b64encode("abc"), "YWJj") eq(base64.b64encode(""), "") eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}"), "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") # Test with arbitrary alternative characters eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\xd3V\xbeo\xf7\x1d', altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") eq(base64.standard_b64encode("a"), "YQ==") eq(base64.standard_b64encode("ab"), "YWI=") eq(base64.standard_b64encode("abc"), "YWJj") eq(base64.standard_b64encode(""), "") eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}"), "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\xd3V\xbeo\xf7\x1d')), '01a-b_cd') def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.b64decode('AA=='), '\x00') eq(base64.b64decode("YQ=="), "a") eq(base64.b64decode("YWI="), "ab") eq(base64.b64decode("YWJj"), "abc") eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.b64decode(bytearray("YWJj")), "abc") # Test standard alphabet eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.standard_b64decode("YQ=="), "a") eq(base64.standard_b64decode("YWI="), "ab") eq(base64.standard_b64decode("YWJj"), "abc") eq(base64.standard_b64decode(""), "") eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") # Non-bytes eq(base64.standard_b64decode(bytearray("YWJj")), "abc") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') eq(base64.b16encode('\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\x01\x02\xab\xcd\xef')), '0102ABCDEF') def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef') eq(base64.b16decode('00'), '\x00') # Lower case is not allowed without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') # Non-bytes eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef') def test_main(): test_support.run_unittest(__name__) if __name__ == '__main__': test_main()
43.271889
81
0.587859
9,215
0.981363
0
0
0
0
0
0
3,453
0.367732
16f095ebea3707b39efe449bdb8d248fee8a8b6e
7,154
py
Python
src/Path.py
gabbonj/Workbench
86bbb2e3184e0f2fc5e9ac6dc7cfec86473fb7b9
[ "MIT" ]
2
2020-08-06T12:20:24.000Z
2020-08-06T12:20:43.000Z
src/Path.py
gabbonj/Workbench
86bbb2e3184e0f2fc5e9ac6dc7cfec86473fb7b9
[ "MIT" ]
null
null
null
src/Path.py
gabbonj/Workbench
86bbb2e3184e0f2fc5e9ac6dc7cfec86473fb7b9
[ "MIT" ]
null
null
null
import numpy as np from ctypes import c_void_p from .Shader import Shader from .transforms import * from OpenGL.GL import * class Path: # position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if rotation: assert len(position) == len(rotation) * 3 self.loadRotation(rotation) else: self.rotation = 'Pio è un figo' def loadPath(self, position): # compiling shader self.path_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation # compiling shader self.xpath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = [] self.yvertices = [] self.zvertices = [] for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) # setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor) return t_versor def renderPath(self, camera): model = np.identity(4) view = camera.view proj = camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0)
46.75817
131
0.643836
7,019
0.980855
0
0
0
0
0
0
794
0.110956
bc3fd4c771ec63f015857f770191b3f22d0f45f1
1,406
py
Python
icfree/echo_instructor/args.py
brsynth/icfree-ml
7f6c67f26bf60e9cadd59855aebb6bdb5bd64fda
[ "MIT" ]
1
2022-01-13T17:54:12.000Z
2022-01-13T17:54:12.000Z
icfree/echo_instructor/args.py
brsynth/icfree-ml
7f6c67f26bf60e9cadd59855aebb6bdb5bd64fda
[ "MIT" ]
null
null
null
icfree/echo_instructor/args.py
brsynth/icfree-ml
7f6c67f26bf60e9cadd59855aebb6bdb5bd64fda
[ "MIT" ]
null
null
null
from argparse import ( ArgumentParser ) from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description): parser = ArgumentParser( program, description, ) parser = add_arguments(parser) return parser def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to a .tsv file containing CFPS parameters and features', ) parser.add_argument( 'init_tset', type=str, help='Path to a .tsv file containing initial training set', ) parser.add_argument( 'norm_set', type=str, help='Path to a .tsv file containing normalizer set', ) parser.add_argument( 'autofluo_set', type=str, help='Path to a .tsv file containing autofluorescence set', ) parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output files' f' (default: {DEFAULT_OUTPUT_FOLDER})') ) return parser
20.985075
75
0.600996
0
0
0
0
0
0
0
0
451
0.320768
bc4085bfce6da5fce4ce47af500b1138fc887137
246
py
Python
ex1_01.py
sitdh/59.com-prog
24f536a72b0467ff3ee1615f515ecff9fbf36bb3
[ "MIT" ]
1
2021-04-25T14:46:12.000Z
2021-04-25T14:46:12.000Z
ex1_01.py
sitdh/com-prog
24f536a72b0467ff3ee1615f515ecff9fbf36bb3
[ "MIT" ]
null
null
null
ex1_01.py
sitdh/com-prog
24f536a72b0467ff3ee1615f515ecff9fbf36bb3
[ "MIT" ]
null
null
null
import math x = float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x = float(1 + prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3) print(prop_4) print(cos_x)
14.470588
43
0.646341
0
0
0
0
0
0
0
0
0
0
bc41a5fa588f792a592b96d3c6500dbf29045ec5
3,211
py
Python
test/datagateway_api/icat/filters/test_where_filter.py
MRichards99/datagateway-api
2e6133636fed950a16190d2f703f152c73bb5b1b
[ "Apache-2.0" ]
2
2022-02-10T17:47:53.000Z
2022-02-10T19:04:02.000Z
test/datagateway_api/icat/filters/test_where_filter.py
MRichards99/datagateway-api
2e6133636fed950a16190d2f703f152c73bb5b1b
[ "Apache-2.0" ]
183
2020-12-02T11:34:18.000Z
2022-03-29T15:19:23.000Z
test/datagateway_api/icat/filters/test_where_filter.py
MRichards99/datagateway-api
2e6133636fed950a16190d2f703f152c73bb5b1b
[ "Apache-2.0" ]
7
2021-04-13T17:26:05.000Z
2021-11-22T14:24:24.000Z
import pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( "operation, value, expected_condition_value", [ pytest.param("eq", 5, ["%s = '5'"], id="equal"), pytest.param("ne", 5, ["%s != 5"], id="not equal"), pytest.param("like", 5, ["%s like '%%5%%'"], id="like"), pytest.param("ilike", 5, ["UPPER(%s) like UPPER('%%5%%')"], id="ilike"), pytest.param("nlike", 5, ["%s not like '%%5%%'"], id="not like"), pytest.param( "nilike", 5, ["UPPER(%s) not like UPPER('%%5%%')"], id="not ilike", ), pytest.param("lt", 5, ["%s < '5'"], id="less than"), pytest.param("lte", 5, ["%s <= '5'"], id="less than or equal"), pytest.param("gt", 5, ["%s > '5'"], id="greater than"), pytest.param("gte", 5, ["%s >= '5'"], id="greater than or equal"), pytest.param("in", [1, 2, 3, 4], ["%s in (1, 2, 3, 4)"], id="in a list"), pytest.param("in", [], ["%s in (NULL)"], id="empty list"), ], ) def test_valid_operations( self, icat_query, operation, value, expected_condition_value, ): test_filter = PythonICATWhereFilter("id", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {"id": expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter("id", "1, 2, 3, 4, 5", "in") def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter("id", 10, "non") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): """Check that values that point to other values in the schema are applied""" test_filter = PythonICATWhereFilter("startDate", "o.endDate", "lt") test_filter.apply_filter(icat_query) assert icat_query.conditions == {"startDate": ["%s < o.endDate"]} def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter("title", "Investigation Title", "eq") test_filter.apply_filter(icat_query) assert icat_query.conditions == {"title": ["%s = 'Investigation Title'"]} def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter("random_field", "my_value", "eq") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter("id", 10, "lt") gt_filter = PythonICATWhereFilter("id", 5, "gt") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {"id": ["%s < '10'", "%s > '5'"]}
43.391892
87
0.617253
2,943
0.916537
0
0
1,328
0.413578
0
0
753
0.234506
bc43defd49d4ea43585c8d3910e9622ef8bc8d38
1,099
py
Python
scrapy/spider/spider/items.py
huobingli/splider
a62f0553160531a0735b249b0dc49747e9c821f9
[ "MIT" ]
null
null
null
scrapy/spider/spider/items.py
huobingli/splider
a62f0553160531a0735b249b0dc49747e9c821f9
[ "MIT" ]
null
null
null
scrapy/spider/spider/items.py
huobingli/splider
a62f0553160531a0735b249b0dc49747e9c821f9
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # # define the fields for your item here like: # # name = scrapy.Field() # pass # # # # class TorrentItem(scrapy.Item): # url = scrapy.Field() # name = scrapy.Field() # description = scrapy.Field() # size = scrapy.Field() # # import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 # define the fields for your item here like: # name = scrapy.Field() code = scrapy.Field() # 股票代码 abbr = scrapy.Field() # 股票简称 last_trade = scrapy.Field() # 最新价 chg_ratio = scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field() # 成交量 turn_over = scrapy.Field() # 成交额
24.977273
52
0.66424
640
0.532889
0
0
0
0
0
0
689
0.573689
bc441b2065c8199c0dd4d1448231c084f1b1cfa3
7,160
py
Python
codetools/contexts/multi_context.py
enthought/codetools
20d8bb1eba68145750a1b689655b839078121474
[ "BSD-3-Clause" ]
29
2015-08-10T20:25:00.000Z
2021-11-30T23:34:24.000Z
codetools/contexts/multi_context.py
enthought/codetools
20d8bb1eba68145750a1b689655b839078121474
[ "BSD-3-Clause" ]
40
2015-01-05T15:01:37.000Z
2022-03-11T13:47:06.000Z
codetools/contexts/multi_context.py
enthought/codetools
20d8bb1eba68145750a1b689655b839078121474
[ "BSD-3-Clause" ]
4
2015-04-14T10:06:26.000Z
2021-01-19T16:46:48.000Z
# # (C) Copyright 2013 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in # LICENSE.txt # """ Context holding multiple subcontexts. """ from __future__ import absolute_import from itertools import chain from collections import MutableMapping as DictMixin from traits.api import (Bool, List, Str, Undefined, Supports, adapt, provides, on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): """ Wrap several subcontexts. """ #: The name of the context. name = Str("multidummy") #: The underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified events veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface #################################################### def __iter__(self): return iter(self.keys()) def __len__(self): return len(list(self.keys())) def __contains__(self, key): for c in self.subcontexts: if key in c: return True return False def __delitem__(self, key): """ Remove the given key with [] access. Only deletes the first instance of the key. Parameters ---------- key : str Raises ------ KeyError if the kew is not available in the context. """ for c in self.subcontexts: try: del c[key] return except KeyError: continue raise KeyError(key) def __getitem__(self, key): for c in self.subcontexts: try: return c[key] except KeyError: continue raise KeyError(key) def __setitem__(self, key, value): """ Set item with [] access. The first subcontext which allows the key/value pair will get it. If an earlier subcontext has the key, but does not allow the assignment, then that key will be deleted. Later contexts with the key will be untouched. If the key/value pair cannot be assigned to anything, no deletion will take place. Parameters ---------- key : str value : object Raises ------ ValueError if the key is not permitted to be assigned that value. """ # Let subtypes dictate compatibility independently of contained contexts if not self.allows(value, key): raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) set = False blocking_contexts = [] for c in self.subcontexts: if not set: if c.allows(value, key): if key in c: added = [] current_value = c[key] try: is_modified = bool(current_value != value) except Exception: is_modified = current_value is not value if is_modified: modified = [key] c[key] = value else: modified = [] else: added = [key] modified = [] c[key] = value set = True break elif key in c: # Record this context as blocking access to the final # location of the value. blocking_contexts.append(c) # Remove all blocking instances. for c in blocking_contexts: del c[key] if not set: raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) # Expose DictMixin's get method over HasTraits'. get = DictMixin.get def __str__(self): # Maybe a good default string subcontext_str = '[%s]' % ', '.join([str(x) for x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def __repr__(self): # Maybe a good default representation return '%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext interface ########################################## def allows(self, value, name=None): for c in self.subcontexts: if c.allows(value, name=name): return True return False #### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): """ Pass events up. """ if event is Undefined: # Nothing to do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): """ Trait listener for items of subcontexts list. """ added = [] removed = [] # Add to the list of items added if len(event.added): for context in event.added: added.extend(list(context.keys())) # Add to the list of items removed if len(event.removed): for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################ def checkpoint(self): """ Make a shallow copy of the context. Technically, this is actually a fairly deep copy. All of the object structure should be replicated, but the actual dictionary storage will be shallowly copied:: copy = context.shallow_copy() copy[key] is context[key] for key in context.keys() These semantics are useful for saving out checkpointed versions of the context for implementing an undo/redo stack. They may not be useful for other purposes. Returns ------- copy : IContext """ copy = self.clone_traits() new_subcontexts = [] for context in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts = new_subcontexts return copy
30.468085
85
0.557682
6,522
0.910894
0
0
6,546
0.914246
0
0
2,662
0.371788
bc447d214c0f2c389991fd5918f6f13fed4aaf6b
634
py
Python
line_counter/TestCodes/python_test.py
FMoller/coding-auxiliary-tools
21784f01731404f33059f3a8c4e73a104709ffe9
[ "MIT" ]
null
null
null
line_counter/TestCodes/python_test.py
FMoller/coding-auxiliary-tools
21784f01731404f33059f3a8c4e73a104709ffe9
[ "MIT" ]
null
null
null
line_counter/TestCodes/python_test.py
FMoller/coding-auxiliary-tools
21784f01731404f33059f3a8c4e73a104709ffe9
[ "MIT" ]
null
null
null
"""A simple file to test the line_counter performance in python This is a multiline doctest """ __author__ = "Frederico Moeller" __copyright__ = "" __credits__ = ["Frederico Moeller"] __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "Frederico Moeller" __email__ = "" __status__ = "" #import things import math #define things def some_function(var_one, var_two, var_three): """This is a function that do things""" if var_one > var_two: if var_two*var_three > var_one: return "blab" #this happens else: return "blob" else: return "fish"
21.133333
63
0.641956
0
0
0
0
0
0
0
0
268
0.422713
bc44b8524b66c7a720d547f156846ae7572f5832
4,602
py
Python
causal_attribution/data.py
VaniW/deconfounded-lexicon-induction
419ecf717f51cfd1741732ca3191b36b565bd1a4
[ "MIT" ]
25
2020-11-03T16:38:51.000Z
2022-03-28T11:53:08.000Z
causal_attribution/data.py
VaniW/deconfounded-lexicon-induction
419ecf717f51cfd1741732ca3191b36b565bd1a4
[ "MIT" ]
1
2019-12-15T08:33:47.000Z
2019-12-16T17:33:15.000Z
causal_attribution/data.py
VaniW/deconfounded-lexicon-induction
419ecf717f51cfd1741732ca3191b36b565bd1a4
[ "MIT" ]
7
2021-05-03T01:01:28.000Z
2022-02-19T04:06:20.000Z
"""Data pipelines.""" from collections import defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): """Gathers info on and creats a featurized example generator for a list of raw examples. Args: examples: list(list, float, or string). Examples to create generator for. vocab: list(str). A vocabulary for discrete datatypes (e.g. text or categorical). max_seq_len: int. maximum sequence length for text examples. Returns: A dict of info about this variable as well as a generator over featurized examples. """ assert isinstance(examples, list), 'examples must be list; got ' + str(type(examples)) assert len(examples) > 0, 'Empty example list!' # Text if isinstance(examples[0], list): assert vocab is not None, 'ERROR: must provide a vocab.' example_type = 'input' vocab = ['UNK', 'PAD'] + vocab tok2id = {tok: i for i, tok in enumerate(vocab)} ngrams = max(len(x.split()) for x in vocab) unk_id = 0 def featurizer(example): ids = [] for n in range(1, ngrams + 1): toks = [' '.join(example[i: i + n]) for i in range(len(example) - n + 1)] ids += [tok2id.get(x, 0) for x in toks] ids = ids[:max_seq_len] padded_ids = ids + ([1] * (max_seq_len - len(ids))) # pad idx = 1 return padded_ids # Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type = 'continuous' vocab = ['N/A'] if isinstance(examples[0], int): featurizer = lambda ex: float(ex) else: featurizer = lambda ex: ex # Categorical elif isinstance(examples[0], str): example_type = 'categorical' if not vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id = {tok: i for i, tok in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0) # 0 is the unk id. else: print("ERROR: unrecognized example type: ", examples[0]) quit() return featurizer, example_type, vocab def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): """Builds a data iterator for text, confounds, and outcomes. Args: vocab: list(str). The vocabulary to use. df: pandas.df. The data we want to iterate over. The columns of these data should be a superset of the keys in name_to_type. name_to_type: dict. A mapping from variable names to whether they are "input", "predict", or "control" variables. batch_size: int. The batch size to use. max_seq_len: int. Maximum length of text sequences. Returns: A generator which yields dictionaries where variable names are mapped to tensors of batched data. """ def featurize(featurizer): return [featurizer(ex) for ex in examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for var_name, var_type in name_to_type.items(): examples = list(df[var_name]) if var_type == 'input': examples = [x.split() for x in examples] featurizer, _, vocab = get_info(examples, vocab, max_seq_len) var_info[var_name] = { 'control': False, 'name': var_name, 'type': var_type, 'vocab': vocab } else: featurizer, varType, vocab = get_info(examples) var_info[var_name] = { 'control': var_type == 'control', 'name': var_name, 'type': varType, 'vocab': vocab } featurized_data[var_name] = [featurizer(ex) for ex in examples] def to_tensor(var_name): dtype = torch.float if var_info[var_name]['type'] in {'categorical', 'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x in zip(*batch)], # group by datatype. batch_size=batch_size) def iterator(): for batch in dataloader: yield dict(zip(feature_names, batch)) return iterator, var_info
35.674419
93
0.612994
0
0
2,312
0.50239
0
0
0
0
1,473
0.320078
bc44f25c8ff96beccbbd3fbaa05ae2dcf6790cc6
576
py
Python
fopp/Chapter 12. Functions/get_num_digits.py
H2u-Hwng/EVC
c650fe7356a333011514cf9025dfd97bf71b1de3
[ "MIT" ]
null
null
null
fopp/Chapter 12. Functions/get_num_digits.py
H2u-Hwng/EVC
c650fe7356a333011514cf9025dfd97bf71b1de3
[ "MIT" ]
null
null
null
fopp/Chapter 12. Functions/get_num_digits.py
H2u-Hwng/EVC
c650fe7356a333011514cf9025dfd97bf71b1de3
[ "MIT" ]
null
null
null
# Take number, and convert integer to string # Calculate and return number of digits def get_num_digits(num): # Convert int to str num_str = str(num) # Calculate number of digits digits = len(num_str) return digits # Define main function def main(): # Prompt user for an integer number = int(input('Enter an integer: ')) # Obtain number of digits num_digits = get_num_digits(number) # Display result print(f'The number of digits in number {number} is {num_digits}.') # Call main function main()
20.571429
70
0.647569
0
0
0
0
0
0
0
0
321
0.557292
bc450f5f688b95fda7b269a4ca568c7ecc5143ca
4,992
py
Python
whois/__init__.py
mzpqnxow/whois-1
b5623ed25cfa58d9457d30dae640e69b9e530b23
[ "MIT" ]
null
null
null
whois/__init__.py
mzpqnxow/whois-1
b5623ed25cfa58d9457d30dae640e69b9e530b23
[ "MIT" ]
null
null
null
whois/__init__.py
mzpqnxow/whois-1
b5623ed25cfa58d9457d30dae640e69b9e530b23
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import * import re import sys import os import subprocess import socket from .parser import WhoisEntry from .whois import NICClient # thanks to https://www.regextester.com/104038 IPV4_OR_V6 = re.compile(r"((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))") def whois(url, command=False, flags=0): # clean domain to expose netloc ip_match = IPV4_OR_V6.match(url) if ip_match: domain = url try: result = socket.gethostbyaddr(url) except socket.herror as e: pass else: domain = extract_domain(result[0]) else: domain = extract_domain(url) if command: # try native whois command r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE) text = r.stdout.read().decode() else: # try builtin client nic_client = NICClient() text = nic_client.whois_lookup(None, domain.encode('idna'), flags) return WhoisEntry.load(domain, text) suffixes = None def extract_domain(url): """Extract the domain from the given URL >>> print(extract_domain('http://www.google.com.au/tos.html')) google.com.au >>> print(extract_domain('abc.def.com')) def.com >>> print(extract_domain(u'www.公司.hk')) 公司.hk >>> print(extract_domain('chambagri.fr')) chambagri.fr >>> print(extract_domain('www.webscraping.com')) webscraping.com >>> print(extract_domain('198.252.206.140')) stackoverflow.com >>> print(extract_domain('102.112.2O7.net')) 2o7.net >>> print(extract_domain('globoesporte.globo.com')) globo.com >>> print(extract_domain('1-0-1-1-1-0-1-1-1-1-1-1-1-.0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info')) 0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info >>> print(extract_domain('2607:f8b0:4006:802::200e')) 1e100.net >>> print(extract_domain('172.217.3.110')) 1e100.net """ if IPV4_OR_V6.match(url): # this is an IP address return socket.gethostbyaddr(url)[0] # load known TLD suffixes global suffixes if not suffixes: # downloaded from https://publicsuffix.org/list/public_suffix_list.dat tlds_path = os.path.join(os.getcwd(), os.path.dirname(__file__), 'data', 'public_suffix_list.dat') with open(tlds_path, encoding='utf-8') as tlds_fp: suffixes = set(line.encode('utf-8') for line in tlds_fp.read().splitlines() if line and not line.startswith('//')) if not isinstance(url, str): url = url.decode('utf-8') url = re.sub('^.*://', '', url) url = url.split('/')[0].lower() # find the longest suffix match domain = b'' split_url = url.split('.') for section in reversed(split_url): if domain: domain = b'.' + domain domain = section.encode('utf-8') + domain if domain not in suffixes: if not b'.' in domain and len(split_url) >= 2: # If this is the first section and there wasn't a match, try to # match the first two sections - if that works, keep going # See https://github.com/richardpenman/whois/issues/50 second_order_tld = '.'.join([split_url[-2], split_url[-1]]) if not second_order_tld.encode('utf-8') in suffixes: break else: break return domain.decode('utf-8') if __name__ == '__main__': try: url = sys.argv[1] except IndexError: print('Usage: %s url' % sys.argv[0]) else: print(whois(url))
42.305085
1,227
0.55629
0
0
0
0
0
0
0
0
2,724
0.5448
bc45c15aebfb0da618b90f3884eb8a545e0f2823
3,255
py
Python
app/dialog/avatar_picture_dialog.py
tirinox/alphavatarbot
5adac8c9c4534206eaf6c146f6e194ed5951d055
[ "MIT" ]
1
2021-03-18T15:35:15.000Z
2021-03-18T15:35:15.000Z
app/dialog/avatar_picture_dialog.py
tirinox/alphavatarbot
5adac8c9c4534206eaf6c146f6e194ed5951d055
[ "MIT" ]
null
null
null
app/dialog/avatar_picture_dialog.py
tirinox/alphavatarbot
5adac8c9c4534206eaf6c146f6e194ed5951d055
[ "MIT" ]
1
2021-03-18T15:35:51.000Z
2021-03-18T15:35:51.000Z
import asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler from localization import BaseLocalization from lib.depcont import DepContainer from lib.texts import kbd # todo: accept documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme: no state handle MAIN = State() class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc, data, d) self._work_lock = asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture: PhotoSize = None): async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST A LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE END stack.push_async_callback(sticker.delete) if explicit_picture is not None: user_pic = await download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user) w, h = user_pic.size if not w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64 <= w <= 4096) and (64 <= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png') await message.answer_document(pic, caption=loc.TEXT_AVA_READY, reply_markup=self.menu_kbd())
39.695122
119
0.677112
2,658
0.81659
0
0
699
0.214747
2,050
0.6298
185
0.056836
bc498b7d39a14ae7cd3ad1e6341af40bb6279e72
5,144
py
Python
image_store_processing.py
olubiyiontheweb/digid_websearch_flask
181107eaa60faff9429b754236406eed56e3c1ec
[ "MIT" ]
1
2021-12-15T18:56:05.000Z
2021-12-15T18:56:05.000Z
image_store_processing.py
olubiyiontheweb/similar_image_websearch
ddb79a3e627c1143ff7f64e6d82f0d8b9dcd8047
[ "MIT" ]
null
null
null
image_store_processing.py
olubiyiontheweb/similar_image_websearch
ddb79a3e627c1143ff7f64e6d82f0d8b9dcd8047
[ "MIT" ]
null
null
null
from skimage.metrics import structural_similarity as ssim from glob import glob from PIL import Image import numpy as np import ntpath import dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER = "./image_store" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops = database_migrations() class preprocess: def __init__(self): # image table values to insert in database self.images_list = dict() self.image_store = list() def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + "/*" + img_type) for img in images: imgname = ntpath.basename(img) values = imgname, IMAGE_FOLDER, "local" print(values) db_ops.image_store_migrations() # TODO Abstract requests and insert from database db_ops.insert_operations("image_store", values) def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER + "/*" + img_type) images = db_ops.request_matches("image_store") print("list from database" + str(images)) self.image_store.clear() self.images_list.clear() for img in images: # get image name print("current list" + str(self.image_store)) self.images_list["image_id"] = img[0] self.images_list["image_name"] = img[1] print("Check the values" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print("Check the images" + str(self.image_store)) print("We have" + str(len(self.image_store)) + "images in the store") print(self.image_store) return self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db: image = Image.open(IMAGE_FOLDER + "\\" + img["image_name"]) row, col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values = img_hash, img["image_id"] db_ops.image_store_migrations() print(values) db_ops.insert_operations("image_store_hash", values) class compare_files: def __init__(self): # image table values to insert in database self.images_list = dict() self.image_store = list() def request_image_hashes(self): images = db_ops.request_matches("image_store_hash") print("list from database" + str(images)) self.image_store.clear() self.images_list.clear() for img in images: # get image name print("current list" + str(img)) self.images_list["image_hash"] = img[1] # request image name from image store database img_name = db_ops.conditional_request_matches( "image_store", img[2], "image_name", "image_id") self.images_list["image_name"] = img_name[0][0] print("Check the values" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print("Check the images" + str(self.image_store)) print("We have" + str(len(self.image_store)) + "images in the store") print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0 count = 0 while (i < len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count += 1 i += 1 return count def mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean Squared Error' between the two images is the # sum of the squared difference between the two images; # NOTE: the two images must have the same dimension err = np.sum((uploaded_image.astype("float") - db_store_image.astype("float"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the MSE, the lower the error, the more "similar" # the two images are return err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make structural similarity and mean squared error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image, db_store_image) return ssim_index, mean_sq_error
36.742857
79
0.631221
4,794
0.93196
0
0
0
0
0
0
991
0.192652
bc49a143fb9688648101a0602142d480263709b3
8,823
py
Python
cogs/jpserv.py
elthorito/Rai
a6f05567a0d4ed98a09676e507c478a27630bf1c
[ "MIT" ]
null
null
null
cogs/jpserv.py
elthorito/Rai
a6f05567a0d4ed98a09676e507c478a27630bf1c
[ "MIT" ]
null
null
null
cogs/jpserv.py
elthorito/Rai
a6f05567a0d4ed98a09676e507c478a27630bf1c
[ "MIT" ]
null
null
null
import discord from discord.ext import commands import os import json from datetime import date, datetime, timedelta from .utils import helper_functions as hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\', '/') class Jpserv(commands.Cog): """Modules unique for the Japanese server""" def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): if not ctx.guild: return return ctx.guild.id == 189571157446492161 or ctx.guild.id == 275146036178059265 # these commands are only useable on Japanese server or my testing server @commands.command() @hf.is_admin() async def swap(self, ctx): """Swaps JHO/JHO2's names and positions in the lists, for if we temporarily want welcome messages to go to JHO2""" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx, *, member=None): """Irreversible hardcore mode. Must talk to an admin to have this undone.""" # if ctx.guild.id != 189571157446492161: # return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member: # if you specified someone else's ID, then remove UHC from them member = await hf.member_converter(ctx, member) if not member: return if hf.admin_check(ctx) and ctx.author.id != member.id: if str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0] = False else: await ctx.send("That user is not in UHC") return else: await ctx.send("That user is not in UHC mode.") return await hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send("I couldn't remove the ultra hardcore role") await ctx.send(f'Undid ultra hardcore mode for {member.name}') else: await ctx.send("You can not remove UHC. Ask a mod/admin to help you.") else: if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f"This is ultra hardcore mode. It means you must speak in the language you are learning" f" (for example, if you are learning Japanese, any messages in English will be deleted)." f" This can not be undone unless you ask a mod to remove it for you. \n\n" f"To enable ultra hardcore mode, type `;uhc on` or `;uhc enable`. ") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx): """Enables UHC""" if ctx.guild.id != 189571157446492161: return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: # if not enabled user = config[str(ctx.author.id)] if user[0]: await ctx.send("You're already in ultra hardcore mode.") return else: user[0] = True else: config[str(ctx.author.id)] = [True, date.today().strftime("%Y/%m/%d"), 0] await hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send("I couldn't add the ultra hardcore role") await ctx.send(f"{ctx.author.name} has chosen to enable ultra hardcore mode. It works the same as " "normal hardcore mode except that you can't undo it and asterisks don't change " "anything. Talk to a mod to undo this.") @ultrahardcore.command() async def list(self, ctx): """Lists the people currently in ultra hardcore mode""" if ctx.guild.id != 189571157446492161: return string = 'The members in ultra hardcore mode right now are ' guild = self.bot.get_guild(189571157446492161) members = [] config = self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id)) if member is not None: # in case a member leaves members.append(member.name) else: del config[member_id] await ctx.send(f'Removed <@{member_id}> from the list, as they seem to have left the server') await ctx.send(string + ', '.join(members)) @ultrahardcore.command() async def explanation(self, ctx): """Explains ultra hardcore mode for those who are using it and can't explain it""" if ctx.guild.id != 189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f"{ctx.author.mention} is currently using ultra hardcore mode. In this mode, they can't" f" speak their native language, and they also cannot undo this mode themselves.") return await ctx.send(f"{ctx.author.mention} is currently NOT using hardcore mode, so I don't know why " f"they're trying to use this command. But, ultra hardcore mode means a user can't speak " f"any English, and can't undo this mode themselves no matter what.") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): """Shows a leaderboard of who has had UHC on for the longest""" if ctx.guild.id != 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], "%Y/%m/%d")).days # {('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort = [[i[0], i[1][0], i[1][2]] for i in list(time_dict.items())] # to_sort: [['243703909166612480', True, 162], ['219617844973797376', False, 122], ...] sorted_dict = sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard = f"The number of days each user has had UHC enabled " \ f"(Bold = This user currently has UHC enabled)\n\n" for i in sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2] < 10 and not i[1]) or (not user): continue if user.nick: name_str = f"{user.mention} ({user.name})" else: name_str = f"{user.name}" if i[1]: leaderboard += f"**{i[2]}: {name_str}**\n" else: leaderboard += f"{i[2]}: {name_str}\n" emb = discord.Embed(title="UHC Leaderboard", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx): """Ignores a channel for UHC""" if ctx.guild.id != 189571157446492161: return config = self.bot.db['ultraHardcore'] try: if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f"Added {ctx.channel.name} to list of ignored channels for UHC") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f"Removed {ctx.channel.name} from list of ignored channels for UHC") except KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f"Added {ctx.channel.name} to list of ignored channels for UHC") await hf.dump_json() def setup(bot): bot.add_cog(Jpserv(bot))
45.715026
120
0.572821
8,497
0.963051
0
0
8,073
0.914995
8,014
0.908308
2,979
0.33764
bc4baf04ed5a5ebda75a1b19ad254a0f725f6190
2,027
py
Python
nehebn2.py
psifertex/nehebn2
8b62a88a9d06624dbb62b8b74cc0566172fba970
[ "MIT" ]
null
null
null
nehebn2.py
psifertex/nehebn2
8b62a88a9d06624dbb62b8b74cc0566172fba970
[ "MIT" ]
null
null
null
nehebn2.py
psifertex/nehebn2
8b62a88a9d06624dbb62b8b74cc0566172fba970
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from components import ProgramState import binaryninja as binja import argparse import os.path import curses # TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop) # TODO...support multi-key presses? Not sure if this already works or not # TODO...make sure to support small terminals (I think it does right now, but I should add some more checks so nothing goes out of bounds) def main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default="") args = parser.parse_args() program = '' if not args.filename == "": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress) == "Idle": prog = bv.analysis_progress stdscr.erase() stdscr.border() state = '' if prog.state == binja.AnalysisState.DisassembleState: state = "Disassembling" else: state = "Analyzing" loadingText = "Loading File: " prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog) + ']') stdscr.refresh() program = ProgramState(stdscr, bv) else: raise IOError("File does not exist.") else: program = ProgramState(stdscr) key = "" while program.is_running: # Input Filtering try: key = stdscr.getkey() except curses.error as err: if not str(err) == "no input": raise curses.error(str(err)) else: key = "" # Clear Key Buffer # Rendering and input program.parseInput(key) program.render() curses.doupdate() if __name__ == "__main__": background = "2a2a2a" text = "e0e0e0" curses.wrapper(main)
28.957143
138
0.644795
0
0
0
0
0
0
0
0
603
0.297484
bc4d5b7bde1ce5d45b97c67684a8f6c61429eb5b
5,144
py
Python
keras/layers/pooling/base_pooling3d.py
itsraina/keras
5e9376b5b94b6fb445dd52dbfafbc4e95bff5e35
[ "Apache-2.0" ]
null
null
null
keras/layers/pooling/base_pooling3d.py
itsraina/keras
5e9376b5b94b6fb445dd52dbfafbc4e95bff5e35
[ "Apache-2.0" ]
null
null
null
keras/layers/pooling/base_pooling3d.py
itsraina/keras
5e9376b5b94b6fb445dd52dbfafbc4e95bff5e35
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Private base class for pooling 3D layers.""" import tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils class Pooling3D(Layer): """Pooling layer for arbitrary pooling functions, for 3D inputs. This class only exists for code reuse. It will never be an exposed API. Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. name: A string, the name of the layer. """ def __init__( self, pool_function, pool_size, strides, padding="valid", data_format="channels_last", name=None, **kwargs ): super().__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format() if strides is None: strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, "pool_size") self.strides = conv_utils.normalize_tuple( strides, 3, "strides", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,) + self.pool_size + (1,) strides = (1,) + self.strides + (1,) if self.data_format == "channels_first": # TF does not support `channels_first` with 3D pooling operations, # so we must handle this case manually. # TODO(fchollet): remove this when TF pooling is feature-complete. inputs = tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format == "channels_first": outputs = tf.transpose(outputs, (0, 4, 1, 2, 3)) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == "channels_first": len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] else: len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if self.data_format == "channels_first": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] ) else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] ) def get_config(self): config = { "pool_size": self.pool_size, "padding": self.padding, "strides": self.strides, "data_format": self.data_format, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
37.823529
80
0.623639
4,218
0.819984
0
0
0
0
0
0
2,241
0.435653
bc4d689703a555cde99de572dc764b14b5f45f70
726
py
Python
main.py
lucastan96/video2bitmap
8a54f33af92b5088d29322abf936a6ce2ecc0ac4
[ "MIT" ]
1
2020-12-30T00:57:38.000Z
2020-12-30T00:57:38.000Z
main.py
lucastan96/video2bitmap
8a54f33af92b5088d29322abf936a6ce2ecc0ac4
[ "MIT" ]
null
null
null
main.py
lucastan96/video2bitmap
8a54f33af92b5088d29322abf936a6ce2ecc0ac4
[ "MIT" ]
null
null
null
import moviepy.editor as mpy import moviepy.video.fx.all as vfx import subprocess as sp # Crop and resize video clip = mpy.VideoFileClip("smoke.mp4") (w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames # Make sure to install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black and white bitmap for i in range(202): col = Image.open("frames_temp/" + str(i + 1) + ".bmp") gray = col.convert('L') bw = gray.point(lambda x: 0 if x<128 else 255, '1') bw.save("frames/" + str(i) + ".bmp")
34.571429
95
0.688705
0
0
0
0
0
0
0
0
266
0.366391
bc4dbd4536189e5c83cb95261570c971ee7df77f
336
py
Python
ghostwriter/rolodex/apps.py
bbhunter/Ghostwriter
1b684ddd119feed9891e83b39c9b314b41d086ca
[ "BSD-3-Clause" ]
601
2019-07-30T17:06:37.000Z
2022-03-31T00:55:31.000Z
ghostwriter/rolodex/apps.py
chrismaddalena/Ghostwriter
5a938358450cd0e69a42883b1b18e067644744a8
[ "BSD-3-Clause" ]
150
2019-08-01T07:20:22.000Z
2022-03-29T19:18:02.000Z
ghostwriter/rolodex/apps.py
chrismaddalena/Ghostwriter
5a938358450cd0e69a42883b1b18e067644744a8
[ "BSD-3-Clause" ]
126
2019-07-30T17:42:49.000Z
2022-03-21T20:43:35.000Z
"""This contains the configuration of the Rolodex application.""" # Django Imports from django.apps import AppConfig class RolodexConfig(AppConfig): name = "ghostwriter.rolodex" def ready(self): try: import ghostwriter.rolodex.signals # noqa F401 isort:skip except ImportError: pass
22.4
70
0.672619
215
0.639881
0
0
0
0
0
0
124
0.369048
bc4f1db83b181105ad1b030028d4a99321957de7
560
py
Python
boards/migrations/0024_boardpreferences_moderators.py
oscarsiles/jotlet
361f7ad0d32ea96d012020a67493931482207036
[ "BSD-3-Clause" ]
null
null
null
boards/migrations/0024_boardpreferences_moderators.py
oscarsiles/jotlet
361f7ad0d32ea96d012020a67493931482207036
[ "BSD-3-Clause" ]
2
2022-03-21T22:22:33.000Z
2022-03-28T22:18:33.000Z
boards/migrations/0024_boardpreferences_moderators.py
oscarsiles/jotlet
361f7ad0d32ea96d012020a67493931482207036
[ "BSD-3-Clause" ]
null
null
null
# Generated by Django 4.0.3 on 2022-03-01 14:42 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations = [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True, related_name='moderated_boards', to=settings.AUTH_USER_MODEL), ), ]
26.666667
115
0.673214
434
0.775
0
0
0
0
0
0
126
0.225
bc4f5018d00b3586d20735c150c38e4b306f48f3
325
py
Python
models/minimize_model.py
MichalBusta/OpenCitiesAIC
2358118a782edde27a588d6adaf79941cbd90de6
[ "MIT" ]
7
2020-03-23T21:43:32.000Z
2021-03-30T09:11:45.000Z
models/minimize_model.py
MichalBusta/OpenCitiesAIC
2358118a782edde27a588d6adaf79941cbd90de6
[ "MIT" ]
4
2020-05-09T01:13:24.000Z
2022-01-13T02:24:14.000Z
models/minimize_model.py
MichalBusta/OpenCitiesAIC
2358118a782edde27a588d6adaf79941cbd90de6
[ "MIT" ]
4
2020-04-17T15:06:36.000Z
2021-03-30T09:11:47.000Z
''' Created on Mar 22, 2020 @author: Michal.Busta at gmail.com ''' #get rid of the optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = { "state_dict": state["state_dict"], } torch.save(state_out, 'model-b2-2.pth')
20.3125
73
0.707692
0
0
0
0
0
0
0
0
167
0.513846
bc4fb0ed6bbdc4f3f5e43225548f14915b084779
1,125
py
Python
setup.py
thomas-kloeber/braumeister
1045df0ad95eb6a4b9b16bb91ece64b09ff1b1f7
[ "MIT" ]
6
2018-02-09T15:03:12.000Z
2021-02-18T07:21:34.000Z
setup.py
thomas-kloeber/braumeister
1045df0ad95eb6a4b9b16bb91ece64b09ff1b1f7
[ "MIT" ]
17
2018-03-20T09:28:32.000Z
2022-01-27T08:48:41.000Z
setup.py
thomas-kloeber/braumeister
1045df0ad95eb6a4b9b16bb91ece64b09ff1b1f7
[ "MIT" ]
7
2018-02-09T15:06:11.000Z
2020-03-02T10:23:10.000Z
import os import re from setuptools import setup version = re.search( '^__version__\s*=\s*"(.*)"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="braumeister", packages=["braumeister", "braumeister.actions"], version=version, author="Marcel Steffen", author_email="[email protected]", description="Easy release bulding, combining JIRA and git", long_description=read('README.md'), license="MIT", keywords="git jira release", url="https://www.talentsconnect.com", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': ["braumeister = braumeister.braumeister:main"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Topic :: Utilities", "Topic :: Software Development :: Version Control :: Git" ], )
26.162791
73
0.639111
0
0
0
0
0
0
0
0
525
0.466667
bc500a982cb78bb46e6aa705ee116eae36444405
3,493
py
Python
modules/inference.py
rubelchowdhury20/wuton-with-densepose
5485f1f311724d8f8b887d669a8b55c73849eb98
[ "MIT" ]
12
2020-11-13T01:51:24.000Z
2022-03-17T03:14:27.000Z
modules/inference.py
rubelchowdhury20/wuton-with-densepose
5485f1f311724d8f8b887d669a8b55c73849eb98
[ "MIT" ]
1
2021-10-12T06:10:22.000Z
2021-10-12T06:10:22.000Z
modules/inference.py
rubelchowdhury20/wuton-with-densepose
5485f1f311724d8f8b887d669a8b55c73849eb98
[ "MIT" ]
2
2021-01-10T17:51:34.000Z
2022-03-02T10:53:11.000Z
# standard library imports import os # third party imports import numpy as np from PIL import Image import torch.nn as nn from torchvision import transforms # local imports import config from . import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir="./output/results"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS["batch_size"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization of the images along with channel first to channel last steps and finally converting np array to pillow format for saving model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, "image_sheet_{}-epoch{}".format(idx, str(epoch).zfill(3)) + ".jpg"))
41.094118
178
0.742056
3,241
0.927856
0
0
0
0
0
0
278
0.079588
bc50340e05b5a45da8fec5c4d61ac3cccc89e3f0
6,577
py
Python
imggen/fonts.py
p-lambda/unlabeled_outputs
18cda9e922591ec99d70caaa173abbb049ef274b
[ "MIT" ]
4
2021-07-02T03:08:29.000Z
2022-03-12T07:13:13.000Z
imggen/fonts.py
p-lambda/unlabeled_outputs
18cda9e922591ec99d70caaa173abbb049ef274b
[ "MIT" ]
1
2021-12-25T21:24:23.000Z
2021-12-25T21:24:23.000Z
imggen/fonts.py
p-lambda/unlabeled_outputs
18cda9e922591ec99d70caaa173abbb049ef274b
[ "MIT" ]
1
2021-12-26T07:33:45.000Z
2021-12-26T07:33:45.000Z
from pathlib import Path import h5py import numpy as np from torchvision.datasets.vision import VisionDataset from PIL import Image import requests import zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params = { 'id' : id }, stream = True) token = get_confirm_token(response) if token: params = { 'id' : id, 'confirm' : token } response = session.get(URL, params = params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path num_train_domains (int): number of train domains up to 41443 test_mean_chars (bool): Use the mean characters as test set split (str): 'train', 'val', 'test' transform: input transformation target_transform: target transformation download (bool): download or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform = transform self.target_transform = target_transform self.denoise = denoise self.denoise_transform = denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the number of fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f"NUM FONTS: {num_fonts}") print(f"NUM CHARS: {data_by_domain.shape[1]}") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples > train_val_max: # to be able to heuristically test what happens if we have more training data train_val_max = 5000 if split == 'train': idxs = idxs[:num_examples] elif split == 'val': idxs = idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ if self.denoise: img = self.data[index] img = Image.fromarray(img) if self.transform is not None: tgt_img = self.transform(img) if self.denoise_transform is not None: src_img = self.denoise_transform(img) return src_img, tgt_img else: img, target = self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, domain_label def get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, domain_label def __len__(self): return len(self.data)
35.939891
149
0.614414
5,514
0.838376
0
0
0
0
0
0
1,099
0.167097
bc511f5404ed81ec6c064f4f97b303375361769d
774
py
Python
leetcode/47.py
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
1
2019-08-28T23:15:25.000Z
2019-08-28T23:15:25.000Z
leetcode/47.py
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
leetcode/47.py
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
""" link: https://leetcode.com/problems/permutations-ii problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 """ class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1: return [nums] new_nums = nums.copy() new_nums.sort() res = [] for i in range(0, len(new_nums)): if i + 1 < len(new_nums) and new_nums[i] == new_nums[i + 1]: continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] = new_nums[0], new_nums[i] return res
28.666667
73
0.529716
651
0.801724
0
0
0
0
0
0
155
0.190887
bc535e8c70a7ae7d8c05a67decf44c291034483f
2,406
py
Python
adminmgr/media/code/A3/task3/T1_ocefXVJ.py
IamMayankThakur/test-bigdata
cef633eb394419b955bdce479699d0115d8f99c3
[ "Apache-2.0" ]
9
2019-11-08T02:05:27.000Z
2021-12-13T12:06:35.000Z
adminmgr/media/code/A3/task3/T1_ocefXVJ.py
IamMayankThakur/test-bigdata
cef633eb394419b955bdce479699d0115d8f99c3
[ "Apache-2.0" ]
6
2019-11-27T03:23:16.000Z
2021-06-10T19:15:13.000Z
adminmgr/media/code/A3/task3/T1_ocefXVJ.py
IamMayankThakur/test-bigdata
cef633eb394419b955bdce479699d0115d8f99c3
[ "Apache-2.0" ]
4
2019-11-26T17:04:27.000Z
2021-12-13T11:57:03.000Z
import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests def tmp(x): y = (x.split(';')[7]).split(',') return (y) def forf(x): for i in x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for i in res1: if(count==4): print("%s" % i) else: print("%s" % i,end=',') count = count +1 conf=SparkConf() conf.setAppName("BigData") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint("/checkpoint_BIGDATA") ''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream("localhost",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream and then reducing by window: #outpu2 dataStream=ssc.socketTextStream("localhost",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream("localhost",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on each RDD # totalcount.foreachRDD(process_rdd) ssc.start() ssc.awaitTermination(25) ssc.stop()
24.804124
86
0.741895
0
0
39
0.016209
0
0
0
0
1,304
0.541978
bc53c586e44516a506fdeff0f180d92c8730dd5b
908
py
Python
courses/migrations/0003_alter_content_options_alter_module_options_and_more.py
antonnifo/E-Soma
93d49b27dedbff58d19f8245a79693762fc819d5
[ "MIT" ]
1
2022-02-09T06:28:04.000Z
2022-02-09T06:28:04.000Z
courses/migrations/0003_alter_content_options_alter_module_options_and_more.py
antonnifo/E-Soma
93d49b27dedbff58d19f8245a79693762fc819d5
[ "MIT" ]
null
null
null
courses/migrations/0003_alter_content_options_alter_module_options_and_more.py
antonnifo/E-Soma
93d49b27dedbff58d19f8245a79693762fc819d5
[ "MIT" ]
1
2022-02-09T06:29:11.000Z
2022-02-09T06:29:11.000Z
# Generated by Django 4.0.1 on 2022-01-20 13:10 import courses.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), ]
25.942857
67
0.562775
801
0.882159
0
0
0
0
0
0
174
0.19163
bc5478846dead2384e17349d8f75968c543992de
407
py
Python
pkg/maths/maths.py
prateekdegaons1991/experiment-loadtest
b53c70fac5b2f7d37df77844b26f79741c74c1b6
[ "Apache-2.0" ]
8
2020-04-17T06:34:30.000Z
2021-12-18T10:54:50.000Z
pkg/maths/maths.py
oumkale/test-python
1f3d3e42ffbe1bf5ed9df8a0c6038e50129b2c4d
[ "Apache-2.0" ]
15
2020-04-18T06:01:53.000Z
2022-02-15T08:56:25.000Z
pkg/maths/maths.py
oumkale/test-python
1f3d3e42ffbe1bf5ed9df8a0c6038e50129b2c4d
[ "Apache-2.0" ]
12
2020-04-17T05:14:27.000Z
2022-03-29T19:24:20.000Z
#Atoi stands for ASCII to Integer Conversion def atoi(string): res = 0 # Iterate through all characters of # input and update result for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res #Adjustment contains rule of three for calculating an integer given another integer representing a percentage def Adjustment(a, b): return (a * b) / 100
27.133333
109
0.673219
0
0
0
0
0
0
0
0
217
0.53317
bc562cc6c9b35189e9adc0f9ba37a99ec2138c03
3,672
py
Python
google_compute_engine/config_manager.py
redoxdrh/GCP-Flask
34af307df541edca4eee58b1d8be64888550a674
[ "Apache-2.0" ]
2
2017-05-04T08:05:29.000Z
2019-02-08T21:36:11.000Z
google_compute_engine/config_manager.py
redoxdrh/GCP-Flask
34af307df541edca4eee58b1d8be64888550a674
[ "Apache-2.0" ]
null
null
null
google_compute_engine/config_manager.py
redoxdrh/GCP-Flask
34af307df541edca4eee58b1d8be64888550a674
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A library for retrieving and modifying configuration settings.""" import os import textwrap from google_compute_engine import file_utils from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): """Process the configuration defaults.""" def __init__(self, config_file=None, config_header=None): """Constructor. Args: config_file: string, the location of the config file. config_header: string, the message to write at the top of the config. """ self.config_file = config_file or CONFIG self.config_header = config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): """Create a file header in the config. Args: fp: int, a file pointer for writing the header. """ text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\n'.join(['# ' + line for line in text])) fp.write('\n\n') def GetOptionString(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: string, the value of the option or None if the option doesn't exist. """ if self.config.has_option(section, option): return self.config.get(section, option) else: return None def GetOptionBool(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: bool, True if the option is enabled or not set. """ return (not self.config.has_option(section, option) or self.config.getboolean(section, option)) def SetOption(self, section, option, value, overwrite=True): """Set the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to set the value of. value: string, the value to set the option. overwrite: bool, True to overwrite an existing value in the config file. """ if not overwrite and self.config.has_option(section, option): return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None): """Write the config values to a given file. Args: config_file: string, the file location of the config file to write. """ config_file = config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp: if self.config_header: self._AddHeader(config_fp) self.config.write(config_fp)
33.381818
78
0.699891
2,822
0.768519
0
0
0
0
0
0
2,054
0.559368
bc56aa53a834b83d16f942b242b5f67998363eda
22,135
py
Python
mscreen/autodocktools_prepare_py3k/mglutil/web/services/AppService_services.py
e-mayo/mscreen
a50f0b2f7104007c730baa51b4ec65c891008c47
[ "MIT" ]
9
2021-03-06T04:24:28.000Z
2022-01-03T09:53:07.000Z
mglutil/web/services/AppService_services.py
e-mayo/autodocktools-prepare-py3k
2dd2316837bcb7c19384294443b2855e5ccd3e01
[ "BSD-3-Clause" ]
3
2021-03-07T05:37:16.000Z
2021-09-19T15:06:54.000Z
mglutil/web/services/AppService_services.py
e-mayo/autodocktools-prepare-py3k
2dd2316837bcb7c19384294443b2855e5ccd3e01
[ "BSD-3-Clause" ]
4
2019-08-28T23:11:39.000Z
2021-11-27T08:43:36.000Z
################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types import * from .AppService_services_types import \ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from ZSI.TCcompound import Struct from ZSI import client import ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError("method not implemented") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = "https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(":") + [80,] if "host" not in kw: kw["host"] = netloc[0] if "port" not in kw: kw["port"] = int(netloc[1]) if "url" not in kw: kw["url"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self, request): """ @param: request is str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str """ if not isinstance(request, str): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/destroy", **kw) response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\ not issubclass(destroyResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def getAppConfig(self, request): """ @param: request to getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str _tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str _ioType: ns1.IOType_Def _IOType: str, optional _max: int, optional _min: int, optional _name: str, optional _required: boolean, optional _semanticType: str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional _semanticType: str, optional _tag: str, optional _textDesc: str, optional _value: str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean """ if not isinstance(request, getAppConfigRequest) and\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/getAppConfig", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def getAppMetadata(self, request): """ @param: request to getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str _tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str _ioType: ns1.IOType_Def _IOType: str, optional _max: int, optional _min: int, optional _name: str, optional _required: boolean, optional _semanticType: str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional _semanticType: str, optional _tag: str, optional _textDesc: str, optional _value: str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str """ if not isinstance(request, getAppMetadataRequest) and\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/getAppMetadata", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def getOutputAsBase64ByName(self, request): """ @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return: response from getOutputAsBase64ByNameResponse:: _item: str, optional """ if not isinstance(request, getOutputAsBase64ByNameRequest) and\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def getOutputs(self, request): """ @param: request is str @return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr: str, optional _stdOut: str, optional """ if not isinstance(request, str): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/getOutputs", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\ not issubclass(getOutputsResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def launchJob(self, request): """ @param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name: str _numProcs: int, optional @return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str """ if not isinstance(request, launchJobRequest) and\ not issubclass(launchJobRequest, request.__class__): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/launchJob", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\ not issubclass(launchJobResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def launchJobBlocking(self, request): """ @param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name: str _numProcs: int, optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr: str, optional _stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str """ if not isinstance(request, launchJobBlockingRequest) and\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/launchJobBlocking", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response def queryStatus(self, request): """ @param: request is str @return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str """ if not isinstance(request, str): raise TypeError("%s incorrect request type" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None, request, soapaction="http://nbcr.sdsc.edu/opal/queryStatus", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\ not issubclass(queryStatusResponse, response.__class__): raise TypeError("%s incorrect response type" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), "typecode" ): typecode = ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): """wrapper for document:literal message""" typecode = destroyRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): destroyRequest.__init__( self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), "typecode" ): typecode = ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): """wrapper for document:literal message""" typecode = destroyResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): destroyResponse.__init__( self, name=None, ns=None ) class getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname="%s" % name, oname="%s xmlns=\"\"" % name ) class getAppConfigRequestWrapper(getAppConfigRequest): """wrapper for document:literal message""" typecode = getAppConfigRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigRequest.__init__( self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), "typecode" ): typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): """wrapper for document:literal message""" typecode = getAppConfigResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigResponse.__init__( self, name=None, ns=None ) class getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname="%s" % name, oname="%s xmlns=\"\"" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): """wrapper for document:literal message""" typecode = getAppMetadataRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), "typecode" ): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): """wrapper for document:literal message""" typecode = getAppMetadataResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), "typecode" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): """wrapper for document:literal message""" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), "typecode" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): """wrapper for document:literal message""" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), "typecode" ): typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): """wrapper for document:literal message""" typecode = getOutputsRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputsRequest.__init__( self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), "typecode" ): typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): """wrapper for document:literal message""" typecode = getOutputsResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputsResponse.__init__( self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), "typecode" ): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): """wrapper for document:literal message""" typecode = launchJobBlockingRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), "typecode" ): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): """wrapper for document:literal message""" typecode = launchJobBlockingResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), "typecode" ): typecode = ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): """wrapper for document:literal message""" typecode = launchJobRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobRequest.__init__( self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), "typecode" ): typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): """wrapper for document:literal message""" typecode = launchJobResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobResponse.__init__( self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), "typecode" ): typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): """wrapper for document:literal message""" typecode = queryStatusRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): queryStatusRequest.__init__( self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), "typecode" ): typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): """wrapper for document:literal message""" typecode = queryStatusResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): queryStatusResponse.__init__( self, name=None, ns=None )
41.296642
136
0.651096
21,677
0.979309
0
0
0
0
0
0
8,095
0.36571
bc56ca67cc1e81684bbce0d45386183e51cffb90
10,340
py
Python
examples/pytorch/swin/checkpoint_quantization.py
hieuhoang/FasterTransformer
440695ccac874574b1d2e1121788e8fa674b4381
[ "Apache-2.0" ]
null
null
null
examples/pytorch/swin/checkpoint_quantization.py
hieuhoang/FasterTransformer
440695ccac874574b1d2e1121788e8fa674b4381
[ "Apache-2.0" ]
null
null
null
examples/pytorch/swin/checkpoint_quantization.py
hieuhoang/FasterTransformer
440695ccac874574b1d2e1121788e8fa674b4381
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import argparse import re import numpy as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print("Quantizing checkpoint ...") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = ["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2"] amax_name_list = ["attn.qkv._input_quantizer", "attn.qkv._aftergemm_quantizer", "attn.proj._input_quantizer", "attn.proj._aftergemm_quantizer", "attn.matmul_q_input_quantizer", "attn.matmul_k_input_quantizer", "attn.matmul_v_input_quantizer", "attn.matmul_a_input_quantizer", "attn.softmax_input_quantizer", "mlp.fc1._input_quantizer", "mlp.fc1._aftergemm_quantizer", "mlp.fc2._input_quantizer", "mlp.fc2._aftergemm_quantizer", "add1_residual_input_quantizer", "add2_residual_input_quantizer" ] int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = ["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2", "attn.matmul_k_input_quantizer", "attn.matmul_v_input_quantizer"] int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = ["attn.qkv._input_quantizer", "attn.proj._input_quantizer", "mlp.fc1._input_quantizer", "mlp.fc2._input_quantizer", "attn.matmul_q_input_quantizer", "attn.matmul_a_input_quantizer"] int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = ["attn.qkv._aftergemm_quantizer", "attn.proj._aftergemm_quantizer", "mlp.fc1._aftergemm_quantizer", "mlp.fc2._aftergemm_quantizer", "attn.softmax_input_quantizer", "attn.proj._input_quantizer"] downsample_input = "downsample.reduction._input_quantizer" downsample_weight = "downsample.reduction._weight_quantizer" downsample_out = "downsample.reduction._aftergemm_quantizer" factor = 1000000.0 for i in range(layer_num): for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in amax_name_list: quant_max = init_dict["layers.{}.blocks.{}.{}._amax".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 # if verbose: # print(i, amax_name) # print('quant_max:', quant_max) # print('amax:', amax) if i != layer_num - 1: amax = init_dict["layers.{}.{}._amax".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 amax = init_dict["layers.{}.{}._amax".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 else: amax_id += 8 if verbose: print("done process layer_{} block_{} activation amax".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict["layers.{}.blocks.{}.{}.weight".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict["layers.{}.blocks.{}.{}._weight_quantizer._amax".format(i, depth, kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict["layers.{}.blocks.{}.{}.weight".format(i, depth, kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id += 1 # if verbose: # print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i != layer_num - 1: amaxList[amax_id] = init_dict["layers.{}.downsample.reduction._weight_quantizer._amax".format(i)].item() amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i != layer_num - 1: patchMerge_i = init_dict["layers.{}.{}._amax".format(i, downsample_input)].item() patchMerge_w = init_dict["layers.{}.{}._amax".format(i, downsample_weight)].item() patchMerge_o = init_dict["layers.{}.{}._amax".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127 * patchMerge_o) amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for trt fused MHA amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 # #### softmax amax # amaxList[amax_id] = amaxList[28] # amax_id += 1 # #### bmm2 amax # amaxList[amax_id] = amaxList[8] # amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0 * 127.0) amax_id += 1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0 * amaxList[8]) amax_id += 1 init_dict["layers.{}.blocks.{}.amaxList".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print("done process layer_{} block_{} kernel weight".format(i, depth)) if i != layer_num - 1: kernel = init_dict["layers.{}.downsample.reduction.weight".format(i)] quant_max2 = init_dict["layers.{}.downsample.reduction._weight_quantizer._amax".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict["layers.{}.downsample.reduction.weight".format(i)] = kernel_processed # print("Quantizing checkpoint done.") return init_dict if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2, 6, 2])
47.214612
137
0.562186
0
0
0
0
0
0
0
0
3,352
0.324178
bc57b1f771495cf5ea069e99b2859a0f3795d393
6,608
py
Python
mars/deploy/kubernetes/core.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
null
null
null
mars/deploy/kubernetes/core.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
null
null
null
mars/deploy/kubernetes/core.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import random import time from ...actors import new_client, FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): """ Pods watcher class, compatible with SchedulerDiscoverer """ dynamic = True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config, client from gevent.threadpool import ThreadPool if k8s_config is not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): # if conditions not supported, always return True if 'status' not in obj_data or 'conditions' not in obj_data['status']: return True return any(cond['type'] == 'Ready' and cond['status'] == 'True' for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for el in query['items']: name, pod_ep = self._extract_pod_name_ep(el) if pod_ep is not None and not self._extract_pod_ready(el): pod_ep = None result[name] = pod_ep return result def get(self, update=False): if self._pod_to_ep is None or update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a for a in self._pod_to_ep.values() if a is not None) def is_all_ready(self): self.get(True) return all(a is not None for a in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import ReadTimeoutError from kubernetes import watch cur_pods = set(self.get(True)) w = watch.Watch() while True: # when some schedulers are not ready, we refresh faster linger = 10 if self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try: event = self._pool.spawn(next, streamer, StopIteration).result() if event is StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if new_pods != cur_pods: cur_pods = new_pods yield self.get(False) break except: # noqa: E722 logger.exception('Unexpected error when watching on kubernetes') break obj_dict = event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \ if endpoint and self._extract_pod_ready(obj_dict) else None yield self.get(False) class ReadinessActor(FunctionActor): """ Dummy actor indicating service start """ @classmethod def default_uid(cls): return 'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): """ Wait till all containers are ready, both in kubernetes and in ClusterInfoActor """ from ...scheduler.utils import SchedulerClusterInfoActor # check if all schedulers are ready using Kubernetes API sleep_fun = (getattr(self, 'pool', None) or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes, waiting ClusterInfoActor to be ready') # check if all schedulers are registered in ClusterInfoActor actor_client = new_client() while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r', kube_schedulers) break sleep_fun(1) # pragma: no cover def create_scheduler_discoverer(self): self.scheduler_discoverer = K8SPodsIPWatcher(label_selector='name=marsscheduler')
39.333333
100
0.628783
5,840
0.883777
1,512
0.228814
571
0.08641
0
0
1,548
0.234262
bc58243dff3b67ec29b9366a2531008a83301c24
767
py
Python
tests/tests_model/tests_bert_model.py
elangovana/gene_normalisation
9152298e951cd968ee516815c7fa11f1ceabca51
[ "MIT" ]
1
2020-10-21T06:01:28.000Z
2020-10-21T06:01:28.000Z
tests/tests_model/tests_bert_model.py
elangovana/gene_normalisation
9152298e951cd968ee516815c7fa11f1ceabca51
[ "MIT" ]
null
null
null
tests/tests_model/tests_bert_model.py
elangovana/gene_normalisation
9152298e951cd968ee516815c7fa11f1ceabca51
[ "MIT" ]
null
null
null
from unittest import TestCase import torch import transformers from model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size = 10 sequence_len = 20 batch = 32 num_classes = 3 expected_shape = (batch, sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config) # Act actual = sut.forward(input_batch)[0] # Assert self.assertEqual(expected_shape, actual.shape)
26.448276
144
0.688396
660
0.860495
0
0
0
0
0
0
26
0.033898
bc583d8b5318b12422c378e8c294b322b7118447
1,593
py
Python
tests/renderer_test.py
tmcclintock/PyDonJuan
ab6d567b568c3e0dd976b10c2628ad99ca81b953
[ "CC0-1.0" ]
2
2020-12-14T20:50:57.000Z
2021-05-26T04:32:24.000Z
tests/renderer_test.py
tmcclintock/PyDonJuan
ab6d567b568c3e0dd976b10c2628ad99ca81b953
[ "CC0-1.0" ]
29
2020-12-18T15:56:14.000Z
2021-01-12T01:17:48.000Z
tests/renderer_test.py
tmcclintock/donjuan
ab6d567b568c3e0dd976b10c2628ad99ca81b953
[ "CC0-1.0" ]
null
null
null
import json import os import tempfile from unittest import TestCase import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r = Renderer() assert r is not None def test_scale(self): r = Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, "fixtures/dummy_dungeon.json") with open(inpath, "r") as f: darr = json.load(f)["dungeon"] n_rows = len(darr) n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and check for the file fp = os.path.join(self.TEMP_DIR, "rendered_dungeon.png") r = Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() # Render and check for the file fp = os.path.join(self.TEMP_DIR, "rendered_dungeon.png") renderer.render(dungeon, file_path=fp) assert os.path.exists(fp)
28.963636
68
0.622724
1,449
0.909605
0
0
1,156
0.725675
0
0
147
0.092279
bc5a20c1be48c7dd2648cc88a86c05d54e4b6c1c
612
py
Python
src/foremast/validate.py
dnava013/foremast
9849821b5bb3cd67b438c5adeaa0e42f86e9eaf8
[ "Apache-2.0" ]
157
2016-09-12T16:24:14.000Z
2018-06-02T15:40:38.000Z
src/foremast/validate.py
dnava013/foremast
9849821b5bb3cd67b438c5adeaa0e42f86e9eaf8
[ "Apache-2.0" ]
206
2016-09-12T16:41:31.000Z
2018-06-04T21:50:29.000Z
src/foremast/validate.py
dnava013/foremast
9849821b5bb3cd67b438c5adeaa0e42f86e9eaf8
[ "Apache-2.0" ]
34
2016-09-12T16:37:57.000Z
2018-06-04T18:37:52.000Z
"""Spinnaker validate functions.""" import logging from .consts import API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): """Check Gate connection.""" try: credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not valid: API_URL = %s', API_URL) def validate_all(args): """Run all validate steps.""" LOG.debug('Args: %s', args) LOG.info('Running all validate steps.') validate_gate()
23.538462
69
0.673203
0
0
0
0
0
0
0
0
210
0.343137
bc5ad874ef55f36dd52e0759ceb93fea5f606b23
2,437
py
Python
constellation_forms/migrations/0001_initial.py
ConstellationApps/Forms
5d2bacf589c1a473cf619f34d569d33191b11285
[ "ISC" ]
2
2017-04-18T02:41:00.000Z
2017-04-18T02:51:39.000Z
constellation_forms/migrations/0001_initial.py
ConstellationApps/Forms
5d2bacf589c1a473cf619f34d569d33191b11285
[ "ISC" ]
33
2017-03-03T06:16:44.000Z
2019-08-20T23:06:21.000Z
constellation_forms/migrations/0001_initial.py
ConstellationApps/Forms
5d2bacf589c1a473cf619f34d569d33191b11285
[ "ISC" ]
1
2017-02-22T18:48:04.000Z
2017-02-22T18:48:04.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ], options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form', unique_together=set([('form_id', 'version')]), ), ]
37.492308
142
0.552318
2,169
0.890029
0
0
0
0
0
0
401
0.164547
bc5ae8aa40e31ef7936556c55251ff7ab9886286
2,258
py
Python
src/webpy1/src/borough/dbsqli.py
ptphp/PyLib
07ac99cf2deb725475f5771b123b9ea1375f5e65
[ "Apache-2.0" ]
1
2020-02-17T08:18:29.000Z
2020-02-17T08:18:29.000Z
src/webpy1/src/borough/dbsqli.py
ptphp/PyLib
07ac99cf2deb725475f5771b123b9ea1375f5e65
[ "Apache-2.0" ]
null
null
null
src/webpy1/src/borough/dbsqli.py
ptphp/PyLib
07ac99cf2deb725475f5771b123b9ea1375f5e65
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 as sqlite import os.path as osp import sys class Sqli(object): conn = '' cursor = '' def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print what sys.exit() self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print "create table website " self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print 'create website index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''') print "create table com " self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]); ''') print 'create map index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''') print "create table com " self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]); ''') print 'create map index' self.conn.commit() def query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except Exception, what: print what def show(self): r = self.cursor.fetchall() return r def showone(self): return self.cursor.fetchone() def __del__(self): self.cursor.close() self.conn.close()
27.204819
79
0.529672
2,152
0.953056
0
0
0
0
0
0
1,009
0.446856
bc5b677ed37d940fc02b036d43d53f7c6322c3f1
599
py
Python
losses/all_lost.py
Liudzz/loss-chapter
22359b92ca5e155d5af32ef2f22eeddf0483b947
[ "Apache-2.0" ]
2
2020-07-07T00:03:31.000Z
2020-07-08T09:58:48.000Z
losses/all_lost.py
Liudzz/loss-chapter
22359b92ca5e155d5af32ef2f22eeddf0483b947
[ "Apache-2.0" ]
null
null
null
losses/all_lost.py
Liudzz/loss-chapter
22359b92ca5e155d5af32ef2f22eeddf0483b947
[ "Apache-2.0" ]
2
2020-07-08T09:58:56.000Z
2020-07-11T13:43:53.000Z
""" easy way to use losses """ from center_loss import Centerloss import torch.nn as nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss = nn.SmoothL1Loss(pred,label) return loss
22.185185
55
0.729549
0
0
0
0
0
0
0
0
30
0.050083
bc5b680a2cd25d3fd6125ee9f9722bc8e692640b
7,320
py
Python
nova/tests/functional/test_metadata.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2020-08-14T02:20:59.000Z
2020-08-14T02:20:59.000Z
nova/tests/functional/test_metadata.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
2
2021-03-31T20:04:16.000Z
2021-12-13T20:45:03.000Z
nova/tests/functional/test_metadata.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2020-07-24T02:31:45.000Z
2020-07-24T02:31:45.000Z
# Copyright 2016 Rackspace Australia # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures import jsonschema import os import requests from oslo_serialization import jsonutils from oslo_utils import uuidutils from nova import test from nova.tests import fixtures as nova_fixtures from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake as fake_image class fake_result(object): def __init__(self, result): self.status_code = 200 self.text = jsonutils.dumps(result) real_request = requests.request def fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server for the tests server = self._build_server(name='test') server = self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make sure that the metadata service returns information about the # server we created above def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much of the data we pass to the REST service is missing because of # the way we've created the fake instance, but we should at least try # and ensure we're passing _some_ data through to the external REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) # load the jsonschema for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), "../../../doc/api_schemas/network_data.json")) with open(schema_file, 'rb') as f: schema = jsonutils.load(f) jsonschema.validate(res.json(), schema)
37.927461
78
0.639617
5,881
0.803415
0
0
0
0
0
0
2,212
0.302186
bc5dd6bb126db54b8402ce56f75664e9271f9ace
8,889
py
Python
openue/sequence_labeling/subject_labeling_data_manager.py
zxlzr/OpenUE
a49f8950dc2b93a489bb8ce0d40abb26c2c0f347
[ "MIT" ]
8
2020-01-08T13:05:35.000Z
2021-12-20T09:43:57.000Z
openue/sequence_labeling/subject_labeling_data_manager.py
zxlzr/OpenUE
a49f8950dc2b93a489bb8ce0d40abb26c2c0f347
[ "MIT" ]
9
2020-09-25T22:36:51.000Z
2022-02-10T01:50:44.000Z
openue/sequence_labeling/subject_labeling_data_manager.py
zxlzr/OpenUE
a49f8950dc2b93a489bb8ce0d40abb26c2c0f347
[ "MIT" ]
null
null
null
import os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../bert"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) import tokenization from config import config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR="raw_data", DATA_OUTPUT_DIR="SKE_2019_tokened_labeling", vocab_file_path="vocab.txt", do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item in spo_list: predicate = spo_item["predicate"] subject = spo_item["subject"] object = spo_item["object"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list): res = [] res_d = {} predicate = "" for spo_item in spo_list: predicate = spo_item["event"] if 'time' in spo_item: time = spo_item["time"] res.append(('time',time)) if 'location' in spo_item: location = spo_item["location"] res.append(('location',location)) if 'participant' in spo_item: participant = spo_item["participant"] res.append(('participant',participant)) if 'denoter' in spo_item: denoter = spo_item["denoter"] res.append(('denoter',denoter)) if 'object' in spo_item: object = spo_item["object"] res.append(('object',object)) res_d[predicate] = res return res_d def _index_q_list_in_k_list(q_list, k_list): """Known q_list in k_list, find index(first time) of q_list in k_list""" q_list_length = len(q_list) k_list_length = len(k_list) for idx in range(k_list_length - q_list_length + 1): t = [q == k for q, k in zip(q_list, k_list[idx: idx + q_list_length])] # print(idx, t) if all(t): # print(idx) idx_start = idx return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None: tokener_error_flag = True ''' 实体: "1981年" 原句: "●1981年2月27日,中国人口学会成立" so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81', '年', '2', '月', '27', '日', ',', '中', '国', '人', '口', '学', '会', '成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + " @@ " + text + "\n") self.bert_tokener_error_log_f.write(str(so_tokened) + " @@ " + str(text_tokened) + "\n") else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start] = "B-" + so_type if so_tokened_length == 2: labeling_list[idx_start + 1] = "I-" + so_type elif so_tokened_length >= 3: labeling_list[idx_start + 1: idx_start + so_tokened_length] = ["I-" + so_type] * (so_tokened_length - 1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False labeling_list = ["O"] * len(text_tokened) if not self.General_Mode: for (spo_subject, spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject, "SUB") #flag_B = _labeling_type(spo_object, "OBJ") if flag_A or flag_B: tokener_error_flag = True else: for item in spo_list_form: if item[1]== None: continue flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened): """标注被 bert_tokenizer.tokenize 拆分的词语""" if token.startswith("##"): labeling_list[idx] = "[##WordPiece]" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(" ".join(labeling_list)+"\t"+predicate+"\n") self.text_f.write(text + "\n") self.token_in_f.write(" ".join(text_tokened)+"\t"+predicate+"\n") self.token_in_not_UNK_f.write(" ".join(text_tokened_not_UNK) + "\n") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, "train")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, "valid")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, "test")) for file_set_type in ["train", "valid"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), "token_label_and_one_prdicate_out.txt"), "w", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), "bert_tokener_error_log.txt"), "w", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), "text.txt"), "w", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), "token_in.txt"), "w", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), "token_in_not_UNK.txt"), "w", encoding='utf-8') if file_set_type == "train": path_to_raw_data_file = "train.json" elif file_set_type == "valid": path_to_raw_data_file = "valid.json" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers = 0 while True: line = f.readline() if line: count_numbers += 1 r = json.loads(line) text = r["text"] spo_list = r["spo_list"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print("all numbers", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__=="__main__": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = "sequence_labeling_data" Vocab_Path = config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode = General_Mode,DATA_INPUT_DIR=DATA_INPUT_DIR, DATA_OUTPUT_DIR=DATA_OUTPUT_DIR,vocab_file_path=Vocab_Path) model_data.separate_raw_data_and_token_labeling()
49.938202
186
0.582068
8,424
0.929288
0
0
0
0
0
0
1,410
0.155543
bc5ea97eac050b419965fd5ba95918dc58fe5bee
3,222
py
Python
clarifai/rest/grpc/custom_converters/custom_message_to_dict.py
Taik/clarifai-python
c3b66b84cb348d3cb1edff958f561a4734b78650
[ "Apache-2.0" ]
322
2015-08-25T03:16:11.000Z
2021-11-08T09:36:50.000Z
clarifai/rest/grpc/custom_converters/custom_message_to_dict.py
Taik/clarifai-python
c3b66b84cb348d3cb1edff958f561a4734b78650
[ "Apache-2.0" ]
76
2015-10-25T13:03:47.000Z
2022-02-19T09:36:10.000Z
clarifai/rest/grpc/custom_converters/custom_message_to_dict.py
Taik/clarifai-python
c3b66b84cb348d3cb1edff958f561a4734b78650
[ "Apache-2.0" ]
136
2015-09-04T13:48:27.000Z
2021-06-12T16:48:36.000Z
import typing # noqa from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer = _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message, js): """ Because of the fields with the custom extension `cl_show_if_empty`, we need to adjust the original's method's return JSON object and keep these fields. """ js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields and oneof fields will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else: name = field.json_name if name in js: # Skip the field which has been serialized already. continue if _IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self, message): """ Converts Struct message according to Proto3 JSON Specification. However, by default, empty objects {} get converted to null. We overwrite this behavior so {} get converted to {}. """ fields = message.fields ret = {} for key in fields: # When there's a Struct with an empty Struct field, this condition will hold True. # Far as I know this is the only case this condition will be true. If not, this condition # needs to be amended. if fields[key].WhichOneof('kind') is None: json_object = {} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key] = json_object return ret
36.202247
97
0.71198
2,471
0.766915
0
0
0
0
0
0
832
0.258225
bc5ea9e7a84513ea2108b53d14947d94915f3a05
26
py
Python
__init__.py
mschrimpf/CapsNetKeras
4c514860bf6689fb1772a7bd858638cd538ff22f
[ "MIT" ]
null
null
null
__init__.py
mschrimpf/CapsNetKeras
4c514860bf6689fb1772a7bd858638cd538ff22f
[ "MIT" ]
null
null
null
__init__.py
mschrimpf/CapsNetKeras
4c514860bf6689fb1772a7bd858638cd538ff22f
[ "MIT" ]
null
null
null
from .capsulenet import *
13
25
0.769231
0
0
0
0
0
0
0
0
0
0
bc5eeaf616c5264490632d3b43d2af7080e1aea8
28,625
py
Python
gate/mate_ksx3267v2.py
mrchoi87/IRSOSv4
886c3dcbeb64c3a8cc257b58692946fd5462312e
[ "BSD-3-Clause" ]
null
null
null
gate/mate_ksx3267v2.py
mrchoi87/IRSOSv4
886c3dcbeb64c3a8cc257b58692946fd5462312e
[ "BSD-3-Clause" ]
null
null
null
gate/mate_ksx3267v2.py
mrchoi87/IRSOSv4
886c3dcbeb64c3a8cc257b58692946fd5462312e
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # import struct import time import socket import select import traceback import hashlib import json from enum import IntEnum from threading import Thread, Lock from mate import Mate, ThreadMate, DevType from mblock import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE = 1 ACTNODE = 2 INTNODE = 3 NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 = 101 TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION = "KSX3267_0.1" _KEYWORDS = {"value" : (2, "float"), "status" : (1, "status"), "opid" : (1, "short"), "state-hold-time" : (2, "int"), "ratio": (1, "short"), "position" : (1, "short"), "remain-time" : (2, "int"), "control": (1, "control"), "area" : (1, "short"), "alert" : (1, "alert"), "hold-time" : (2, "int"), "operation" : (1, "operation"), "time" : (2, "int"), "opentime" : (1, "short"), "closetime" : (1, "short"), "EC": (2, "float"), "pH": (2, "float"), "on-sec" : (1, "short"), "start-area" : (1, "short"), "stop-area": (1, "short"), "epoch" : (2, "int"), "vfloat": (2, "float"), "vint" : (2, "int")} _DEVINFOREG = 2 _DEVCODEREG = 101 def __init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout = 3 if "timeout" not in option else option["timeout"] self._conn = {} self._tempthd = [] self._isdetecting = False self._detection = {"port": [], "saddr":0, "eaddr":0, "opid":0} #self._nodes = self._devinfo.getgw()["children"] self._lock = Lock() self._logger.info("KSX3267MateV2 Started.") def detect_node(self, conn, unit, registers): print "detect_node", unit, registers compcode = registers[0] nodecode = registers[2] size = registers[4] while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res is None or res.isError(): self._logger.warn("Fail to get devices from " + str(unit) + " " + str(res)) return None if len(res.registers) != size: self._logger.info("retry to get data since size of data is not matched. " + str(size) + " " + str(len(res.registers))) continue return {"compcode" : compcode, "nodecode" : nodecode, "devcodes": res.registers} def getdk(self, dev, idx): dk = json.loads(dev["dk"]) return dk[idx] def setdetection(self, flag, opid=0): self._isdetecting = flag self._detection["opid"] = opid def startdetection(self, params, opid): if self._detection["opid"] != 0: self._logger.info("detection is processing.... so this command would be ignored.") return ResCode.FAIL self.setdetection(True, opid) if params: self._detection["saddr"] = params['saddr'] self._detection["eaddr"] = params['eaddr'] self._detection["port"] = params['port'] else: self._detection["saddr"] = 1 self._detection["eaddr"] = 12 self._detection["port"] = None return ResCode.OK def readregister(self, conn, addr, count, unit): print "....... before lock for read" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info("read_holding_registers: " + str(unit) + " " + str(addr) + " " + str(count)) print "read register", unit, addr, count try: return conn.read_holding_registers(addr, count, unit=unit) except Exception as ex: self._logger.warn("fail to read holding registers. : " + str(ex)) return None def detect(self): detected = {} for port, conn in self._conn.iteritems(): if self._isdetecting == False or self.isexecuting() == False: self._logger.info("Total detection is canceled.") break info = self.detectone(port, conn) detected[port] = info self._logger.info ("finished to detect devices : " + str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if noti: noti.setkeyvalue("opid", self._detection["opid"]) for port, info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self, port, conn): detected = {} if self._detection["port"] is not None and port not in self._detection["port"]: return detected #mrchoi87 #for unit in range(self._detection["saddr"], 12): for unit in range(self._detection["saddr"], self._detection["eaddr"]): if self._isdetecting == False or self.isexecuting() == False: self._logger.info("A port " + str(port) + " detection is canceled.") break tempid = port + "-" + str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if noti: noti.setkeyvalue("opid", self._detection["opid"]) self.writecb(noti) noti = None info = None res = None for _ in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res is None or res.isError(): continue if len(res.registers) != 6: self._logger.info("retry to get data since size of data is not matched. 6 " + str(len(res.registers))) continue break if res is None or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info ("Fail to get information from a node : " + str(unit) + " " + str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers) self._logger.info ("Found a node : " + str(unit) + " " + str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version elif res.registers[1] == NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers) self._logger.info ("Found a nutrient system : " + str(unit) + " " + str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if noti is None: if info is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find a node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) # found a node detected[unit] = info noti.setkeyvalue("opid", self._detection["opid"]) print "noti", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue("opid", self._detection["opid"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self, opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info("listen : " + str(opt)) executing = True while executing: self._logger.info("waiting a client~") rsoc, wsoc, esoc = select.select([servsoc], [], [], 10) for sock in rsoc: if sock == servsoc: clisoc, address = servsoc.accept() self._logger.info("client connected from " + str(address)) for tmp in self._tempthd: if tmp["port"] == opt["port"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt["port"]] = conn tmp["status"] = 10 # connected executing = False except Exception as ex: servsoc.close() for tmp in self._tempthd: if tmp["port"] == opt["port"]: self._logger.warn(" port [" + str(opt["port"]) + "] exception : " + str(ex)) tmp["status"] = 5 # error def listen(self, opt): tmp = {"thd" : Thread(target=self._listen, args=(opt)), "status": 0, "port":opt['port']} self._tempthd.append(tmp) tmp["thd"].start() def checktempthreads(self): for tmp in self._tempthd: if tmp["status"] > 2: tmp["thd"].stop() tmp["thd"].join() def connectone(self, opt): ret = False conn = None if opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg = "failed to connect with rtu" code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect() msg = "failed to connect with tcp" code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info("It would wait for a while to connect a client.") ret = self.listen(opt) msg = "failed to connect with tcp" code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn = None else: msg = "It's a wrong connection method. " + str(opt['method']) if ret == False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti) return conn def connect(self): ret = False for opt in self._option['conn']: conn = self.connectone(opt) if conn: self._conn[opt["port"][8:]] = conn super(KSX3267MateV2, self).connect() return ret def closeone(self, port): self._conn[port].close() def close(self): for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq = [] for gw in self._devinfo: for nd in gw["children"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev, request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation = request.getcommand() params = request.getparams() params["operation"] = operation # need to convert by case params["opid"] = request.getopid() # need to convert by case properparams = CmdCode.getparams(operation) + ["operation", "opid"] registers = [] for key in self.getdk(dev, 4): if key not in properparams: # key param is not used for this operation # However, the register should be filled. val = 0 elif key in params: val = params[key] else: self._logger.warn("Wrong Keyword : " + str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == "int": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == "float": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn("This param is needed for this operation. " + str(params['operation']) + ", " + str(key)) # return ResCode.FAIL_WRONG_KEYWORD print "....... befor lock for write" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print "....... lock for write", self.getdk(dev, 3), registers res = self._conn[gw["dk"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError(): self._logger.warn("Fail to write a request to dev." + str(dev) + "," + str(res) + ":" + str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if msg is None: self._logger.warn("Fail to read dev status.") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk): print "received message", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn("The message is not request. " + str(blk.gettype())) return False response = Response(blk) cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params = blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print "detect device" code = self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print "cancel to detect device" code = self.canceldetection(params) else: self._logger.warn("Unknown Error. " + str(blk) + ", " + str(dev)) code = ResCode.FAIL elif dev is None: self._logger.warn("There is no device. " + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn("The request is not proper. " + str(cmd) + " " + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev, blk, nd) self._logger.info("Actuator processed : " + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info("Gateway does not receive a request") code = ResCode.FAIL else: self._logger.warn("Unknown Error. " + str(blk) + ", " + str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info("write response: " + str(response)) self.writecb(response) return True #if code == ResCode.OK else False def parseregisters(self, names, values): idx = 0 ret = {} for nm in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype == "float": val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype == "int": val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val = values[idx] ret[nm] = val idx = idx + size print "parsed", ret return ret def readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev, 2)) #for _ in range(3): res = self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0)) if res is None: self._logger.warn("fail to get status from " + str(dev['dk'])) # break elif res.isError(): self._logger.info("retry to get status from " + str(dev['dk']) + " " + str(res)) # continue else: if len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info("retry to get data since size of data is not matched. " + str(size) + " " + str(len(res.registers))) return None def readnodeinfo(self, node): ret = {"id" : node["id"], "sen" : {}, "act" : {}, "nd" : {"status":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node["id"]) conn = self._conn[gw["dk"]] ret["conn"] = conn info = self.readinfofromdev(conn, node) if info: ret["nd"] = info else: self._logger.warn("fail to read node info : " + str(node)) return ret def readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev["dt"]): info = self.readinfofromdev(ret["conn"], dev) if info: ret["sen"][dev["id"]] = info #else: # self._logger.warn("fail to read sensor info : " + str(dev) + " however continue to read other device") return ret def readactnodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev["dt"]) == False: info = self.readinfofromdev(ret["conn"], dev) if info: ret["act"][dev["id"]] = info else: self._logger.warn("fail to read actuator info : " + str(dev) + " however continue to read other device") return ret def readactinfo(self, node, act): ret = self.readnodeinfo(node) info = self.readinfofromdev(ret["conn"], act) if info: ret["act"][act["id"]] = info else: self._logger.warn("fail to read actuator info : " + str(act) + " however continue to read other device") return ret def sendobs(self): for msg in self._msgq: if msg is None: continue self.sendobservation(msg) def sendnoti(self): for gw in self._devinfo: for node in gw["children"]: ret = self.readnodeinfo(node) i = 1 for dev in node['children']: if DevType.issensor(dev["dt"]) == False: info = self.readinfofromdev(ret["conn"], dev) if info: ret["act"][dev["id"]] = info i = i + 1 if i % 3 == 0: self.sendnoticeforactuatorstatus(ret) ret["act"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo["nd"]["status"]) == False: ndinfo["nd"]["status"] = StatCode.ERROR.value obsblk = Observation(ndinfo["id"]) obsblk.setobservation(ndinfo["id"], 0, StatCode(ndinfo["nd"]["status"])) for devid, info in ndinfo["sen"].iteritems(): if StatCode.has_value(info["status"]) == False: info["status"] = StatCode.ERROR.value obsblk.setobservation(devid, info["value"], StatCode(info["status"])) # do not send observation for actuator #for devid, info in ndinfo["act"].iteritems(): # if StatCode.has_value(info["status"]) == False: # info["status"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info["status"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo["id"], NotiCode.ACTUATOR_STATUS, ndinfo["id"], ndinfo["nd"]) for devid, info in ndinfo["act"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True def stop(self): super(KSX3267MateV2, self).stop() return True def getsize(self, lst): size =0 for k in lst: if k in KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn("wrong keyword : " + str(k)) return -1 return size if __name__ == "__main__": isnutri = False opt = { 'conn' : [{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }] } nutriinfo = [{ "id" : "1", "dk" : "", "dt": "gw", "children" : [{ "id" : "101", "dk" : '[1,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ {"id" : "102", "dk" : '[1,40211,["control","status","area","alert","opid"],45001,["operation", "opid", "control","EC","pH", "start-area", "stop-area", "on-sec"]]', "dt": "nutrient-supply/level1"}, {"id" : "103", "dk" : '[1,40221,["value","status"]]', "dt": "sen"}, {"id" : "104", "dk" : '[1,40231,["value","status"]]', "dt": "sen"}, {"id" : "105", "dk" : '[1,40241,["value","status"]]', "dt": "sen"}, {"id" : "106", "dk" : '[1,40251,["value","status"]]', "dt": "sen"}, {"id" : "107", "dk" : '[1,40261,["value","status"]]', "dt": "sen"}, {"id" : "109", "dk" : '[1,40271,["value","status"]]', "dt": "sen"}, {"id" : "110", "dk" : '[1,40281,["value","status"]]', "dt": "sen"}, {"id" : "111", "dk" : '[1,40291,["value","status"]]', "dt": "sen"}, {"id" : "112", "dk" : '[1,40301,["value","status"]]', "dt": "sen"}, {"id" : "113", "dk" : '[1,40311,["value","status"]]', "dt": "sen"} ]} ]} ] devinfo = [{ "id" : "1", "dk" : "JND2", "dt": "gw", "children" : [ # { # "id" : "101", "dk" : '[1,201,["status"],301,["operation","opid"]]', "dt": "nd", "children" : [ #{"id" : "102", "dk" : '[1,210,["value","status"]]', "dt": "sen"}, #{"id" : "103", "dk" : '[1,220,["value","status"]]', "dt": "sen"} # "id" : "101", "dk" : '[1,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ #{"id" : "102", "dk" : '[1,41010,["value","status"]]', "dt": "sen"}, #{"id" : "103", "dk" : '[1,41020,["value","status"]]', "dt": "sen"} # {"id" : "102", "dk" : '[1,40202,["value","status"]]', "dt": "sen"}, # {"id" : "103", "dk" : '[1,40205,["value","status"]]', "dt": "sen"}, #{"id" : "104", "dk" : '[1,40208,["value","status"]]', "dt": "sen"}, # {"id" : "105", "dk" : '[1,40211,["value","status"]]', "dt": "sen"}, #{"id" : "106", "dk" : '[1,40251,["value","status"]]', "dt": "sen"}, #{"id" : "107", "dk" : '[1,40261,["value","status"]]', "dt": "sen"}, #{"id" : "108", "dk" : '[1,40271,["value","status"]]', "dt": "sen"}, #{"id" : "109", "dk" : '[1,40281,["value","status"]]', "dt": "sen"}, #{"id" : "110", "dk" : '[1,40291,["value","status"]]', "dt": "sen"} # ] # } ] }] """ }, { "id" : "201", "dk" : '[2,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ {"id" : "202", "dk" : '[2,40202,["opid","status","state-hold-time","remain-time"],40206,["operation","opid","time"]]', "dt": "act/retractable/level1"}, {"id" : "202", "dk" : '[2,40209,["opid","status","state-hold-time","remain-time"],40213,["operation","opid","time"]]', "dt": "act/retractable/level1"}, {"id" : "203", "dk" : '[2,40216,["value","status"]]', "dt": "sen"}, {"id" : "204", "dk" : '[2,40219,["value","status"]]', "dt": "sen"}, #{"id" : "203", "dk" : (2,40221,["opid","status"],45021,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "204", "dk" : (2,40231,["opid","status"],45031,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "205", "dk" : (2,40241,["opid","status"],45041,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "206", "dk" : (2,40251,["opid","status"],45051,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "207", "dk" : (2,40261,["opid","status"],45061,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "208", "dk" : (2,40271,["opid","status"],45071,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "209", "dk" : (2,40281,["opid","status"],45081,["operation","opid"]), "dt": "act/switch/level0"} ] }, { "id" : "301", "dk" : (3,40201,["opid","status"],45001,["operation","opid"]), "dt": "nd", "children" : [ {"id" : "302", "dk" : (3,40211,["opid","status"],45011,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "303", "dk" : (3,40221,["opid","status"],45021,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "304", "dk" : (3,40231,["opid","status"],45031,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "305", "dk" : (3,40241,["opid","status"],45041,["operation","opid"]), "dt": "act/retractable/level0"} ] }] }] """ if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, "1", None) else: kdmate = KSX3267MateV2(opt, devinfo, "1", None) mate = Mate ({}, [], "1", None) kdmate.start (mate.writeblk) print "mate started" time.sleep(10) req = Request(None) req.setcommand("1", CmdCode.DETECT_DEVICE, None) print "=======================================#1" kdmate.writeblk(req) print "=======================================#1" """ time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.CANCEL_DETECT, {}) print "=======================================#2" kdmate.writeblk(req) print "=======================================#2" time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.DETECT_DEVICE, None) print "=======================================#3" kdmate.writeblk(req) print "=======================================#3" time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.CANCEL_DETECT, {}) print "=======================================#4" kdmate.writeblk(req) print "=======================================#4" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {"time":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {"time":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) """ time.sleep(30) kdmate.stop() print "mate stopped"
40.71835
212
0.516681
21,232
0.741729
0
0
0
0
0
0
9,572
0.334393
bc60aeeb26d899f8ba324554b05c50b567a13167
6,525
py
Python
CircleciScripts/run_integrationtests.py
aimalygin/aws-sdk-ios
6cfaa3c56296300499f4885e9039c2dd24624cfa
[ "Apache-2.0" ]
17
2018-02-19T16:29:51.000Z
2020-04-03T13:52:52.000Z
CircleciScripts/run_integrationtests.py
aimalygin/aws-sdk-ios
6cfaa3c56296300499f4885e9039c2dd24624cfa
[ "Apache-2.0" ]
2
2019-11-07T15:23:33.000Z
2020-03-12T18:46:47.000Z
CircleciScripts/run_integrationtests.py
aimalygin/aws-sdk-ios
6cfaa3c56296300499f4885e9039c2dd24624cfa
[ "Apache-2.0" ]
10
2018-03-06T14:27:12.000Z
2020-10-20T22:01:30.000Z
import demjson import sys from subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree as ET import os from datetime import datetime from functions import runcommand #from sets import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root = tree.getroot() testbundle = root.get('name') testbundle = testbundle[0:len(testbundle) - 7] failedtests = set() #TODO we can filter with condtion for testsuite in root.findall(".//testsuite"): for testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename = testcase.get('name') if withBundle: failedtests.add(testbundle + '/' + suitename + '/' + casename) else: failedtests.add(suitename + '/' + casename) return failedtests #run test def runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath, timeout = 0): runcommand("rm raw.log") runcommand("rm xcpretty.log") testcommand = "xcodebuild test-without-building -project {0} -scheme {1} -sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=" " + otherargments; rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print("Formatting test result .......") xcprettycommand = "cat raw.log | xcpretty -r junit | tee xcpretty.log" runcommand(xcprettycommand) return exit_code ########################## main function ############################### # a command will like if (len(sys.argv) < 3 or sys.argv[1] == '-h' or sys.argv[1] == '-h') : print("Usage: \r\n {0} <integrationTestsConfiguration json file path> <test result location> <group name>".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print("group name:", group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print("projectName, projectPath, schemeName, destination", projectName, projectPath, schemeName, destination) # testcommandhead = f"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'" # testcommandtail = " | tee raw.log | xcpretty -r junit | tee xcpretty.log" runcommand('echo "export testresult=0" >> $BASH_ENV') testresult = 0 for testname in testlist: print("-------------------------------", testname , "-------------------------------"); test = testlist[testname] testarguments = ' -only-testing:' + testname #create skipping tests parameters skipingtests = "" if 'excludetests' in test: for skipingtest in test['excludetests']: skipingtests += ' -skip-testing:' + testname+ "/" + skipingtest print("excludetests:", skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, "exit code:", exit_code) # if test fails, check if the failed tests can be retried if exit_code == 65: retriabletimes = 3 ; if 'retriabletimes' in test: retriabletimes = test['retriabletimes'] if retriabletimes > 1: #get all failed test cases faileds = getfailedcases() if len(faileds) == 0 : print("test command return an error code, but the failed test cases is 0") print("exit code:", exit_code) break; print("failed tests:",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and exit_code > 0: print("retry ", testname, "for ", retrytimes, " times") testarguments = "" for failed in faileds: testarguments += ' -only-testing:' + failed retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print("retry exit code:", exit_code) if(exit_code != 0 ): faileds = getfailedcases() if exit_code != 0 : print("exit code:", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo "{2}" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code == 65 : failedtests = getfailedcases(False) print("failedtests:", failedtests) if 'ignoreFailures' in test and failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print("There are failed testcases that can be ignored") ignorefailure = True; else : print("Failed testcases that cannot be ignored: ", failedtests - ignoreFailures ) if not ignorefailure: print("There are faillures in the test") testresult = 1 else: print("Test succeed") print("testresult:", testresult) runcommand('echo "export testresult={0}" >> $BASH_ENV'.format(testresult))
42.927632
222
0.632337
0
0
0
0
0
0
0
0
2,042
0.31295
bc60d0aa50b7ae50518bf50520f50484fbc32b50
572
py
Python
seagrass/hooks/__init__.py
kernelmethod/Seagrass
52c5f1852fb2d52b3d94411c2a49c3da6fab6c6c
[ "BSD-2-Clause" ]
null
null
null
seagrass/hooks/__init__.py
kernelmethod/Seagrass
52c5f1852fb2d52b3d94411c2a49c3da6fab6c6c
[ "BSD-2-Clause" ]
21
2021-06-07T20:10:46.000Z
2021-07-07T22:14:25.000Z
seagrass/hooks/__init__.py
kernelmethod/Seagrass
52c5f1852fb2d52b3d94411c2a49c3da6fab6c6c
[ "BSD-2-Clause" ]
null
null
null
# flake8: noqa: F401 from .context_manager_hook import ContextManagerHook from .counter_hook import CounterHook from .file_open_hook import FileOpenHook from .logging_hook import LoggingHook from .profiler_hook import ProfilerHook from .runtime_audit_hook import RuntimeAuditHook from .stack_trace_hook import StackTraceHook from .timer_hook import TimerHook from .tracing_hook import TracingHook __all__ = [ "CounterHook", "FileOpenHook", "LoggingHook", "ProfilerHook", "StackTraceHook", "RuntimeAuditHook", "TimerHook", "TracingHook", ]
26
52
0.783217
0
0
0
0
0
0
0
0
132
0.230769
bc613b321946268bd365a901afc58d30c0ee1a72
3,549
py
Python
tests/test_internal.py
aschleg/hypy
d5b8451dcd24b803bbf2eebc46bc3acfd64d8edc
[ "MIT" ]
40
2018-08-04T15:36:31.000Z
2022-03-12T02:06:28.000Z
tests/test_internal.py
aschleg/hypy
d5b8451dcd24b803bbf2eebc46bc3acfd64d8edc
[ "MIT" ]
5
2018-06-17T12:44:59.000Z
2021-09-28T01:10:26.000Z
tests/test_internal.py
aschleg/hypy
d5b8451dcd24b803bbf2eebc46bc3acfd64d8edc
[ "MIT" ]
8
2018-08-19T14:28:44.000Z
2021-12-20T18:52:07.000Z
import pytest import numpy as np import pandas as pd from hypothetical._lib import _build_des_mat def test_array(): d = np.array([[1., 1.11, 2.569, 3.58, 0.76], [1., 1.19, 2.928, 3.75, 0.821], [1., 1.09, 2.865, 3.93, 0.928], [1., 1.25, 3.844, 3.94, 1.009], [1., 1.11, 3.027, 3.6, 0.766], [1., 1.08, 2.336, 3.51, 0.726], [1., 1.11, 3.211, 3.98, 1.209], [1., 1.16, 3.037, 3.62, 0.75], [2., 1.05, 2.074, 4.09, 1.036], [2., 1.17, 2.885, 4.06, 1.094], [2., 1.11, 3.378, 4.87, 1.635], [2., 1.25, 3.906, 4.98, 1.517], [2., 1.17, 2.782, 4.38, 1.197], [2., 1.15, 3.018, 4.65, 1.244], [2., 1.17, 3.383, 4.69, 1.495], [2., 1.19, 3.447, 4.4, 1.026], [3., 1.07, 2.505, 3.76, 0.912], [3., 0.99, 2.315, 4.44, 1.398], [3., 1.06, 2.667, 4.38, 1.197], [3., 1.02, 2.39, 4.67, 1.613], [3., 1.15, 3.021, 4.48, 1.476], [3., 1.2, 3.085, 4.78, 1.571], [3., 1.2, 3.308, 4.57, 1.506], [3., 1.17, 3.231, 4.56, 1.458], [4., 1.22, 2.838, 3.89, 0.944], [4., 1.03, 2.351, 4.05, 1.241], [4., 1.14, 3.001, 4.05, 1.023], [4., 1.01, 2.439, 3.92, 1.067], [4., 0.99, 2.199, 3.27, 0.693], [4., 1.11, 3.318, 3.95, 1.085], [4., 1.2, 3.601, 4.27, 1.242], [4., 1.08, 3.291, 3.85, 1.017], [5., 0.91, 1.532, 4.04, 1.084], [5., 1.15, 2.552, 4.16, 1.151], [5., 1.14, 3.083, 4.79, 1.381], [5., 1.05, 2.33, 4.42, 1.242], [5., 0.99, 2.079, 3.47, 0.673], [5., 1.22, 3.366, 4.41, 1.137], [5., 1.05, 2.416, 4.64, 1.455], [5., 1.13, 3.1, 4.57, 1.325], [6., 1.11, 2.813, 3.76, 0.8], [6., 0.75, 0.84, 3.14, 0.606], [6., 1.05, 2.199, 3.75, 0.79], [6., 1.02, 2.132, 3.99, 0.853], [6., 1.05, 1.949, 3.34, 0.61], [6., 1.07, 2.251, 3.21, 0.562], [6., 1.13, 3.064, 3.63, 0.707], [6., 1.11, 2.469, 3.95, 0.952]]) return d def test_build_design_matrix(): dat = test_array() dat_df = pd.DataFrame(dat) des_mat = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=dat[:, 0]) des_mat_df = _build_des_mat(dat_df[1], dat_df[2], dat_df[3], dat_df[4], group=dat_df[0]) des_mat_no_group = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4]) des_mat_group_df = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=pd.DataFrame(dat[:, 0])) des_mat_group_df = _build_des_mat(dat[:, 1], dat[:, 2], dat[:, 3], dat[:, 4], group=pd.DataFrame(dat[:, 0])) assert isinstance(des_mat, np.ndarray) assert des_mat.shape == dat.shape assert isinstance(des_mat_df, np.ndarray) assert des_mat_df.shape == dat.shape assert isinstance(des_mat_no_group, np.ndarray) assert des_mat_no_group.shape[1] == 2 assert isinstance(des_mat, np.ndarray) assert des_mat_group_df.shape == dat.shape def test_build_matrix(): arr1 = [4, 4, 5, 5, 3, 2, 5] arr2 = [2, 3, 3, 3, 3, 3, 3]
39.876404
112
0.412511
0
0
0
0
0
0
0
0
0
0
bc633f72ddfead99679ba43f47af451833e0fa30
3,563
py
Python
download.py
JamesWang007/Open3D-PointNet
402847ceef8d364672ca7d81e0afebcb445cceb5
[ "MIT" ]
120
2019-04-06T16:04:01.000Z
2021-07-22T17:07:51.000Z
test/Open3D-PointNet-master/download.py
AhsanulIslam/Thesis_Computer_Vision
c308cce15146a33a3e474790b0f9535ee9e41eb7
[ "MIT" ]
null
null
null
test/Open3D-PointNet-master/download.py
AhsanulIslam/Thesis_Computer_Vision
c308cce15146a33a3e474790b0f9535ee9e41eb7
[ "MIT" ]
25
2019-04-08T09:39:47.000Z
2021-05-12T15:39:56.000Z
#!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Download big files from Google Drive.""" import shutil import sys import requests import os import time import urllib.request import zipfile def reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = time.time() - start_time progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) if percent % 5 == 0: sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush() def sizeof_fmt(num, suffix='B'): # https://stackoverflow.com/a/1094933/5308925 for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1000.0: return "%3.2f%s%s" % (num, unit, suffix) num /= 1000.0 return "%.2f%s%s" % (num, 'Yi', suffix) def print_status(destination, progress): message = "Downloading %s... %s" % (destination, sizeof_fmt(progress)) empty_space = shutil.get_terminal_size((80, 20)).columns - len(message) sys.stdout.write('\r' + message + empty_space * ' ') sys.stdout.flush() def download_file_from_google_drive(id, destination): # https://stackoverflow.com/a/39225039/5308925 def save_response_content(response, destination): chunk_size = 32768 written_size = 0 with open(destination, "wb") as f: for chunk in response.iter_content(chunk_size): if chunk: # filter out keep-alive new chunks f.write(chunk) written_size += chunk_size print_status(destination, written_size) print('Done.') def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None url = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(url, params={'id': id}, stream=True) token = get_confirm_token(response) if token: params = {'id': id, 'confirm': token} response = session.get(url, params=params, stream=True) save_response_content(response, destination) def download_contents(): # download model model_path = './cls_model.pth' if os.path.isfile(model_path): print('Model file already downloaded in', model_path) else: download_file_from_google_drive('1WWf5B5fmik5_P1dwxltJ-atRkYeCcCC5', './cls_model.pth') # download dataset dataset_path = './shapenetcore_partanno_segmentation_benchmark_v0.zip' if os.path.isfile(dataset_path): print('Dataset file already downloaded in', dataset_path) else: dataset_url = 'https://shapenet.cs.stanford.edu/ericyi/shapenetcore_partanno_segmentation_benchmark_v0.zip' urllib.request.urlretrieve(dataset_url, os.path.basename(dataset_url), reporthook) # unzip dataset zip_ref = zipfile.ZipFile(os.path.basename(dataset_url), 'r') zip_ref.extractall('.') zip_ref.close() print('Now unzipping...Wait for 2 minutes ish...!') return 0 if __name__ == '__main__': download_contents()
31.8125
115
0.646646
0
0
0
0
0
0
0
0
1,019
0.285995
bc63b363d6718bb79d14c412bc96475ee3170b28
763
py
Python
ls12/demo5.py
cklwblove/python-100-days-source-code
5d66c7708047f0d7bac0ce05d21834bbbfa6ccf1
[ "MIT" ]
null
null
null
ls12/demo5.py
cklwblove/python-100-days-source-code
5d66c7708047f0d7bac0ce05d21834bbbfa6ccf1
[ "MIT" ]
null
null
null
ls12/demo5.py
cklwblove/python-100-days-source-code
5d66c7708047f0d7bac0ce05d21834bbbfa6ccf1
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ 将耗时间的任务放到线程中以获得更好的用户体验。 """ import time import tkinter import tkinter.messagebox def download(): # 模拟下载任务需要花费10秒时间 time.sleep(10) tkinter.messagebox.showinfo('提示', '下载完成') def show_about(): tkinter.messagebox.showinfo('关于', '作者:罗浩') def main(): top = tkinter.Tk() top.title('单线程') top.geometry('200x150') top.wm_attributes('-topmost', True) panel = tkinter.Frame(top) button1 = tkinter.Button(panel, text='下载', command=download) button1.pack(side='left') button2 = tkinter.Button(panel, text='关于', command=show_about) button2.pack(side='right') panel.pack(side='bottom') tkinter.mainloop() if __name__ == '__main__': main()
20.078947
67
0.621232
0
0
0
0
0
0
0
0
271
0.309714
bc652014fdf4755fbb2d576c8ff7469edba046ae
3,250
py
Python
hangupsbot/sinks/gitlab/simplepush.py
mygreentour/hangoutsbot
9ea2da10f546e6f1dd06c8240187049501c5452a
[ "Unlicense" ]
null
null
null
hangupsbot/sinks/gitlab/simplepush.py
mygreentour/hangoutsbot
9ea2da10f546e6f1dd06c8240187049501c5452a
[ "Unlicense" ]
null
null
null
hangupsbot/sinks/gitlab/simplepush.py
mygreentour/hangoutsbot
9ea2da10f546e6f1dd06c8240187049501c5452a
[ "Unlicense" ]
null
null
null
""" GitLab webhook receiver - see http://doc.gitlab.com/ee/web_hooks/web_hooks.html """ import asyncio import json import logging from sinks.base_bot_request_handler import AsyncRequestHandler logger = logging.getLogger(__name__) try: import dateutil.parser except ImportError: logger.error("missing module python_dateutil: pip3 install python_dateutil") raise class webhookReceiver(AsyncRequestHandler): """Receive REST API posts from GitLab""" _bot = None @asyncio.coroutine def process_request(self, path, dummy_query_string, content): """Process a received POST to a given converstation""" path = path.split("/") conv_or_user_id = path[1] if conv_or_user_id is None: logger.error("conversation or user id must be provided as part of path") return try: payload = json.loads(content) except json.JSONDecodeError as err: logger.exception("invalid payload @%d:%d: %s", err.lineno, err.colno, err) logger.error("GitLab message: %s", json.dumps(payload)) refs = payload.get("ref", '').split("/") user = payload.get("user_name") if not user: user = payload["user"]["name"] message = ["GitLab update for [{}]({}) by __{}__".format( payload["project"]["name"], payload["project"]["web_url"], user)] if payload["object_kind"] == "push": message.append("Pushed {} commit(s) on {} branch:".format( payload["total_commits_count"], "/".join(refs[2:]))) for commit in payload["commits"]: message.append("{} -- {} at [{:%c}]({})".format( commit["message"], commit["author"]["name"], dateutil.parser.parse(commit["timestamp"]), commit["url"])) elif payload["object_kind"] == "tag_push": message.append("Pushed tag {}]".format("/".join(refs[2:]))) elif payload["object_kind"] == "issue": issue = payload["object_attributes"] message.append("Update {} issue {} at {:%c}\n[{}]({})".format( issue["state"], issue["id"], dateutil.parser.parse(issue["updated_at"]), issue["title"], issue["url"])) elif payload["object_kind"] == "note": note = payload["object_attributes"] message.append("{} note on {}: [{}]({})".format( note["notable_type"], note["id"], note["note"], note["url"])) elif payload["object_kind"] == "merge_request": request = payload["object_attributes"] message.append("Merge request {}: from [{}:{}]({}) to [{}:{}]({})".format( request["id"], request["source"]["name"], request["source_branch"], request["source"]["web_url"], request["target"]["name"], request["target_branch"], request["target"]["web_url"])) else: message.append("{}: unknown gitlab webhook object kind".format(payload["object_kind"])) logger.warning("%s: unknown gitlab webhook object kind", payload["object_kind"]) if message: yield from self.send_data(conv_or_user_id, "\n".join(message))
37.790698
99
0.577538
2,871
0.883385
2,738
0.842462
2,761
0.849538
0
0
1,158
0.356308
bc6537e769f6b3ef7aa9a2e3afa098d8b075693f
1,220
py
Python
evsim/assessor.py
cbchoi/nppsim
4d096f9d2fdb5ebf3e3e83be7b1974bfc92554c1
[ "MIT" ]
3
2020-01-21T13:06:37.000Z
2021-03-01T23:35:20.000Z
evsim/assessor.py
cbchoi/pohangsim
e978ff39ec94413ae44129510c56acb134770298
[ "MIT" ]
null
null
null
evsim/assessor.py
cbchoi/pohangsim
e978ff39ec94413ae44129510c56acb134770298
[ "MIT" ]
null
null
null
from evsim.system_simulator import SystemSimulator from evsim.behavior_model_executor import BehaviorModelExecutor from evsim.system_message import SysMessage from evsim.definition import * import os import subprocess as sp class Assessor(BehaviorModelExecutor): def __init__(self, instance_time, destruct_time, name, engine_name): BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name) # Open CSV self.init_state("IDLE") self.insert_state("IDLE", Infinite) self.insert_state("MOVE", 1) self.insert_input_port("assess") self.insert_output_port("done") def ext_trans(self,port, msg): data = msg.retrieve() #print("Assessor") #print(str(datetime.datetime.now()) + " " + str(data[0])) #temp = "[%f] %s" % (SystemSimulator().get_engine(self.engine_name).get_global_time(), str(data[0])) #print(temp) def output(self): #temp = "[%f] %s" % (SystemSimulator().get_engine(self.engine_name).get_global_time(), "Human Receiver Object: Move") #print(temp) return None def int_trans(self): self._cur_state = "MOVE"
34.857143
126
0.657377
986
0.808197
0
0
0
0
0
0
372
0.304918
bc65af7557f0841ee2695968775683b6f5578bc6
19,786
py
Python
tei_entity_enricher/interface/postprocessing/gnd_connector.py
NEISSproject/TEIEntityEnricher
09a4a932b30886e50965959935dc803b36063e36
[ "Apache-2.0" ]
null
null
null
tei_entity_enricher/interface/postprocessing/gnd_connector.py
NEISSproject/TEIEntityEnricher
09a4a932b30886e50965959935dc803b36063e36
[ "Apache-2.0" ]
null
null
null
tei_entity_enricher/interface/postprocessing/gnd_connector.py
NEISSproject/TEIEntityEnricher
09a4a932b30886e50965959935dc803b36063e36
[ "Apache-2.0" ]
1
2021-04-27T13:55:29.000Z
2021-04-27T13:55:29.000Z
import os from typing import Union, List from tei_entity_enricher.interface.postprocessing.io import FileReader, FileWriter from tei_entity_enricher.util.helper import local_save_path, makedir_if_necessary from tei_entity_enricher.util.exceptions import FileNotFound class GndConnector: def __init__( self, gnd_id: Union[str, List[str], None] = None, apiindex: int = 0, check_connectivity: bool = True, show_printmessages: bool = True, ) -> None: """establishes connection to api, from which norm data for entities of Deutsche Nationalbibliothek´s database is retrieved, loaded data can be passed to an instance of Cache class for further processing or FileWriter class to save it gnd_id: gnd id number(s) apiindex: index of selected api in list defined in self.apilist check_connectivity: execute connectivity check in __init__() or not (see connectivitycheck_loop()) show_printmessages: show class internal printmessages on runtime or not apilist_filepath: path to apilist config file apilist: list of dicts as configuration data set, delivers a mapping to be able to normalize data from different apis, defines api`s url and aliases for filtering purposes (see get_gnd_data()) connection_established: data from an api has already been received or not remaining_apis_to_check: list of apiindex values, which have not been checked yet in connectivitycheck_loop()""" print("initializing GndConnector..") if show_printmessages else None self.show_printmessages: bool = show_printmessages self.gnd_id: Union[str, List[str], None] = gnd_id self.apiindex: int = apiindex self.apilist_filepath: str = os.path.join(local_save_path, "config", "postprocessing", "gnd_apilist.json") try: self.apilist: Union[dict, None] = FileReader( filepath=self.apilist_filepath, origin="local", internal_call=True, show_printmessages=False ).loadfile_json() except FileNotFound: print( "GndConnector: could not find gnd_apilist.json in config dir. creating file with default settings..." ) if self.show_printmessages else None self.apilist: List[dict] = [ { "name": "culturegraph", "baseUrl": "https://hub.culturegraph.org/entityfacts/{}", "baseAliases": { "type": [ "@type", "str", "categorial", { "person": "person", "organisation": "organisation", "place": "place", }, ], "name": ["preferredName", "str", "nominal"], "furtherNames": ["variantName", ["str"], "nominal"], "sameAs": ["sameAs", [{"@id": "str"}], "nominal"], "pseudonyms": [ "pseudonym", [{"preferredName": "str"}], "nominal", ], }, "personAliases": {}, "placeAliases": {}, "organizationAliases": {}, }, { "name": "lobid", "baseUrl": "http://lobid.org/gnd/{}", "baseAliases": { "type": [ "type", ["str"], "categorial", { "person": "Person", "organisation": "CorporateBody", "place": "PlaceOrGeographicName", }, ], "name": ["preferredName", "str", "nominal"], "furtherNames": ["variantName", ["str"], "nominal"], "sameAs": ["sameAs", [{"id": "str"}], "nominal"], "pseudonyms": [ "variantNameEntityForThePerson", [{"forename": ["str"], "surname": ["str"]}], "nominal", ], }, "personAliases": {}, "placeAliases": {}, "organizationAliases": {}, }, ] self.apiindex: int = 0 try: makedir_if_necessary(os.path.dirname(self.apilist_filepath)) FileWriter(data=self.apilist, filepath=self.apilist_filepath).writefile_json() except: print( f"GndConnector __init__(): could not create default gnd_apilist.json in config folder." ) if self.show_printmessages == True else None self.check_connectivity: bool = check_connectivity self.connection_established: bool = False self.remaining_apis_to_check: list = [i for i, _ in enumerate(self.apilist)] if self.check_connectivity == True: self.connectivitycheck_loop() else: print( "GndConnector: initialization has been done without connectivity check." ) if self.show_printmessages else None def connectivitycheck_single(self, index_to_test: int, gnd_id_to_test: str = "118540238") -> bool: """auxiliary method of connectivitycheck_loop(), checks a single api`s (from self.apilist) response status code and checks if response data type is json, preset gnd_id_to_test value refers to Goethe""" try: result: dict = FileReader( filepath=self.apilist[index_to_test]["baseUrl"].format(gnd_id_to_test), origin="web", internal_call=True, show_printmessages=self.show_printmessages, ).loadfile_json() except: return False if type(result) == dict: return True return False def connectivitycheck_loop(self) -> int: """recursive connectivity check, checking every single api in self.apilist (ascending) and setting self.apiindex to the value of those api, which is first to pass the check successfully. returns 0 or -1 for unittest purposes""" if self.check_connectivity == False: self.check_connectivity == True if len(self.remaining_apis_to_check) > 0: if self.connectivitycheck_single(self.remaining_apis_to_check[0]) == True: print( f"GndConnector: connectivity check passed, connection to {self.apilist[self.remaining_apis_to_check[0]]['name']} api established." ) if self.show_printmessages else None self.apiindex = self.remaining_apis_to_check[0] self.remaining_apis_to_check = [i for i, _ in enumerate(self.apilist)] self.connection_established = True return 0 else: print( f"GndConnector connectivity check: {self.apilist[self.remaining_apis_to_check[0]]['name']} api is currently not responding as expected. checking for alternatives..." ) if self.show_printmessages else None self.remaining_apis_to_check.remove(self.remaining_apis_to_check[0]) self.connectivitycheck_loop() else: print( "GndConnector connectivity check error: none of the listed apis is responding as expected." ) if self.show_printmessages else None return -1 def print_complete_url(self, index: int = 0) -> int: """print baseUrl string of the currently selected api defined in self.apilist, formatted with a gnd id number of self.gnd_id (list or str) selected by index value. returns 0 or -1 for unittest purposes""" if self.apiindex not in [i for i, _ in enumerate(self.apilist)]: print( "GndConnector print_complete_url() error: apiindex is not defined correctly. using default api..." ) if self.show_printmessages else None self.apiindex = 0 if self.gnd_id is not None: if type(self.gnd_id) == str: print( f"GndConnector complete URL: {self.apilist[self.apiindex]['baseUrl'].format(self.gnd_id)}" ) if self.show_printmessages else None elif type(self.gnd_id) == list: print( f"GndConnector complete URL of gnd id number {index + 1} in passed gnd id list: {self.apilist[self.apiindex]['baseUrl'].format(self.gnd_id[index])}" ) if self.show_printmessages else None return 0 else: print( "GndConnector print_complete_url() internal error: no gnd id number has been passed to connector object yet." ) if self.show_printmessages else None return -1 def return_complete_url(self, index: int = 0) -> Union[str, None]: """return baseUrl string of the currently selected api defined in self.apilist, formatted with a gnd id number of self.gnd_id (list or str) selected by index value""" if self.apiindex not in [i for i, _ in enumerate(self.apilist)]: print( "GndConnector return_complete_url() error: apiindex is not defined correctly. using default api..." ) if self.show_printmessages else None self.apiindex = 0 if self.gnd_id is not None: if type(self.gnd_id) == str: return self.apilist[self.apiindex]["baseUrl"].format(self.gnd_id) elif type(self.gnd_id) == list: return self.apilist[self.apiindex]["baseUrl"].format(self.gnd_id[index]) else: print( "GndConnector return_complete_url() internal error: no gnd id number has been passed to connector object yet." ) if self.show_printmessages else None return None def get_gnd_data(self, data_selection: Union[str, List[str], None] = None) -> Union[dict, None]: """method to receive data from api with the possibility to filter results, a dict is created, having gnd id numbers as keys and filtered or unfiltered response json data as values data_selection: if delivered, a normalized output is generated by renaming keys and re-sorting data from different keys from the raw data into new keys (purpose: json data delivered by different apis comes in different key-value-structures; normalization of this data is achieved with the help of key-value mapping information stored in self.apilist) can be "base" (all baseAliases data is provided: "type", "name", "furtherNames", "sameAs", "pseudonyms") can be a list of one or more baseAliases (i.e. ["type", "name"]) (not yet implemented: can be a "person", "place", "organization" or a custom string refering to a user-defined set of keys, for which the mapping is provided in self.apilist) """ if self.check_connectivity == False: print( f"GndConnector note: connections to apis have not been checked yet. to do so manually execute connectivitycheck_loop() method of the current connector object. continuing attempt to receive gnd data from {self.apilist[self.apiindex]['name']} api..." ) if self.show_printmessages else None elif self.connection_established == False: print( "GndConnector connectivity error: after connectivity check no connection could has been established to any of the available apis. gnd data queries can not be executed at the moment." ) if self.show_printmessages else None return None result = {} if type(self.gnd_id) == str: _temp_data = {} try: filereader = FileReader( filepath=self.return_complete_url(), origin="web", internal_call=True, show_printmessages=False ) _temp_data = filereader.loadfile_json() except: print( "GndConnector connectivity error in get_gnd_data() method: could not load resource from api as expected." ) if self.show_printmessages else None return None self.connection_established = True if _temp_data != None and _temp_data != False: result[self.gnd_id] = _temp_data print( f"GndConnector get_gnd_data() status: data for gnd id {self.gnd_id} received." ) if self.show_printmessages else None else: print( f"GndConnector get_gnd_data() status: for gnd id {self.gnd_id} no data could be delivered by api" ) if self.show_printmessages else None return None elif type(self.gnd_id) == list: for index, gnd in enumerate(self.gnd_id): _temp_data = {} try: filereader = FileReader( filepath=self.return_complete_url(index), origin="web", internal_call=True, show_printmessages=True, ) _temp_data = filereader.loadfile_json() except: print( f"GndConnector get_gnd_data() status: for gnd id {index + 1} ({gnd}) of {len(self.gnd_id)} no data could be delivered by api" ) if self.show_printmessages else None result[gnd] = _temp_data print( f"GndConnector get_gnd_data() status: gnd id {index + 1} ({gnd}) of {len(self.gnd_id)} processed" ) if self.show_printmessages else None self.connection_established = True # filtering: build new dict with selected values, which should be returned (base mode = all base aliases from apilist definition. list mode = select specific aliases from base set) # defining sub method for filtering def filter_received_data(gnd_id: str, mode: Union[str, List[str]]) -> dict: """sub method, which extracts the key-value pairs from the raw data received from api for one gnd id number and renames the keys and/or values. alias definitions in self.apilist are used for this filtering process: the keys of 'baseAliases' dict define the new key names, their value list denotates (in order of the list) 1. the original key name, 2. the original value type (python-wise: i.e. 'str' or '[str]'), 3. the original value type (logic-wise: 'categorial' or 'nominal'), 4. a categorization dict, if the original value type logic-wise is 'categorial': it delivers mapping information to assign a category (defined keys of this mapping dict) based on specific values (defined in the values of this mapping dict) found in raw data, example 1: using culturegraph api the value of the base category 'type' is assigned to 'person', if the raw data json object has a key '@type' with the value 'person' of type str, example 2: using lobid api the value of the base category 'type' is assigned to 'person', if the raw data json object has a key 'type' with a list as a value, which has itself a value 'Person' of type str in it, mode parameter accepts str 'base' (all base aliases will be extracted) or a list of str (specific aliases will be extracted)""" # todo: handle additional alias definition sets in gnd_apilist.json by user # category_sets = {'base': [list(self.apilist[self.apiindex]["baseAliases"].keys()), 'baseAliases'], # 'custom': [list(self.apilist[self.apiindex]["custom"].keys()), 'custom'] # } # selected_categories_list = category_sets.get(mode)[0] if type(mode) == str else mode # selected_categories_alias = category_sets.get(mode)[1] if type(mode) == str else 'baseAliases' # => allow parsing a list of categories to get_gnd_data() only if they are defined in baseAlias set? base_categories = list(self.apilist[self.apiindex]["baseAliases"].keys()) selected_categories = base_categories if mode == "base" else mode selected_categories_data = {} for category in selected_categories: _temp_data = [] try: _temp_data = result[gnd_id][self.apilist[self.apiindex]["baseAliases"][category][0]] except KeyError: _temp_data = [] print( f"GndConnector get_gnd_data() filtering note: could not find {category} information for {gnd_id} in raw data. continuing processing..." ) if self.show_printmessages else None # handling of categorical data types if ( len(_temp_data) > 0 and self.apilist[self.apiindex]["baseAliases"][category][2] == "categorial" and type(self.apilist[self.apiindex]["baseAliases"][category][3] == dict) ): _temp_category_data_form = self.apilist[self.apiindex]["baseAliases"][category][1] _temp_categorial_values = self.apilist[self.apiindex]["baseAliases"][category][3] # change found categorial string to selfdefined string (i.e. 'Person' to 'person') if type(_temp_category_data_form) == str: for _type in _temp_categorial_values: if _temp_data == _temp_categorial_values[_type]: _temp_data = _type # replace found categorial list with selfdefined string (i.e. ['Person', 'PoliticalLeader'] to 'person') elif type(_temp_category_data_form) == list: for _type in _temp_categorial_values: if _temp_categorial_values[_type] in _temp_data: _temp_data = _type selected_categories_data[category] = _temp_data return selected_categories_data # executing sub method for filtering if data_selection is not None: if type(self.gnd_id) == str: _new_dict = {list(result.keys())[0]: filter_received_data(self.gnd_id, data_selection)} elif type(self.gnd_id) == list: _new_dict = {} for key in result: _new_dict[key] = filter_received_data(key, data_selection) result = _new_dict return result
58.712166
347
0.564237
19,509
0.98595
0
0
0
0
0
0
8,813
0.445393
bc669999ddb0624f8b1b18f8677a007603269fec
122
py
Python
neslter/workflow/__init__.py
WHOIGit/nes-lter-ims
d4cc96c10da56ca33286af84d669625b67170522
[ "MIT" ]
3
2019-01-24T16:32:50.000Z
2021-11-05T02:18:12.000Z
neslter/workflow/__init__.py
WHOIGit/nes-lter-ims
d4cc96c10da56ca33286af84d669625b67170522
[ "MIT" ]
45
2019-05-23T15:15:32.000Z
2022-03-15T14:09:20.000Z
neslter/workflow/__init__.py
WHOIGit/nes-lter-ims
d4cc96c10da56ca33286af84d669625b67170522
[ "MIT" ]
null
null
null
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.level = logging.DEBUG
24.4
40
0.819672
0
0
0
0
0
0
0
0
0
0
bc66bbff24da2cc4aab8ede584053c2dba3e5cf5
440
py
Python
inference/_archive/render_section.py
emitch/SEAMLeSS
cae21c67316ed36529fdc2e470a105a9f847975c
[ "MIT" ]
4
2018-12-17T18:45:57.000Z
2021-04-29T16:30:42.000Z
inference/_archive/render_section.py
emitch/SEAMLeSS
cae21c67316ed36529fdc2e470a105a9f847975c
[ "MIT" ]
19
2019-01-02T19:09:12.000Z
2020-12-14T18:50:47.000Z
inference/_archive/render_section.py
emitch/SEAMLeSS
cae21c67316ed36529fdc2e470a105a9f847975c
[ "MIT" ]
2
2020-03-18T01:24:03.000Z
2022-01-06T06:19:58.000Z
from args import get_argparser, parse_args, get_aligner, get_bbox def render(aligner, bbox, z): aligner.total_bbox = bbox aligner.zs = z aligner.render_section_all_mips(z, bbox) if __name__ == '__main__': parser = get_argparser() args = parse_args(parser) a = get_aligner(args) bbox = get_bbox(args) for z in range(args.bbox_start[2], args.bbox_stop[2]): print('Rendering z={0}'.format(z)) render(a, bbox, z)
24.444444
66
0.697727
0
0
0
0
0
0
0
0
27
0.061364
bc6934a711c5b2c64314e9faedf3a6f0838f298a
52,806
py
Python
venv/lib/python3.9/site-packages/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3
630dcef73e6a258b6e9a52f934e2dd912ce741f8
[ "Apache-2.0" ]
null
null
null
venv/lib/python3.9/site-packages/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3
630dcef73e6a258b6e9a52f934e2dd912ce741f8
[ "Apache-2.0" ]
null
null
null
venv/lib/python3.9/site-packages/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3
630dcef73e6a258b6e9a52f934e2dd912ce741f8
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Accesses the google.spanner.admin.instance.v1 InstanceAdmin API.""" import functools import pkg_resources import warnings from google.oauth2 import service_account import google.api_core.client_options import google.api_core.gapic_v1.client_info import google.api_core.gapic_v1.config import google.api_core.gapic_v1.method import google.api_core.gapic_v1.routing_header import google.api_core.grpc_helpers import google.api_core.operation import google.api_core.operations_v1 import google.api_core.page_iterator import google.api_core.path_template import grpc from google.cloud.spanner_admin_instance_v1.gapic import enums from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client_config from google.cloud.spanner_admin_instance_v1.gapic.transports import ( instance_admin_grpc_transport, ) from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2_grpc from google.iam.v1 import iam_policy_pb2 from google.iam.v1 import options_pb2 from google.iam.v1 import policy_pb2 from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 _GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-spanner").version class InstanceAdminClient(object): """ Cloud Spanner Instance Admin API The Cloud Spanner Instance Admin API can be used to create, delete, modify and list instances. Instances are dedicated Cloud Spanner serving and storage resources to be used by Cloud Spanner databases. Each instance has a "configuration", which dictates where the serving resources for the Cloud Spanner instance are located (e.g., US-central, Europe). Configurations are created by Google based on resource availability. Cloud Spanner billing is based on the instances that exist and their sizes. After an instance exists, there are no additional per-database or per-operation charges for use of the instance (though there may be additional network bandwidth charges). Instances offer isolation: problems with databases in one instance will not affect other instances. However, within an instance databases can affect each other. For example, if one database in an instance receives a lot of requests and consumes most of the instance resources, fewer resources are available for other databases in that instance, and their performance may suffer. """ SERVICE_ADDRESS = "spanner.googleapis.com:443" """The default address of the service.""" # The name of the interface for this client. This is the key used to # find the method configuration in the client_config dictionary. _INTERFACE_NAME = "google.spanner.admin.instance.v1.InstanceAdmin" @classmethod def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: InstanceAdminClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @classmethod def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, ) @classmethod def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, ) @classmethod def project_path(cls, project): """Return a fully-qualified project string.""" return google.api_core.path_template.expand( "projects/{project}", project=project ) def __init__( self, transport=None, channel=None, credentials=None, client_config=None, client_info=None, client_options=None, ): """Constructor. Args: transport (Union[~.InstanceAdminGrpcTransport, Callable[[~.Credentials, type], ~.InstanceAdminGrpcTransport]): A transport instance, responsible for actually making the API calls. The default transport uses the gRPC protocol. This argument may also be a callable which returns a transport instance. Callables will be sent the credentials as the first argument and the default transport class as the second argument. channel (grpc.Channel): DEPRECATED. A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. This argument is mutually exclusive with providing a transport instance to ``transport``; doing so will raise an exception. client_config (dict): DEPRECATED. A dictionary of call options for each method. If not specified, the default configuration is used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. client_options (Union[dict, google.api_core.client_options.ClientOptions]): Client options used to set user options on the client. API Endpoint should be set through client_options. """ # Raise deprecation warnings for things we want to go away. if client_config is not None: warnings.warn( "The `client_config` argument is deprecated.", PendingDeprecationWarning, stacklevel=2, ) else: client_config = instance_admin_client_config.config if channel: warnings.warn( "The `channel` argument is deprecated; use " "`transport` instead.", PendingDeprecationWarning, stacklevel=2, ) api_endpoint = self.SERVICE_ADDRESS if client_options: if type(client_options) == dict: client_options = google.api_core.client_options.from_dict( client_options ) if client_options.api_endpoint: api_endpoint = client_options.api_endpoint # Instantiate the transport. # The transport is responsible for handling serialization and # deserialization and actually sending data to the service. if transport: if callable(transport): self.transport = transport( credentials=credentials, default_class=instance_admin_grpc_transport.InstanceAdminGrpcTransport, address=api_endpoint, ) else: if credentials: raise ValueError( "Received both a transport instance and " "credentials; these are mutually exclusive." ) self.transport = transport else: self.transport = instance_admin_grpc_transport.InstanceAdminGrpcTransport( address=api_endpoint, channel=channel, credentials=credentials ) if client_info is None: client_info = google.api_core.gapic_v1.client_info.ClientInfo( gapic_version=_GAPIC_LIBRARY_VERSION ) else: client_info.gapic_version = _GAPIC_LIBRARY_VERSION self._client_info = client_info # Parse out the default settings for retry and timeout for each RPC # from the client configuration. # (Ordinarily, these are the defaults specified in the `*_config.py` # file next to this one.) self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( client_config["interfaces"][self._INTERFACE_NAME] ) # Save a dictionary of cached API call functions. # These are the actual callables which invoke the proper # transport methods, wrapped with `wrap_method` to add retry, # timeout, and the like. self._inner_api_calls = {} # Service calls def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 2 and 64 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, ) def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in ``field_mask`` need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in ``Instance`` should be updated. The field mask must always be specified; this prevents any future fields in ``Instance`` from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, ) def list_instance_configs( self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists the supported instance configurations for a given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instance_configs(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instance_configs(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of supported instance configurations is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instance_configs" not in self._inner_api_calls: self._inner_api_calls[ "list_instance_configs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instance_configs, default_retry=self._method_configs["ListInstanceConfigs"].retry, default_timeout=self._method_configs["ListInstanceConfigs"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstanceConfigsRequest( parent=parent, page_size=page_size ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instance_configs"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instance_configs", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance_config( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance configuration. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') >>> >>> response = client.get_instance_config(name) Args: name (str): Required. The name of the requested instance configuration. Values are of the form ``projects/<project>/instanceConfigs/<config>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance_config" not in self._inner_api_calls: self._inner_api_calls[ "get_instance_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance_config, default_retry=self._method_configs["GetInstanceConfig"].retry, default_timeout=self._method_configs["GetInstanceConfig"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceConfigRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) def list_instances( self, parent, page_size=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all instances in the given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instances(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instances(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. filter_ (str): An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: - ``name`` - ``display_name`` - ``labels.key`` where key is the name of a label Some examples of using filters are: - ``name:*`` --> The instance has a name. - ``name:Howl`` --> The instance's name contains the string "howl". - ``name:HOWL`` --> Equivalent to above. - ``NAME:howl`` --> Equivalent to above. - ``labels.env:*`` --> The instance has the label "env". - ``labels.env:dev`` --> The instance has the label "env" and the value of the label contains the string "dev". - ``name:howl labels.env:dev`` --> The instance's name contains "howl" and it has the label "env" with its value containing "dev". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstancesRequest( parent=parent, page_size=page_size, filter=filter_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instances"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instances", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance( self, name, field_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> response = client.get_instance(name) Args: name (str): Required. The name of the requested instance. Values are of the form ``projects/<project>/instances/<instance>``. field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): If field_mask is present, specifies the subset of ``Instance`` fields that should be returned. If absent, all ``Instance`` fields are returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance" not in self._inner_api_calls: self._inner_api_calls[ "get_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance, default_retry=self._method_configs["GetInstance"].retry, default_timeout=self._method_configs["GetInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceRequest( name=name, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def delete_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes an instance. Immediately upon completion of the request: - Billing ceases for all of the instance's reserved resources. Soon afterward: - The instance and *all of its databases* immediately and irrevocably disappear from the API. All data in the databases is permanently deleted. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> client.delete_instance(name) Args: name (str): Required. The name of the instance to be deleted. Values are of the form ``projects/<project>/instances/<instance>`` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_instance" not in self._inner_api_calls: self._inner_api_calls[ "delete_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_instance, default_retry=self._method_configs["DeleteInstance"].retry, default_timeout=self._method_configs["DeleteInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.DeleteInstanceRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def set_iam_policy( self, resource, policy, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sets the access control policy on an instance resource. Replaces any existing policy. Authorization requires ``spanner.instances.setIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `policy`: >>> policy = {} >>> >>> response = client.set_iam_policy(resource, policy) Args: resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. policy (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "set_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_iam_policy, default_retry=self._method_configs["SetIamPolicy"].retry, default_timeout=self._method_configs["SetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def get_iam_policy( self, resource, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. Authorization requires ``spanner.instances.getIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> response = client.get_iam_policy(resource) Args: resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. options_ (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_iam_policy, default_retry=self._method_configs["GetIamPolicy"].retry, default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.GetIamPolicyRequest( resource=resource, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def test_iam_permissions( self, resource, permissions, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns permissions that the caller has on the specified instance resource. Attempting this RPC on a non-existent Cloud Spanner instance resource will result in a NOT_FOUND error if the user has ``spanner.instances.list`` permission on the containing Google Cloud Project. Otherwise returns an empty set of permissions. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] >>> >>> response = client.test_iam_permissions(resource, permissions) Args: resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`__. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.TestIamPermissionsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "test_iam_permissions" not in self._inner_api_calls: self._inner_api_calls[ "test_iam_permissions" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.test_iam_permissions, default_retry=self._method_configs["TestIamPermissions"].retry, default_timeout=self._method_configs["TestIamPermissions"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["test_iam_permissions"]( request, retry=retry, timeout=timeout, metadata=metadata )
43.142157
165
0.613926
50,870
0.963337
0
0
1,523
0.028841
0
0
34,636
0.65591
bc69b9f3ab057490f4ec7854149028c2c310ae9c
31,196
py
Python
src/ScaleHD/__backend.py
helloabunai/ScaleHD
b48c1a1ed742bdbda0a4cd42555d1e12d2e3024d
[ "MIT" ]
3
2017-07-03T19:45:13.000Z
2020-05-12T16:56:19.000Z
src/ScaleHD/__backend.py
helloabunai/ScaleHD
b48c1a1ed742bdbda0a4cd42555d1e12d2e3024d
[ "MIT" ]
1
2019-06-21T14:49:50.000Z
2019-06-24T08:24:37.000Z
src/ScaleHD/__backend.py
helloabunai/ScaleHD
b48c1a1ed742bdbda0a4cd42555d1e12d2e3024d
[ "MIT" ]
2
2017-06-05T21:56:36.000Z
2021-03-22T20:34:13.000Z
#/usr/bin/python __version__ = '1.0' __author__ = '[email protected]' ## ## Imports import string import os import errno import shutil import sys import glob import datetime import subprocess import logging as log import numpy as np import csv from io import StringIO import PyPDF2 from sklearn import preprocessing from collections import defaultdict from xml.etree import cElementTree from lxml import etree from reportlab.pdfgen import canvas class Colour: def __init__(self): pass purple = '\033[95m' cyan = '\033[96m' darkcyan = '\033[36m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' bold = '\033[1m' underline = '\033[4m' end = '\033[0m' class ConfigReader(object): """ The configuration file reader. Opens a configuration file, and if valid, converts the parameters within the file to a dictionary object, reader to be viewed through accessing the config_dict variable. """ def __init__(self, scriptdir, config_filename=None): ## ## Instance variables self.scriptdir = scriptdir self.config_filename = config_filename self.dtd_filename = scriptdir + "/config/config.dtd" ## ## Check for configuration file (just incase) if self.config_filename is None: log.error("No configuration file specified!") else: self.config_file = etree.parse(self.config_filename) ## ## Check config vs dtd, parse info to dictionary, validate vs ruleset self.validate_against_dtd() self.set_dictionary() self.validate_config() def validate_against_dtd(self): """ Validate input config against DTD ruleset i.e. confirms conformation of XML structure """ ## ## Open > etree.DTD object dtd_file = open(self.dtd_filename, 'r') dtd_object = etree.DTD(dtd_file) ## ## If validation fails, close the object (memory) and raise an error if not dtd_object.validate(self.config_file): dtd_file.close() log.error("DTD validation failure {0}: {1}".format(self.config_filename, dtd_object.error_log.filter_from_errors()[0])) sys.exit(2) dtd_file.close() def set_dictionary(self): """ Takes the now validated XML and extracts information from the tree into a python dictionary {key: value}. This dictionary will be used for variables within the pipeline. Recursion adapted from http://stackoverflow.com/a/9286702 """ def recursive_generation(t): d = {t.tag: {} if t.attrib else None} children = list(t) ## ## If list was populated, create dictionary, Append keys if children: dd = defaultdict(list) for dc in map(recursive_generation, children): for k, v in dc.items(): dd[k].append(v) d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} ## ## Values for key if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.items()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d ## ## Takes the formatted xml doc, puts through generator, returns dictionary string_repr = etree.tostring(self.config_file, pretty_print=True) element_tree = cElementTree.XML(string_repr) self.config_dict = recursive_generation(element_tree) self.config_dict = self.config_dict[list(self.config_dict.keys())[0]] def validate_config(self): """ Method which validates the configuration file's contents. If all pass, guarantees that the settings dictionary is full of valid settings! """ trigger = False ## ## Main configuration instance settings data_directory = self.config_dict['@data_dir'] if not os.path.exists(data_directory): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified data directory could not be found.')) trigger = True for fqfile in glob.glob(os.path.join(data_directory, '*')): if not (fqfile.endswith('.fq') or fqfile.endswith('.fastq') or fqfile.endswith('.fq.gz') or fqfile.endswith('.fastq.gz')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Non FastQ/GZ data detected in specified input directory.')) trigger = True forward_reference = self.config_dict['@forward_reference'] if not os.path.isfile(forward_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file could not be found.')) trigger = True if not (forward_reference.endswith('.fa') or forward_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file is not a fa/fas file.')) trigger = True reverse_reference = self.config_dict['@reverse_reference'] if not os.path.isfile(reverse_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file could not be found.')) trigger = True if not (reverse_reference.endswith('fa') or reverse_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file is not a fa/fas file.')) trigger = True if forward_reference.split('/')[-1] == reverse_reference.split('/')[-1]: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: FW and RV references have identical filenames. Will create indexing issue.')) trigger = True ## ## Instance flag settings demultiplexing_flag = self.config_dict['instance_flags']['@demultiplex'] if not (demultiplexing_flag == 'True' or demultiplexing_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Demultiplexing flag is not set to True/False.')) trigger = True sequence_qc_flag = self.config_dict['instance_flags']['@quality_control'] if not (sequence_qc_flag == 'True' or sequence_qc_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Quality control flag is not set to True/False.')) trigger = True alignment_flag = self.config_dict['instance_flags']['@sequence_alignment'] if not (alignment_flag == 'True' or alignment_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Alignment flag is not set to True/False.')) trigger = True atypical_flag = self.config_dict['instance_flags']['@atypical_realignment'] if not (atypical_flag == 'True' or atypical_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Atypical Realignment flag is not True/False.')) trigger = True genotype_flag = self.config_dict['instance_flags']['@genotype_prediction'] if not (genotype_flag == 'True' or genotype_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Genotype Prediction control flag is not True/False.')) trigger = True snpcall_flag = self.config_dict['instance_flags']['@snp_calling'] if not (snpcall_flag == 'True' or snpcall_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Calling flag is not True/False.')) trigger = True ## ## Demultiplexing flag settings trim_adapter_base = ['A', 'G', 'C', 'T'] if demultiplexing_flag == 'True': forward_adapter = self.config_dict['demultiplex_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in forward_adapter demultiplexing flag.')) trigger = True forward_position = self.config_dict['demultiplex_flags']['@forward_position'] if forward_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing forward adapter position invalid! [5P, 3P, AP]')) trigger = True reverse_adapter = self.config_dict['demultiplex_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in reverse_adapter demultiplexing flag.')) trigger = True reverse_position = self.config_dict['demultiplex_flags']['@reverse_position'] if reverse_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing reverse adapter position invalid! [5P, 3P, AP]')) trigger = True error_rate = self.config_dict['demultiplex_flags']['@error_rate'] if not error_rate.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error_rate is not a valid integer.')) trigger = True minimum_overlap = self.config_dict['demultiplex_flags']['@min_overlap'] if not minimum_overlap.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_overlap is not a valid integer.')) trigger = True minimum_length = self.config_dict['demultiplex_flags']['@min_length'] if not minimum_length == '': if not minimum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_length is not a valid integer.')) trigger = True maximum_length = self.config_dict['demultiplex_flags']['@max_length'] if not maximum_length == '': if not maximum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified max_length is not a valid integer.')) trigger = True ## ## Trimming flag settings if sequence_qc_flag == 'True': trimming_type = self.config_dict['trim_flags']['@trim_type'] if not (trimming_type == 'Quality' or trimming_type == 'Adapter' or trimming_type == 'Both'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Trimming type is not Quality/Adapter/Both.')) trigger = True quality_threshold = self.config_dict['trim_flags']['@quality_threshold'] if not quality_threshold.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer is invalid.')) trigger = True elif not int(quality_threshold) in range(0,39): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer out of range (0-38).')) trigger = True trim_adapters = ['-a','-g','-a$','-g^','-b'] adapter_flag = self.config_dict['trim_flags']['@adapter_flag'] if not (adapter_flag in trim_adapters): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified trimming adapter not valid selection.')) trigger = True forward_adapter = self.config_dict['trim_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in FW adapter sequence.')) trigger = True reverse_adapter = self.config_dict['trim_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in RV adapter sequence.')) trigger = True error_tolerance = self.config_dict['trim_flags']['@error_tolerance'] if not isinstance(float(error_tolerance), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not a valid float.')) trigger = True if not float(error_tolerance) in np.arange(0,1.1,0.01): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not 0.0 < x < 1.0.')) trigger = True ## ## Alignment flag settings if alignment_flag == 'True': min_seed_length = self.config_dict['alignment_flags']['@min_seed_length'] if not min_seed_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_seed_length integer is invalid.')) trigger=True band_width = self.config_dict['alignment_flags']['@band_width'] if not band_width.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified band_width integer is invalid.')) trigger=True seed_length_extension = self.config_dict['alignment_flags']['@seed_length_extension'] if not isinstance(float(seed_length_extension), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seed_length_extension float is invalid.')) trigger=True skip_seed_with_occurrence = self.config_dict['alignment_flags']['@skip_seed_with_occurrence'] if not skip_seed_with_occurrence.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified skip_seed_with_occurrence integer is invalid.')) trigger=True chain_drop = self.config_dict['alignment_flags']['@chain_drop'] if not isinstance(float(chain_drop), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified chain_drop float is invalid.')) trigger=True seeded_chain_drop = self.config_dict['alignment_flags']['@seeded_chain_drop'] if not seeded_chain_drop.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seeded_chain_drop integer is invalid.')) trigger=True seq_match_score = self.config_dict['alignment_flags']['@seq_match_score'] if not seq_match_score.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seq_match_score integer is invalid.')) trigger=True mismatch_penalty = self.config_dict['alignment_flags']['@mismatch_penalty'] if not mismatch_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified mismatch_penalty integer is invalid.')) trigger=True indel_penalty_raw = self.config_dict['alignment_flags']['@indel_penalty'] indel_penalty = indel_penalty_raw.split(',') for individual_indelpen in indel_penalty: if not individual_indelpen.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified indel_penalty integer(s) is(are) invalid.')) trigger=True gap_extend_penalty_raw = self.config_dict['alignment_flags']['@gap_extend_penalty'] gap_extend_penalty = gap_extend_penalty_raw.split(',') for individual_gaextend in gap_extend_penalty: if not individual_gaextend.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified gap_extend_penalty integer(s) is(are) invalid.')) trigger=True prime_clipping_penalty_raw = self.config_dict['alignment_flags']['@prime_clipping_penalty'] prime_clipping_penalty = prime_clipping_penalty_raw.split(',') for individual_prclip in prime_clipping_penalty: if not individual_prclip.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified prime_clipping_penalty integer(s) is(are) invalid.')) trigger=True unpaired_pairing_penalty = self.config_dict['alignment_flags']['@unpaired_pairing_penalty'] if not unpaired_pairing_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified unpaired_pairing_penalty integer is invalid.')) trigger=True ## ## Genotype prediction flag settings if genotype_flag == 'True': snp_observation_pcnt = self.config_dict['prediction_flags']['@snp_observation_threshold'] if not snp_observation_pcnt.isdigit(): if not int(snp_observation_pcnt) in range(1,5): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Observation value invalid! Please use 1-10.')) trigger = True quality_cutoff = self.config_dict['prediction_flags']['@quality_cutoff'] if not quality_cutoff.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Quality Cutoff value is not an integer.')) trigger = True if trigger: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Failure, exiting.')) sys.exit(2) else: log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'XML Config: Parsing parameters successful!')) class DataClump(dict): """Container object for datasets: dictionary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): dict.__init__(self, kwargs) self.__dict__ = self class DataLoader: def __init__(self, database, descriptor): self.database = database self.descriptor = descriptor def load_model(self): ## Loads description file for respective data set modeldescr_name = self.descriptor with open(modeldescr_name) as f: descr_text = f.read() ## Loads data set from csv, into objects in preparation for bunch() data_file_name = self.database with open(data_file_name) as f: data_file = csv.reader(f) temp = next(data_file) n_samples = int(temp[0]) n_features = int(temp[1]) data = np.empty((n_samples, n_features)) temp = next(data_file) feature_names = np.array(temp) labels = [] for i, d in enumerate(data_file): data[i] = d[:-1] label = d[-1] labels.append(label) le = preprocessing.LabelEncoder() le.fit(labels) hash_int_labels = le.transform(labels) return DataClump(DATA=data, TARGET=hash_int_labels, FTRNAME=feature_names[:-1], DESCR=descr_text, ENCDR=le) def parse_boolean(boolean_value): """ Given a string (boolean_value), returns a boolean value representing the string contents. For example, a string with 'true', 't', 'y' or 'yes' will yield True. """ boolean_value = string.lower(boolean_value) in ('yes', 'y', 'true', 't', '1') return boolean_value def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the string is empty, True is returned. """ if string != '': return False if raise_exception: raise ValueError("Empty string detected!") return True def sanitise_inputs(parsed_arguments): """ Utilises filesystem_exists_check and check_input_files if either return false, path is invalid or unsupported files present so, quit """ trigger = False ## ## Jobname prefix validity check if parsed_arguments.jobname: for character in parsed_arguments.jobname: if character is ' ' or character is '/': log.error('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified Job Name has invalid characters: "', character, '"')) trigger = True ## ## Config mode check if parsed_arguments.config: if not filesystem_exists_check(parsed_arguments.config[0]): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file could not be found.')) trigger = True for xmlfile in parsed_arguments.config: if not check_input_files('.xml',xmlfile): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file is not an XML file.')) trigger = True return trigger def extract_data(input_data_directory): target_files = glob.glob(os.path.join(input_data_directory, '*')) for extract_target in target_files: if extract_target.lower().endswith(('.fq.gz', '.fastq.gz')): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Detected compressed input data. Extracting!')) break for extract_target in target_files: unzipd = subprocess.Popen(['gzip', '-q', '-f', '-d', extract_target], stderr=subprocess.PIPE) unzipd.wait() return True def sequence_pairings(data_path, instance_rundir): ## ## Get input files from data path ## Sort so that ordering isn't screwy on linux input_files = glob.glob(os.path.join(data_path, '*')) sorted_input = sorted(input_files) sequence_pairs = [] file_count = len(sorted_input) if not file_count % 2 == 0: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'I/O: Non-even number of input files specified. Cannot continue without pairing!')) sys.exit(2) ## ## Optimise so code isn't recycled for i in range(0, len(sorted_input), 2): file_pair = {} forward_data = sorted_input[i] reverse_data = sorted_input[i+1] ## ## Check forward ends with R1 forward_data_name = sorted_input[i].split('/')[-1].split('.')[0] if not forward_data_name.endswith('_R1'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Forward input file does not end in _R1. ', forward_data)) sys.exit(2) ## ## Check reverse ends with R2 reverse_data_name = sorted_input[i+1].split('/')[-1].split('.')[0] if not reverse_data_name.endswith('_R2'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Reverse input file does not end in _R2. ', reverse_data)) sys.exit(2) ## ## Make Stage outputs for use in everywhere else in pipeline sample_root = '_'.join(forward_data_name.split('_')[:-1]) instance_path = os.path.join(instance_rundir) seq_qc_path = os.path.join(instance_rundir, sample_root, 'SeqQC') align_path = os.path.join(instance_rundir, sample_root, 'Align') predict_path = os.path.join(instance_rundir, sample_root, 'Predict') file_pair[sample_root] = [forward_data, reverse_data, instance_path, seq_qc_path, align_path, predict_path] sequence_pairs.append(file_pair) return sequence_pairs def filesystem_exists_check(path, raise_exception=True): """ Checks to see if the path, specified by parameter path, exists. Can be either a directory or file. If the path exists, True is returned. If the path does not exist, and raise_exception is set to True, an IOError is raised - else False is returned. """ if os.path.lexists(path): return True if raise_exception: log.error('{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified input path could not be found.')) return False def check_input_files(input_format, input_file): if input_file.endswith(input_format): return True return False def initialise_libraries(instance_params): trigger = False ## ## Subfunction for recycling code ## Calls UNIX type for checking binaries present ## Changed from WHICH as apparently type functions over different shells/config files def type_func(binary): binary_result = [] binary_string = 'type {}'.format(binary) binary_subprocess = subprocess.Popen([binary_string], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) binary_result = binary_subprocess.communicate() binary_subprocess.wait() if 'not found'.encode() in binary_result[0] or binary_result[1]: log.critical('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Missing binary: ', binary, '!')) raise NameError ## ## To determine which binaries to check for ## AttributeError in the situation where instance_params origin differs ## try for -c style, except AttributeError for -b style try: quality_control = instance_params.config_dict['instance_flags']['@quality_control'] alignment = instance_params.config_dict['instance_flags']['@sequence_alignment'] genotyping = instance_params.config_dict['instance_flags']['@genotype_prediction'] snp_calling = instance_params.config_dict['instance_flags']['@snp_calling'] except AttributeError: quality_control = instance_params['quality_control'] alignment = instance_params['sequence_alignment'] genotyping = instance_params['genotype_prediction'] snp_calling = instance_params['snp_calling'] if quality_control == 'True': try:type_func('java') except NameError: trigger=True try:type_func('fastqc') except NameError: trigger=True try:type_func('cutadapt') except NameError: trigger=True if alignment == 'True': try:type_func('seqtk') except NameError: trigger=True try:type_func('bwa') except NameError: trigger=True try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if genotyping == 'True': try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if snp_calling == 'True': try: type_func('picard') except NameError: trigger=True try: type_func('freebayes') except NameError: trigger=True return trigger def sanitise_outputs(jobname, output_argument): run_dir = '' output_root = output_argument[0] if jobname: target_output = os.path.join(output_root, jobname) if not os.path.exists(target_output): log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating Output with prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) mkdir_p(run_dir) else: purge_choice = '' while True: purge_choice = input('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Job folder already exists. Delete existing folder? Y/N: ')) if not (purge_choice.lower() == 'y') and not (purge_choice.lower() == 'n'): log.info('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Invalid input. Please input Y or N.')) continue else: break if purge_choice.lower() == 'y': log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Clearing pre-existing Jobname Prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) if os.path.exists(run_dir): shutil.rmtree(run_dir, ignore_errors=True) mkdir_p(run_dir) else: raise Exception('User chose not to delete pre-existing Job folder. Cannot write output.') else: ## Ensures root output is a real directory ## Generates folder name based on date (for run ident) date = datetime.date.today().strftime('%d-%m-%Y') walltime = datetime.datetime.now().strftime('%H%M%S') today = date + '-' + walltime ## If the user specified root doesn't exist, make it ## Then make the run directory for datetime if not os.path.exists(output_root): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating output root... ')) mkdir_p(output_root) run_dir = os.path.join(output_root, 'ScaleHDRun_'+today) log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating instance run directory.. ')) mkdir_p(run_dir) ## Inform user it's all gonna be okaaaayyyy log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'Output directories OK!')) return run_dir def replace_fqfile(mutate_list, target_fqfile, altered_path): if target_fqfile in mutate_list: loc = mutate_list.index(target_fqfile) mutate_list[loc] = altered_path return mutate_list def scrape_summary_data(stage, input_report_file): ## ## If the argument input_report_file is from trimming.. if stage == 'trim': with open(input_report_file, 'r') as trpf: trim_lines = trpf.readlines() ## ## Determine buffer size to slice from above array scraping_buffer = 8 if '-q' in trim_lines[1]: scraping_buffer += 1 ## ## Get Anchor summary_start = 0 for i in range(0, len(trim_lines)): if '== Summary ==' in trim_lines[i]: summary_start = i ## ## Slice and close summary_data = trim_lines[summary_start:summary_start + scraping_buffer] trpf.close() return summary_data[2:] ## ## If the argument input_report_file is from alignment.. if stage == 'align': with open(input_report_file, 'r') as alnrpf: align_lines = alnrpf.readlines() alnrpf.close() ## ## No ranges required, only skip first line return align_lines[1:] ## ## No need to tidy up report for genotyping ## since we already have the data from our own objects if stage == 'gtype': pass def generate_atypical_xml(label, allele_object, index_path, direction): """ :param allele_object: :param index_path: :return: """ ##TODO docstring atypical_path = os.path.join(index_path, '{}{}_{}.xml'.format(direction, label, allele_object.get_reflabel())) fp_flank = 'GCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTC' cagstart = ''; cagend = '' intv = allele_object.get_intervening() ccgstart = ''; ccgend = '' ccglen = allele_object.get_ccg() cctlen = allele_object.get_cct() tp_flank = 'CAGCTTCCTCAGCCGCCGCCGCAGGCACAGCCGCTGCT' if direction == 'fw': cagstart = '1'; cagend = '200' ccgstart = '1'; ccgend = '20' if direction == 'rv': cagstart = '100'; cagend = '100' ccgstart = '1'; ccgend = '20' ## ## Create XML data_root = etree.Element('data') loci_root = etree.Element('loci', label=allele_object.get_reflabel()); data_root.append(loci_root) ## ## Loci Nodes fp_input = etree.Element('input', type='fiveprime', flank=fp_flank) cag_region = etree.Element('input', type='repeat_region', order='1', unit='CAG', start=cagstart, end=cagend) intervening = etree.Element('input', type='intervening', sequence=intv, prior='1') ccg_region = etree.Element('input', type='repeat_region', order='2', unit='CCG', start=ccgstart, end=ccgend) cct_region = etree.Element('input', type='repeat_region', order='3', unit='CCT', start=str(cctlen), end=str(cctlen)) tp_input = etree.Element('input', type='threeprime', flank=tp_flank) for node in [fp_input, cag_region, intervening, ccg_region, cct_region, tp_input]: loci_root.append(node) s = etree.tostring(data_root, pretty_print=True) with open(atypical_path, 'w') as xmlfi: xmlfi.write(s.decode()) xmlfi.close() return atypical_path def generate_reference(input_xml, index_path, ref_indexes, direction): ##TODO docstring label = input_xml.split('/')[-1].split('.')[0] target_output = os.path.join(index_path, label + '.fa') temp_output = os.path.join(index_path, label + '_concat.fa') gen_process = subprocess.Popen(['generatr', '-i', input_xml, '-o', target_output], stdout=subprocess.PIPE, stderr=subprocess.PIPE) gen_process.wait() ## ## Join typical and atypical reference into one file if direction == 'fw': toutfi = open(temp_output, 'w') cat_process = subprocess.Popen(['cat', target_output, ref_indexes[0]], stdout=toutfi, stderr=subprocess.PIPE) cat_process.wait() toutfi.close() target_output = temp_output return target_output def seek_target(input_list, target): for i in range(0, len(input_list)): if target in input_list[i]: return i def sanitise_trimming_output(input_object, input_list): if type(input_object) is int: cleanse_target = input_list[input_object].split(':')[1].lstrip().rstrip() return cleanse_target else: return '*' def sanitise_alignment_output(input_object, input_list, stage): if type(input_object) is int: if stage == 3: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:1] return ''.join(cleanse_target) else: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:2] return ' '.join(cleanse_target) else: return '*' def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
38.277301
155
0.702526
17,233
0.552411
0
0
0
0
0
0
11,225
0.359822
bc6acbe604cb779e768957863e598871559e6e15
3,966
py
Python
tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encoder.py
Jian137/mmediting-1
e1ac6c93441ec96696d0b530f040b91b809015b6
[ "Apache-2.0" ]
1,884
2020-07-09T18:53:43.000Z
2022-03-31T12:06:18.000Z
tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encoder.py
Jian137/mmediting-1
e1ac6c93441ec96696d0b530f040b91b809015b6
[ "Apache-2.0" ]
622
2020-07-09T18:52:27.000Z
2022-03-31T14:41:09.000Z
tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encoder.py
Jian137/mmediting-1
e1ac6c93441ec96696d0b530f040b91b809015b6
[ "Apache-2.0" ]
361
2020-07-09T19:21:47.000Z
2022-03-31T09:58:27.000Z
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmedit.models.backbones import ContextualAttentionNeck, DeepFillEncoder from mmedit.models.common import SimpleGatedConvModule def test_deepfill_enc(): encoder = DeepFillEncoder() x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.stride == (2, 2) assert encoder.enc2.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_conv') x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_attention') x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 128 if torch.cuda.is_available(): encoder = DeepFillEncoder().cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.stride == (2, 2) assert encoder.enc2.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_conv').cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 64 encoder = DeepFillEncoder(encoder_type='stage2_attention').cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 128, 64, 64) assert encoder.enc2.out_channels == 32 assert encoder.enc3.out_channels == 64 assert encoder.enc4.out_channels == 128 encoder = DeepFillEncoder( conv_type='gated_conv', channel_factor=0.75).cuda() x = torch.randn((2, 5, 256, 256)).cuda() outputs = encoder(x) assert isinstance(outputs, dict) assert 'out' in outputs res = outputs['out'] assert res.shape == (2, 96, 64, 64) assert isinstance(encoder.enc2, SimpleGatedConvModule) assert encoder.enc2.conv.stride == (2, 2) assert encoder.enc2.conv.out_channels == 48 * 2 def test_deepfill_contextual_attention_neck(): # TODO: add unittest for contextual attention module neck = ContextualAttentionNeck(in_channels=128) x = torch.rand((2, 128, 64, 64)) mask = torch.zeros((2, 1, 64, 64)) mask[..., 20:100, 23:90] = 1. res, offset = neck(x, mask) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) if torch.cuda.is_available(): neck.cuda() res, offset = neck(x.cuda(), mask.cuda()) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) neck = ContextualAttentionNeck( in_channels=128, conv_type='gated_conv').cuda() res, offset = neck(x.cuda(), mask.cuda()) assert res.shape == (2, 128, 64, 64) assert offset.shape == (2, 32, 32, 32, 32) assert isinstance(neck.conv1, SimpleGatedConvModule)
35.72973
76
0.620524
0
0
0
0
0
0
0
0
255
0.064297
bc6c634a8700c04a493d0272caa915d4e9038c51
580
py
Python
mvp/migrations/0004_auto_20201127_0649.py
Wastecoinng/mvp_beta
2faa4b9eeac99b2c284bafad955b90f9951991fc
[ "MIT" ]
null
null
null
mvp/migrations/0004_auto_20201127_0649.py
Wastecoinng/mvp_beta
2faa4b9eeac99b2c284bafad955b90f9951991fc
[ "MIT" ]
null
null
null
mvp/migrations/0004_auto_20201127_0649.py
Wastecoinng/mvp_beta
2faa4b9eeac99b2c284bafad955b90f9951991fc
[ "MIT" ]
null
null
null
# Generated by Django 2.2.13 on 2020-11-27 05:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mvp', '0003_hublocation'), ] operations = [ migrations.RemoveField( model_name='hublocation', name='longitude', ), migrations.AddField( model_name='hublocation', name='longi', field=models.TextField(default=654433, max_length=90, unique=True, verbose_name='Longitude'), preserve_default=False, ), ]
24.166667
105
0.591379
486
0.837931
0
0
0
0
0
0
126
0.217241
bc6daca01b612effa21edcc2bb7e569ddcd2750f
751
py
Python
adminapp/migrations/0012_auto_20210714_1155.py
mofresh27/MuseumExperience-Group2-Python-BE-1
d6ca7aceeddfcfdefdf112ab5e40cf74d6b472ce
[ "MIT" ]
null
null
null
adminapp/migrations/0012_auto_20210714_1155.py
mofresh27/MuseumExperience-Group2-Python-BE-1
d6ca7aceeddfcfdefdf112ab5e40cf74d6b472ce
[ "MIT" ]
1
2021-07-19T14:27:28.000Z
2021-07-19T14:27:28.000Z
adminapp/migrations/0012_auto_20210714_1155.py
mofresh27/MuseumExperience-Group2-Python-BE-1
d6ca7aceeddfcfdefdf112ab5e40cf74d6b472ce
[ "MIT" ]
2
2021-07-14T21:56:46.000Z
2021-07-15T16:11:41.000Z
# Generated by Django 3.2.4 on 2021-07-14 11:55 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('adminapp', '0011_faq'), ] operations = [ migrations.AddField( model_name='faq', name='uuid', field=models.UUIDField(blank=True, default=uuid.uuid4, null=True), ), migrations.AlterField( model_name='faq', name='answer', field=models.TextField(blank=True, default=None, null=True), ), migrations.AlterField( model_name='faq', name='question', field=models.TextField(blank=True, default=None, null=True), ), ]
25.033333
78
0.565912
646
0.860186
0
0
0
0
0
0
106
0.141145
bc6de8ef28a6c9ca4fc7727dee2d21bb765f85a1
1,585
py
Python
scripts/json_parse.py
andrewsimonds14/Capstone
5ae56b9be40846e9993a8f23aaa8e1ef92cd9ea3
[ "MIT" ]
null
null
null
scripts/json_parse.py
andrewsimonds14/Capstone
5ae56b9be40846e9993a8f23aaa8e1ef92cd9ea3
[ "MIT" ]
null
null
null
scripts/json_parse.py
andrewsimonds14/Capstone
5ae56b9be40846e9993a8f23aaa8e1ef92cd9ea3
[ "MIT" ]
null
null
null
import json import os import nibabel as nib import csv from operator import itemgetter # PATH TO PREPROCESSED DATA raw_data_path = '/home/lab/nnUNet_data/nnUNet_raw_data_base/nnUNet_raw_data/Task500_BrainMets' pixdim_ind = [1,2,3] # Indexes at which the voxel size [x,y,z] is stored # PATH TO JSON FILE with open('/home/lab/nnUNet_data/RESULTS_FOLDER/nnUNet/3d_fullres/Task500_BrainMets/nnUNetTrainerV2__nnUNetPlansv2.1/fold_4/validation_raw/summary.json') as file: data = json.load(file) with open('json_parsed.csv', mode='w') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Case Number', 'Dice Score', 'Voxel Size-X', 'Voxel Size-Y', 'Voxel Size-Z']) for img in data['results']['all']: # Get dice score on image dice = img['1']['Dice'] # Get nifti data on image img_filename = (os.path.basename(img['reference']).split('.'))[0] img_ni = nib.load(raw_data_path + '/imagesTr/' + img_filename + '_0000.nii.gz') label_ni = nib.load(raw_data_path + '/labelsTr/' + img_filename + '.nii.gz') voxel_size = itemgetter(*pixdim_ind)(img_ni.header["pixdim"]) # Get tumor dimensions # tumor_size = # Get case number corresponding to image case_number = img_filename.split('_')[1] # Write to csv file csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow([case_number, dice, voxel_size[0], voxel_size[1], voxel_size[2]])
36.860465
162
0.683281
0
0
0
0
0
0
0
0
657
0.414511
bc6e15840fb47699b6ed6ae5254ac356715fcfad
2,794
py
Python
tests/gen_test.py
tinylambda/tornadio2
7b112e2e207bd7500288b42896f9970c16e623ad
[ "Apache-2.0" ]
null
null
null
tests/gen_test.py
tinylambda/tornadio2
7b112e2e207bd7500288b42896f9970c16e623ad
[ "Apache-2.0" ]
null
null
null
tests/gen_test.py
tinylambda/tornadio2
7b112e2e207bd7500288b42896f9970c16e623ad
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ tornadio2.tests.gen ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by the Serge S. Koval, see AUTHORS for more details. :license: Apache, see LICENSE for more details. """ from collections import deque from nose.tools import eq_ from tornadio2 import gen _queue = None def init_environment(): global _queue _queue = deque() def run_sync(test, callback): callback(test) def queue_async(test, callback): global _queue _queue.append((callback, test)) def step_async(): callback = _queue.popleft() callback[0](callback[1]) def run_async(): global _queue while True: try: step_async() except IndexError: break def run_async_oor(): global _queue while True: try: callback = _queue.pop() callback[0](callback[1]) except IndexError: break class Dummy(): def __init__(self, queue_type): self.v = None self.queue_type = queue_type @gen.sync_engine def test(self, value): self.v = yield gen.Task(self.queue_type, value) class DummyList(): def __init__(self, queue_type): self.v = [] self.queue_type = queue_type @gen.sync_engine def test(self, value): self.v.append((yield gen.Task(self.queue_type, value))) class DummyListOutOfOrder(): def __init__(self, queue_type): self.v = [] self.queue_type = queue_type @gen.engine def test(self, value): self.v.append((yield gen.Task(self.queue_type, value))) class DummyLoop(): def __init__(self, queue_type): self.v = 0 self.queue_type = queue_type @gen.sync_engine def test(self, value): for n in range(2): self.v += (yield gen.Task(self.queue_type, value)) def test(): init_environment() dummy = Dummy(run_sync) dummy.test('test') eq_(dummy.v, 'test') def test_async(): init_environment() dummy = Dummy(queue_async) dummy.test('test') run_async() # Verify value eq_(dummy.v, 'test') def test_sync_queue(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_sync_queue_oor(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_async_queue_oor(): init_environment() dummy = DummyListOutOfOrder(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['3', '2', '1'])
17.910256
77
0.598067
916
0.327845
362
0.129563
441
0.157838
0
0
343
0.122763
bc6e2a6ace5b77db9c88569ae6f6456c11dc1f48
21,122
py
Python
DeepBrainSeg/tumor/Tester.py
JordanMicahBennett/DeepBrainSeg
659dd439d20d4c024fe337874eadb90deffc40a4
[ "MIT" ]
1
2021-01-01T18:06:50.000Z
2021-01-01T18:06:50.000Z
DeepBrainSeg/tumor/Tester.py
JordanMicahBennett/DeepBrainSeg
659dd439d20d4c024fe337874eadb90deffc40a4
[ "MIT" ]
null
null
null
DeepBrainSeg/tumor/Tester.py
JordanMicahBennett/DeepBrainSeg
659dd439d20d4c024fe337874eadb90deffc40a4
[ "MIT" ]
1
2021-01-01T18:06:52.000Z
2021-01-01T18:06:52.000Z
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: Avinash Kori # contact: [email protected] import torch import SimpleITK as sitk import numpy as np import nibabel as nib from torch.autograd import Variable from skimage.transform import resize from torchvision import transforms from time import gmtime, strftime from tqdm import tqdm import pdb import os from ..helpers.helper import * from os.path import expanduser home = expanduser("~") #======================================================================================== # prediction functions..................... bin_path = os.path.join('/opt/ANTs/bin/') class tumorSeg(): """ class performs segmentation for a given sequence of patient data. to main platform for segmentation mask estimation one for the patient data in brats format other with any random format step followed for in estimation of segmentation mask 1. ABLnet for reducing false positives outside the brain Air Brain Lesson model (2D model, 103 layered) 2. BNet3Dnet 3D network for inner class classification Dual Path way network 3. MNet2D 57 layered convolutional network for inner class classification 4. Tir3Dnet 57 layered 3D convolutional network for inner class classification more on training details and network information: (https://link.springer.com/chapter/10.1007/978-3-030-11726-9_43<Paste>) ========================= quick: True (just evaluates on Dual path network (BNet3D) else copmutes an ensumble over all four networks """ def __init__(self, quick = False, ants_path = bin_path): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # device = "cpu" map_location = device #======================================================================================== ckpt_tir2D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_2D_FC57_best_loss.pth.tar') ckpt_tir3D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_3D_FC57_best_acc.pth.tar') ckpt_BNET3D = os.path.join(home, '.DeepBrainSeg/BestModels/BrainNet_3D_best_acc.pth.tar') ckpt_ABL = os.path.join(home, '.DeepBrainSeg/BestModels/ABL_CE_best_model_loss_based.pth.tar') #======================================================================================== # air brain lesion segmentation.............. from .models.modelABL import FCDenseNet103 self.ABLnclasses = 3 self.ABLnet = FCDenseNet103(n_classes = self.ABLnclasses) ## intialize the graph saved_parms=torch.load(ckpt_ABL, map_location=map_location) self.ABLnet.load_state_dict(saved_parms['state_dict']) ## fill the model with trained params print ("=================================== ABLNET2D Loaded =================================") self.ABLnet.eval() self.ABLnet = self.ABLnet.to(device) #======================================================================================== # Tir2D net....................... from .models.modelTir2D import FCDenseNet57 self.Mnclasses = 4 self.MNET2D = FCDenseNet57(self.Mnclasses) ckpt = torch.load(ckpt_tir2D, map_location=map_location) self.MNET2D.load_state_dict(ckpt['state_dict']) print ("=================================== MNET2D Loaded ===================================") self.MNET2D.eval() self.MNET2D = self.MNET2D.to(device) #======================================================================================== if not quick: # BrainNet3D model...................... from .models.model3DBNET import BrainNet_3D_Inception self.B3Dnclasses = 5 self.BNET3Dnet = BrainNet_3D_Inception() ckpt = torch.load(ckpt_BNET3D, map_location=map_location) self.BNET3Dnet.load_state_dict(ckpt['state_dict']) print ("=================================== KAMNET3D Loaded =================================") self.BNET3Dnet.eval() self.BNET3Dnet = self.BNET3Dnet.to(device) #======================================================================================== # Tir3D model................... from .models.modelTir3D import FCDenseNet57 self.T3Dnclasses = 5 self.Tir3Dnet = FCDenseNet57(self.T3Dnclasses) ckpt = torch.load(ckpt_tir3D, map_location=map_location) self.Tir3Dnet.load_state_dict(ckpt['state_dict']) print ("================================== TIRNET2D Loaded =================================") self.Tir3Dnet.eval() self.Tir3Dnet = self.Tir3Dnet.to(device) #======================================================================================== self.device = device self.quick = quick self.ants_path = ants_path def get_ants_mask(self, t1_path): """ We make use of ants framework for generalized skull stripping t1_path: t1 volume path (str) saves the mask in the same location as t1 data directory returns: maskvolume (numpy uint8 type) """ mask_path = os.path.join(os.path.dirname(t1_path), 'mask.nii.gz') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' Normalize '+ t1_path) os.system(self.ants_path +'ThresholdImage 3 '+ mask_path +' '+ mask_path +' 0.01 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' MD '+ mask_path +' 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' ME '+ mask_path +' 1') os.system(self.ants_path +'CopyImageHeaderInformation '+ t1_path+' '+ mask_path +' '+ mask_path +' 1 1 1') mask = np.uint8(nib.load(mask_path).get_data()) return mask def get_localization(self, t1_v, t1c_v, t2_v, flair_v, brain_mask): """ ABLnetwork output, finds the brain, Whole tumor region t1_v = t1 volume (numpy array) t1c_v = t1c volume (numpy array) t2_v = t2 volume (numpy array) flair_v = flair volume (numpy array) brain_mask = brain, whole tumor mask (numpy array, output of ANTs pieline) """ t1_v = normalize(t1_v, brain_mask) t1c_v = normalize(t1c_v, brain_mask) t2_v = normalize(t2_v, brain_mask) flair_v = normalize(flair_v, brain_mask) generated_output_logits = np.empty((self.ABLnclasses, flair_v.shape[0],flair_v.shape[1],flair_v.shape[2])) for slices in tqdm(range(flair_v.shape[2])): flair_slice = np.transpose(flair_v[:,:,slices]) t2_slice = np.transpose(t2_v[:,:,slices]) t1ce_slice = np.transpose(t1c_v[:,:,slices]) t1_slice = np.transpose(t1_v[:,:,slices]) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],4)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array[:,:,3] = t1_slice transformed_array = torch.from_numpy(convert_image(array)).float() transformed_array = transformed_array.unsqueeze(0) ## neccessary if batch size == 1 transformed_array = transformed_array.to(self.device) logits = self.ABLnet(transformed_array).detach().cpu().numpy()# 3 x 240 x 240 generated_output_logits[:,:,:, slices] = logits.transpose(0, 1, 3, 2) final_pred = apply_argmax_to_logits(generated_output_logits) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes_air_brain_tumour(np.uint8(final_pred)) return np.uint8(final_pred) def inner_class_classification_with_logits_NCube(self, t1, t1ce, t2, flair, brain_mask, mask, N = 64): """ output of 3D tiramisu model (tir3Dnet) mask = numpy array output of ABLnet N = patch size during inference """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.T3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = N) x_min, x_max, y_min, y_max, z_min, z_max = x_min, min(shape[0] - N, x_max), y_min, min(shape[1] - N, y_max), z_min, min(shape[2] - N, z_max) with torch.no_grad(): for x in tqdm(range(x_min, x_max, N//2)): for y in range(y_min, y_max, N//2): for z in range(z_min, z_max, N//2): high = np.zeros((1, 4, N, N, N)) high[0, 0, :, :, :] = flair[x:x+N, y:y+N, z:z+N] high[0, 1, :, :, :] = t2[x:x+N, y:y+N, z:z+N] high[0, 2, :, :, :] = t1[x:x+N, y:y+N, z:z+N] high[0, 3, :, :, :] = t1ce[x:x+N, y:y+N, z:z+N] high = Variable(torch.from_numpy(high)).to(self.device).float() pred = torch.nn.functional.softmax(self.Tir3Dnet(high).detach().cpu()) pred = pred.data.numpy() final_prediction[:, x:x+N, y:y+N, z:z+N] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_DualPath(self, t1, t1ce, t2, flair, brain_mask, mask=None, prediction_size = 9): """ output of BNet3D prediction_size = mid inference patch size """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.B3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = prediction_size) # obtained by aspect ratio calculation high_res_size = prediction_size + 16 resize_to = int(prediction_size ** 0.5) + 16 low_res_size = int(51*resize_to/19) hl_pad = (high_res_size - prediction_size)//2 hr_pad = hl_pad + prediction_size ll_pad = (low_res_size - prediction_size)//2 lr_pad = ll_pad + prediction_size for x in tqdm(range(x_min, x_max - prediction_size, prediction_size)): for y in (range(y_min, y_max - prediction_size, prediction_size)): for z in (range(z_min, z_max - prediction_size, prediction_size)): high = np.zeros((1, 4, high_res_size, high_res_size, high_res_size)) low = np.zeros((1, 4, low_res_size, low_res_size, low_res_size)) low1 = np.zeros((1, 4, resize_to, resize_to, resize_to)) high[0, 0], high[0, 1], high[0, 2], high[0, 3] = high[0, 0] + flair[0,0,0], high[0, 1] + t2[0,0,0], high[0, 2] + t1[0,0,0], high[0, 2] + t1ce[0,0,0] low[0, 0], low[0, 1], low[0, 2], low[0, 3] = low[0, 0] + flair[0,0,0], low[0, 1] + t2[0,0,0], low[0, 2] + t1[0,0,0], low[0, 2] + t1ce[0,0,0] low1[0, 0], low1[0, 1], low1[0, 2], low1[0, 3] = low1[0, 0] + flair[0,0,0], low1[0, 1] + t2[0,0,0], low1[0, 2] + t1[0,0,0], low1[0, 2] + t1ce[0,0,0] # ========================================================================= vxf, vxt = max(0, x-hl_pad), min(shape[0], x+hr_pad) vyf, vyt = max(0, y-hl_pad), min(shape[1], y+hr_pad) vzf, vzt = max(0, z-hl_pad), min(shape[2], z+hr_pad) txf, txt = max(0, hl_pad-x), max(0, hl_pad-x) + vxt - vxf tyf, tyt = max(0, hl_pad-y), max(0, hl_pad-y) + vyt - vyf tzf, tzt = max(0, hl_pad-z), max(0, hl_pad-z) + vzt - vzf high[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= vxf, vxt = max(0, x-ll_pad), min(shape[0], x+lr_pad) vyf, vyt = max(0, y-ll_pad), min(shape[1], y+lr_pad) vzf, vzt = max(0, z-ll_pad), min(shape[2], z+lr_pad) txf, txt = max(0, ll_pad-x), max(0, ll_pad-x) + vxt - vxf tyf, tyt = max(0, ll_pad-y), max(0, ll_pad-y) + vyt - vyf tzf, tzt = max(0, ll_pad-z), max(0, ll_pad-z) + vzt - vzf low[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= low1[0] = [resize(low[0, i, :, :, :], (resize_to, resize_to, resize_to)) for i in range(4)] high = Variable(torch.from_numpy(high)).to(self.device).float() low1 = Variable(torch.from_numpy(low1)).to(self.device).float() pred = torch.nn.functional.softmax(self.BNET3Dnet(high, low1, pred_size=prediction_size).detach().cpu()) pred = pred.numpy() final_prediction[:, x:x+prediction_size, y:y+prediction_size, z:z+prediction_size] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_2D(self, t1ce_volume, t2_volume, flair_volume): """ output of 2D tiramisu model (MNet) """ normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) transformList = [] transformList.append(transforms.ToTensor()) transformList.append(normalize) transformSequence=transforms.Compose(transformList) generated_output = np.empty((self.Mnclasses,flair_volume.shape[0],flair_volume.shape[1],flair_volume.shape[2])) for slices in tqdm(range(flair_volume.shape[2])): flair_slice = scale_every_slice_between_0_to_255(np.transpose(flair_volume[:,:,slices])) t2_slice = scale_every_slice_between_0_to_255(np.transpose(t2_volume[:,:,slices])) t1ce_slice = scale_every_slice_between_0_to_255(np.transpose(t1ce_volume[:,:,slices])) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],3)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array = np.uint8(array) transformed_array = transformSequence(array) transformed_array = transformed_array.unsqueeze(0) transformed_array = transformed_array.to(self.device) outs = torch.nn.functional.softmax(self.MNET2D(transformed_array).detach().cpu()).numpy() outs = np.swapaxes(generated_output,1, 2) return outs def get_segmentation(self, t1_path, t2_path, t1ce_path, flair_path, save_path = None): """ Generates segmentation for the data not in brats format if save_path provided function saves the prediction with DeepBrainSeg_Prediction.nii.qz name in the provided directory returns: segmentation mask """ t1 = nib.load(t1_path).get_data() t2 = nib.load(t2_path).get_data() t1ce = nib.load(t1ce_path).get_data() flair = nib.load(flair_path).get_data() affine = nib.load(flair_path).affine brain_mask = self.get_ants_mask(t2_path) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) # mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair).transpose(0, 2, 1, 3) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save_path: os.makedirs(save_path, exist_ok=True) save_volume(final_pred, affine, os.path.join(save_path, 'DeepBrainSeg_Prediction')) return final_pred def get_segmentation_brats(self, path, save = True): """ Generates segmentation for the data in BraTs format if save True saves the prediction in the save directory in the patients data path returns : segmentation mask """ name = path.split("/")[-1] + "_" flair = nib.load(os.path.join(path, name + 'flair.nii.gz')).get_data() t1 = nib.load(os.path.join(path, name + 't1.nii.gz')).get_data() t1ce = nib.load(os.path.join(path, name + 't1ce.nii.gz')).get_data() t2 = nib.load(os.path.join(path, name + 't2.nii.gz')).get_data() affine= nib.load(os.path.join(path, name + 'flair.nii.gz')).affine print ("[INFO: DeepBrainSeg] (" + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) + ") Working on: ", path) brain_mask = self.get_ants_mask(os.path.join(path, name + 't2.nii.gz')) # brain_mask = get_brain_mask(t1) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save: save_volume(final_pred, affine, os.path.join(path, 'DeepBrainSeg_Prediction')) return final_pred # ======================================================================================== if __name__ == '__main__': ext = deepSeg(True) ext.get_segmentation_brats('../../sample_volume/Brats18_CBICA_AVG_1/')
46.937778
168
0.548717
20,264
0.959379
0
0
0
0
0
0
4,831
0.228719
bc6e8fa55969e186c06ce2946db2244dfbf09a10
7,334
py
Python
statsmodels/discrete/tests/test_conditional.py
porcpine1967/statsmodels
db4900056d80732ffff2733454fac88781ced8d2
[ "BSD-3-Clause" ]
null
null
null
statsmodels/discrete/tests/test_conditional.py
porcpine1967/statsmodels
db4900056d80732ffff2733454fac88781ced8d2
[ "BSD-3-Clause" ]
null
null
null
statsmodels/discrete/tests/test_conditional.py
porcpine1967/statsmodels
db4900056d80732ffff2733454fac88781ced8d2
[ "BSD-3-Clause" ]
null
null
null
import numpy as np from statsmodels.discrete.conditional_models import ( ConditionalLogit, ConditionalPoisson) from statsmodels.tools.numdiff import approx_fprime from numpy.testing import assert_allclose import pandas as pd def test_logit_1d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, ] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.9272407], rtol=1e-5) assert_allclose(result.bse, np.r_[1.295155], rtol=1e-5) def test_logit_2d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[0, 0, 1, 0, 0, 1, 0, 1, 1, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, -1.5*x] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad, rtol=1e-5) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[1.011074, 1.236758], rtol=1e-3) assert_allclose(result.bse, np.r_[1.420784, 1.361738], rtol=1e-5) result.summary() def test_formula(): for j in 0, 1: np.random.seed(34234) n = 200 y = np.random.randint(0, 2, size=n) x1 = np.random.normal(size=n) x2 = np.random.normal(size=n) g = np.random.randint(0, 25, size=n) x = np.hstack((x1[:, None], x2[:, None])) if j == 0: model1 = ConditionalLogit(y, x, groups=g) else: model1 = ConditionalPoisson(y, x, groups=g) result1 = model1.fit() df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "g": g}) if j == 0: model2 = ConditionalLogit.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) else: model2 = ConditionalPoisson.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) result2 = model2.fit() assert_allclose(result1.params, result2.params, rtol=1e-5) assert_allclose(result1.bse, result2.bse, rtol=1e-5) assert_allclose(result1.cov_params(), result2.cov_params(), rtol=1e-5) assert_allclose(result1.tvalues, result2.tvalues, rtol=1e-5) def test_poisson_1d(): y = np.r_[3, 1, 1, 4, 5, 2, 0, 1, 6, 2] g = np.r_[0, 0, 0, 0, 1, 1, 1, 1, 1, 1] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.6466272], rtol=1e-4) assert_allclose(result.bse, np.r_[0.4170918], rtol=1e-5) def test_poisson_2d(): y = np.r_[3, 1, 4, 8, 2, 5, 4, 7, 2, 6] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[2, 1, 0, 0, 1, 2, 3, 2, 0, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[-.9478957, -.0134279], rtol=1e-3) assert_allclose(result.bse, np.r_[.3874942, .1686712], rtol=1e-5) result.summary() def test_lasso_logistic(): np.random.seed(3423948) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = 1 / (1 + np.exp(-lin_pred)) y = (np.random.uniform(size=n) < mean).astype(np.int) model0 = ConditionalLogit(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalLogit(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalLogit(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.05) # Rxegression test assert_allclose(result2.params, np.r_[0, 0, 0.55235152, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalLogit.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.05) assert_allclose(result2.params, result3.params) def test_lasso_poisson(): np.random.seed(342394) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = np.exp(lin_pred) y = np.random.poisson(mean) model0 = ConditionalPoisson(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalPoisson(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalPoisson(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.2) # Regression test assert_allclose(result2.params, np.r_[0, 0, 0.91697508, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalPoisson.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.2) assert_allclose(result2.params, result3.params)
30.558333
78
0.587947
0
0
0
0
0
0
0
0
659
0.089855
bc710066cef80510ad81cb68d1ed3e70cec4fc2d
905
py
Python
bert_e/workflow/gitwaterflow/utils.py
tcarmet/bert-e
8e0623d9a8c7bd111790d72307862167eca18a23
[ "Apache-2.0" ]
null
null
null
bert_e/workflow/gitwaterflow/utils.py
tcarmet/bert-e
8e0623d9a8c7bd111790d72307862167eca18a23
[ "Apache-2.0" ]
35
2020-08-26T09:25:56.000Z
2022-01-10T20:38:15.000Z
bert_e/workflow/gitwaterflow/utils.py
tcarmet/bert-e
8e0623d9a8c7bd111790d72307862167eca18a23
[ "Apache-2.0" ]
2
2021-08-17T15:56:50.000Z
2022-01-05T19:26:48.000Z
def bypass_incompatible_branch(job): return (job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False)) def bypass_peer_approval(job): return (job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False)) def bypass_leader_approval(job): return (job.settings.bypass_leader_approval or job.author_bypass.get('bypass_leader_approval', False)) def bypass_author_approval(job): return (job.settings.bypass_author_approval or job.author_bypass.get('bypass_author_approval', False)) def bypass_build_status(job): return (job.settings.bypass_build_status or job.author_bypass.get('bypass_build_status', False)) def bypass_jira_check(job): return (job.settings.bypass_jira_check or job.author_bypass.get('bypass_jira_check', False))
30.166667
71
0.742541
0
0
0
0
0
0
0
0
138
0.152486
bc71cbe7f13c2f51663de7c1b18572924543ac36
26,868
py
Python
bkt/library/powerpoint/elements.py
pyro-team/bkt-toolbox
bbccba142a81ca0a46056f2bcda75899979158a5
[ "MIT" ]
12
2019-05-31T02:57:26.000Z
2022-03-26T09:40:50.000Z
bkt/library/powerpoint/elements.py
mrflory/bkt-toolbox
bbccba142a81ca0a46056f2bcda75899979158a5
[ "MIT" ]
27
2021-11-27T16:33:19.000Z
2022-03-27T17:47:26.000Z
bkt/library/powerpoint/elements.py
pyro-team/bkt-toolbox
bbccba142a81ca0a46056f2bcda75899979158a5
[ "MIT" ]
3
2019-06-12T10:59:20.000Z
2020-04-21T15:13:50.000Z
# -*- coding: utf-8 -*- ''' Created on 02.11.2017 @author: fstallmann ''' from __future__ import absolute_import from collections import deque import bkt from bkt import dotnet Drawing = dotnet.import_drawing() from . import helpers as pplib class TextframeSpinnerBox(bkt.ribbon.RoundingSpinnerBox): ### Instance initialization attr = 'MarginTop' def __init__(self, **kwargs): ''' attr examples: MarginTop, MarginBottom, MarginLeft, MarginRight ''' #self.attr is automatically set through RibbonControl attribute handling self.fallback_value = 0 my_kwargs = dict( size_string = '###', round_cm = True, convert = 'pt_to_cm', get_enabled = bkt.apps.ppt_selection_contains_textframe, ) my_kwargs.update(kwargs) super(TextframeSpinnerBox, self).__init__(**my_kwargs) ### Spinner Box callbacks ### def get_text(self, shapes, selection): value = self.get_attr_from_shapes(shapes, selection) if value is None: #e.g. no textframe detected return None elif int(value) == -2147483648: #replace large negative number (values differ between selected items) with fallback value return self.fallback_value else: return value def on_change(self, shapes, selection, value): self.set_attr_for_shapes(shapes, selection, value) ### Getter Methods ### def get_attr_from_shapes(self, shapes, selection): ''' Get attr for shapes ''' for textframe in pplib.iterate_shape_textframes(shapes): try: return self.get_attr_from_textframe(textframe) except: # produces error for certain chart types, e.g. Treemap continue return None def get_attr_from_textframe(self, textframe): return getattr(textframe, self.attr) ### Setter methods ### def set_attr_for_shapes(self, shapes, selection, value): ''' Set attr for shapes ''' value = max(0,value) for textframe in pplib.iterate_shape_textframes(shapes): self.set_attr_for_textframe(textframe, value) def set_attr_for_textframe(self, textframe, value): setattr(textframe, self.attr, value) class ParagraphFormatSpinnerBox(bkt.ribbon.RoundingSpinnerBox): ### Instance initialization attr = 'SpaceBefore' def __init__(self, **kwargs): ''' attr examples: SpaceBefore, SpaceAfter, LeftIndent, FirstLineIndent, LineSpacing ''' #self.attr is automatically set through RibbonControl attribute handling self.fallback_value = 0 my_kwargs = dict( size_string = '-###', get_enabled = bkt.apps.ppt_selection_contains_textframe, ) if self.attr in ["SpaceBefore", "SpaceAfter", "SpaceWithin"]: my_kwargs["round_pt"] = True else: my_kwargs["round_cm"] = True my_kwargs["convert"] = "pt_to_cm" if self.attr in ["LeftIndent", "FirstLineIndent"]: my_kwargs["big_step"] = 0.25 my_kwargs["small_step"] = 0.125 my_kwargs["rounding_factor"] = 0.125 my_kwargs.update(kwargs) super(ParagraphFormatSpinnerBox, self).__init__(**my_kwargs) ### Spinner Box callbacks ### def get_text(self, shapes, selection): value = self.get_attr_from_shapes(shapes, selection) if value is None: #e.g. no textframe detected return None elif int(value) == -2147483648: #replace large negative number (values differ between selected items) with fallback value return self.fallback_value else: return value def on_change(self, shapes, selection, value): self.set_attr_for_shapes(shapes, selection, value) ### Getter Methods ### def get_attr_from_shapes(self, shapes, selection): if selection.Type == 3: # text selected try: # produces error if no text is selected return self._get_attr(selection.TextRange2.Paragraphs(1,1).ParagraphFormat) except: try: # produces error if there is no textrange, e.g. selection within a chart return self._get_attr(selection.TextRange2.ParagraphFormat) except: return None else: # shapes selected for textframe in pplib.iterate_shape_textframes(shapes): try: value = self.get_attr_from_textrange(textframe.TextRange) except: # produces error for certain chart types, e.g. Treemap continue try: if int(value) == -2147483648: #different values for each paragraph, so get value from first paragraph value = self._get_attr(textframe.TextRange.Paragraphs(1,1).ParagraphFormat) except: pass return value return None def get_attr_from_textrange(self, textrange): return self._get_attr(textrange.ParagraphFormat) def _get_attr(self, par_format): if self.attr in ["SpaceBefore", "SpaceAfter", "SpaceWithin"]: if (self.attr == "SpaceBefore" and par_format.LineRuleBefore == 0) or (self.attr == "SpaceAfter" and par_format.LineRuleAfter == 0) or (self.attr == "SpaceWithin" and par_format.LineRuleWithin == 0): self.huge_step = 10 self.big_step = 3 self.small_step = 1 self.round_at = 0 else: self.huge_step = 0.5 self.big_step = 0.2 self.small_step = 0.1 self.round_at = 1 return getattr(par_format, self.attr) ### Setter methods ### def set_attr_for_shapes(self, shapes, selection, value): if self.attr != "FirstLineIndent": #FirstLineIndent can be negative! value = max(0,value) if selection.Type == 3: # text selected self.set_attr_for_textrange(selection.TextRange2, value) #need to use TextRange2 as TextRange does not contain LeftIndent, etc. else: for textframe in pplib.iterate_shape_textframes(shapes): self.set_attr_for_textrange(textframe.TextRange, value) def set_attr_for_textrange(self, textrange, value): #using textrange instead of textframe! if self.attr == "SpaceBefore" and textrange.ParagraphFormat.LineRuleBefore == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleBefore = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleBefore if self.attr == "SpaceAfter" and textrange.ParagraphFormat.LineRuleAfter == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleAfter = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleAfter if self.attr == "SpaceWithin" and textrange.ParagraphFormat.LineRuleWithin == -2: #if values differ, set the same value as in the first paragraph textrange.ParagraphFormat.LineRuleWithin = textrange.Paragraphs(1,1).ParagraphFormat.LineRuleWithin setattr(textrange.ParagraphFormat, self.attr, value) class PPTSymbolsSettings(object): recent_symbols = deque(bkt.settings.get("bkt.symbols.recent_symbols", []), maxlen=3) convert_into_shape = bkt.settings.get("bkt.symbols.convert_into_shape", True) #always convert newly inserted symbols into shapes convert_into_bitmap = bkt.settings.get("bkt.symbols.convert_into_bitmap", False) #always convert newly inserted symbols into bitmap picture unicode_font = bkt.settings.get("bkt.symbols.unicode_font", None) #insert unicode characters as symbol with special font (e.g. Arial Unicode) @classmethod def add_to_recent(cls, item): try: #try to remove if already exists and add to beginning cls.recent_symbols.remove(item) cls.recent_symbols.append(item) except ValueError: cls.recent_symbols.append(item) bkt.settings["bkt.symbols.recent_symbols"] = cls.recent_symbols @classmethod def switch_unicode_font(cls, font=None): cls.unicode_font = font #if font else SymbolsGallery.fallback_font bkt.settings["bkt.symbols.unicode_font"] = cls.unicode_font @classmethod def convert_into_text(cls): return not (cls.convert_into_shape or cls.convert_into_bitmap) @classmethod def switch_convert_into_text(cls, pressed): cls.convert_into_shape = False cls.convert_into_bitmap = False bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def switch_convert_into_shape(cls, pressed): cls.convert_into_shape = pressed cls.convert_into_bitmap = False bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def get_convert_into_shape(cls): return (cls.convert_into_shape or bkt.get_key_state(bkt.KeyCodes.SHIFT)) and not bkt.get_key_state(bkt.KeyCodes.CTRL) @classmethod def switch_convert_into_bitmap(cls, pressed): cls.convert_into_shape = False cls.convert_into_bitmap = pressed bkt.settings["bkt.symbols.convert_into_shape"] = cls.convert_into_shape bkt.settings["bkt.symbols.convert_into_bitmap"] = cls.convert_into_bitmap @classmethod def get_convert_into_bitmap(cls): return (cls.convert_into_bitmap or bkt.get_key_state(bkt.KeyCodes.CTRL)) and not bkt.get_key_state(bkt.KeyCodes.SHIFT) class PPTSymbolsGallery(bkt.ribbon.SymbolsGallery): @property def fallback_font(self): return PPTSymbolsSettings.unicode_font or bkt.ribbon.SymbolsGallery.fallback_font def on_action_indexed(self, selected_item, index, context, selection, **kwargs): ''' create numberd shape according of settings in clicked element ''' item = self.symbols[index] self._add_to_recent(item) shift_or_ctrl = bkt.get_key_state(bkt.KeyCodes.CTRL) or bkt.get_key_state(bkt.KeyCodes.SHIFT) if selection.Type == 3 and not shift_or_ctrl: #text selected selection.TextRange2.Text = "" #remove selected text first and then insert symbol self.insert_symbol_into_text(selection.TextRange2, item) elif PPTSymbolsSettings.convert_into_text() and selection.Type == 2 and not shift_or_ctrl: #shapes selected self.insert_symbol_into_shapes(pplib.get_shapes_from_selection(selection), item) else: #convert into shape or bitmap if PPTSymbolsSettings.get_convert_into_bitmap(): self.create_symbol_bitmap(selection.SlideRange(1), item) else: self.create_symbol_shape(selection.SlideRange(1), item) def _add_to_recent(self, item): PPTSymbolsSettings.add_to_recent(item) def insert_symbol_into_text(self, textrange, item): if item[0] or PPTSymbolsSettings.unicode_font is not None: #font name is given, then insert as symbol font = item[0] or self.fallback_font try: char_number = ord(item[1]) #ord does not work for higher level unicode, e.g. emojis, and throws TypeError if char_number > 61695: #for higher numbers (f0ff works, f100 doesnt work) InsertSymbol does not work anymore. Also the default ppt symbol-picker only shows unicode chars til f0ff. raise TypeError("character number to large for InsertSymbol") #fallback to InsertAfter placeholder_char = textrange.InsertAfter("X") #append placeholder symbol so that InsertSymbol behaves the same as InsertAfter return placeholder_char.InsertSymbol(font, char_number, -1) #symbol: FontName, CharNumber (decimal), Unicode=True except TypeError: char_inserted = textrange.InsertAfter(item[1]) #append symbol text #so, NameFarEast and NameComplexScript should be writable, but they are not if InsertSymbol is used before (it remains the font of the symbol). only way to replace these values and correctly show icon is setting it to '+mn-..' char_inserted.Font.NameFarEast = "+mn-ea" char_inserted.Font.NameComplexScript = "+mn-cs" char_inserted.Font.Name = font #font name return char_inserted else: return textrange.InsertAfter(item[1]) #append symbol text # if item[0]: # char_inserted.Font.Name = item[0] #font name def insert_symbol_into_shapes(self, shapes, item): #pplib.iterate_shape_textframes(shapes, lambda textframe: self.insert_symbol_into_text(textframe.TextRange, item)) for textframe in pplib.iterate_shape_textframes(shapes): self.insert_symbol_into_text(textframe.TextRange, item) # for shape in shapes: # if shape.HasTextFrame == -1: # self.insert_symbol_into_text(shape.TextFrame2.TextRange, item) def create_symbol_shape(self, slide, item): shape = slide.shapes.addTextbox( #office.MsoAutoShapeType.msoShapeRectangle.value__, 1, 100,100,200,200) shape.TextFrame2.WordWrap = 0 shape.TextFrame2.AutoSize = 1 #ppAutoSizeShapeToFitText shape.TextFrame2.MarginBottom = 0 shape.TextFrame2.MarginTop = 0 shape.TextFrame2.MarginLeft = 0 shape.TextFrame2.MarginRight = 0 self.insert_symbol_into_text(shape.TextFrame2.TextRange, item) # if item[0]: # shape.TextFrame.TextRange.Font.Name = item[0] #font name # shape.TextFrame.TextRange.Text = item[1] #symbol text if PPTSymbolsSettings.get_convert_into_shape(): #convert into shape try: orig_fontsize = shape.TextFrame2.TextRange.Font.Size shape.TextFrame2.TextRange.Font.Size = 60 shape.TextFrame2.TextRange.ParagraphFormat.Bullet.Visible = 0 new_shape = pplib.convert_text_into_shape(shape) new_shape.TextFrame2.TextRange.Font.Size = orig_fontsize except: shape.select() else: new_shape.select() else: shape.select() def create_symbol_bitmap(self, slide, item): import tempfile, os font = item[0] or self.fallback_font img = bkt.ribbon.SymbolsGallery.create_symbol_image(font, item[1], 400, None) tmpfile = os.path.join(tempfile.gettempdir(), "bkt-symbol.png") img.Save(tmpfile, Drawing.Imaging.ImageFormat.Png) shape = slide.shapes.AddPicture(tmpfile, 0, -1, 200, 200) #FileName, LinkToFile, SaveWithDocument, Left, Top shape.select() os.remove(tmpfile) class PPTSymbolsGalleryRecent(PPTSymbolsGallery): @property def symbols(self): return PPTSymbolsSettings.recent_symbols @symbols.setter def symbols(self, value): pass def get_item_image(self, index): try: return super(PPTSymbolsGalleryRecent, self).get_item_image(index) except: return super(PPTSymbolsGalleryRecent, self).create_symbol_image("Arial", "?") def button_get_label(self, index): try: return self.symbols[index][2] except: return "Zuletzt verwendet: Undefined" def button_get_visible(self, index): try: return self.symbols[index] is not None except: return False def get_index_as_button(self, index): return bkt.ribbon.Button( id="{}_button_{}".format(self.id, index), get_label=bkt.Callback(lambda: self.button_get_label(index)), on_action=bkt.Callback(lambda context, selection: self.on_action_indexed(None, index, context, selection)), get_image=bkt.Callback(lambda: self.get_item_image(index)), get_visible=bkt.Callback(lambda: self.button_get_visible(index)), ) class LocpinGallery(bkt.ribbon.Gallery): def __init__(self, locpin=None, item_supertip="Shape-Fixpunkt bzw. Fixierung bei Änderung {}", **kwargs): self.locpin = locpin or pplib.GlobalLocPin self.items = [ ("fix_locpin_tl", "Oben-links", item_supertip.format("oben-links")), ("fix_locpin_tm", "Oben-mitte", item_supertip.format("oben-mitte")), ("fix_locpin_tr", "Oben-rechts", item_supertip.format("oben-rechts")), ("fix_locpin_ml", "Mitte-links", item_supertip.format("mitte-links")), ("fix_locpin_mm", "Mitte-mitte", item_supertip.format("mitte-mitte")), ("fix_locpin_mr", "Mitte-rechts", item_supertip.format("mitte-rechts")), ("fix_locpin_bl", "Unten-links", item_supertip.format("unten-links")), ("fix_locpin_bm", "Unten-mitte", item_supertip.format("unten-mitte")), ("fix_locpin_br", "Unten-rechts", item_supertip.format("unten-rechts")), ] my_kwargs = dict( # get_enabled=bkt.apps.ppt_shapes_or_text_selected, columns="3", item_height="24", item_width="24", show_item_label=False, on_action_indexed = bkt.Callback(self.locpin_on_action_indexed), get_selected_item_index = bkt.Callback(lambda: self.locpin.index), get_item_count = bkt.Callback(lambda: len(self.items)), get_item_label = bkt.Callback(lambda index: self.items[index][1]), get_item_image = bkt.Callback(self.locpin_get_image, context=True), get_item_screentip = bkt.Callback(lambda index: self.items[index][1]), get_item_supertip = bkt.Callback(lambda index: self.items[index][2]), # children = [ # Item(image=gal_item[0], screentip=gal_item[1], supertip=gal_item[2]) # for gal_item in self.items # ] ) if not "image" in kwargs and not "image_mso" in kwargs: my_kwargs["get_image"] = bkt.Callback(self.locpin_get_image, context=True) my_kwargs.update(kwargs) super(LocpinGallery, self).__init__(**my_kwargs) def locpin_on_action_indexed(self, selected_item, index): self.locpin.index = index def locpin_get_image(self, context, index=None): if index is None: return context.python_addin.load_image(self.items[self.locpin.index][0]) else: return context.python_addin.load_image(self.items[index][0]) class PositionGallery(bkt.ribbon.Gallery): # items: [label, position, reference] # position: [left, top, width, height] # values can be absolute or percentage # reference: CONTENTE / SLIDE / ABS # values are converted according to reference items = [ [u"Volle Fläche", [ 0, 0, 1, 1], 'CONTENT'], [u"2/3 Links", [ 0, 0, 2./3, 1], 'CONTENT'], [u"2/3 Rechts", [1./3, 0, 2./3, 1], 'CONTENT'], [u"1/2 Links", [ 0, 0, .5, 1], 'CONTENT'], [u"1/2 Mitte", [.25, 0, .5, 1], 'CONTENT'], [u"1/2 Rechts", [ .5, 0, .5, 1], 'CONTENT'], [u"1/3 Links", [ 0, 0, 1./3, 1], 'CONTENT'], [u"1/3 Mitte", [1./3, 0, 1./3, 1], 'CONTENT'], [u"1/3 Rechts", [2./3, 0, 1./3, 1], 'CONTENT'], [u"1/6 Oben", [ 0, 0, 1, 1./6], 'CONTENT'], [u"1/6 Unten", [ 0, 5./6, 1, 1./6], 'CONTENT'] ] def __init__(self, positions=None, label="Standardpositionen", columns=3, **kwargs): self.items = positions or PositionGallery.items super(PositionGallery, self).__init__( label = label, columns = columns, image_mso='PositionAnchoringGallery', supertip=u"Positioniere die ausgewählten Shapes auf eine Standardposition.", children=[ bkt.ribbon.Button( label="Benutzerdef. Bereich festlegen", supertip="Der benutzerdefinierte Bereich wird anhand des gewählten Shapes festgelegt. Dieser Bereich ist anschließend über die Gallery wählbar und wird dauerhaft in der aktuellen Prästentation vorgehalten.", on_action=bkt.Callback(self.set_userdefined_area), get_enabled = bkt.get_enabled_auto ) ], **kwargs ) def on_action_indexed(self, selected_item, index, context, **kwargs): ''' reposition shapes according of settings in clicked element ''' item = self.items[index] position = item[1] reference = item[2] #self.change_position(selection, shapes, item[1]) # reference size if reference == 'CONTENT': ref_left,ref_top,ref_width,ref_height = pplib.slide_content_size(context.slide) else: # SLIDE / ABS page_setup = context.presentation.PageSetup ref_left,ref_top = 0, 0 ref_width,ref_height = page_setup.SlideWidth, page_setup.SlideHeight # target size left,top,width,height = self.rect_from_definition(position, ref_frame=[ref_left,ref_top,ref_width, ref_height]) frame = pplib.BoundingFrame.from_rect(left, top, width, height) if 'on_position_change' in self._callbacks: if context: return context.invoke_callback(self._callbacks['on_position_change'], target_frame=frame, **kwargs) def get_item_count(self, presentation): self.init_userdefined_area_item(presentation) return len(self.items) # def get_enabled(self, shapes): # return True # def get_item_label(self, index): # item = self.items[index] # return "%s" % getattr(NumberedShapes, 'label_' + item['label'])[index%self.columns] def get_item_image(self, index, presentation): ''' creates an item image with target area according to settings in the specified item ''' # retrieve item-settings item = self.items[index] return self.create_image(item[1], item[2], presentation) def get_item_screentip(self, index): # retrieve item-settings item = self.items[index] return 'Positionierung: ' + item[0] def get_item_supertip(self, index): return 'Verwende angezeigten Position/Größe.' def create_image(self, position, reference, presentation): # create bitmap, define pen/brush height = 40 width = height*16./9 img = Drawing.Bitmap(width, height) g = Drawing.Graphics.FromImage(img) # reference size if reference == 'CONTENT': v_offset = height/5 v_ref = (height*4)/5 left,top,fill_width,fill_height = self.rect_from_definition(position, ref_frame=[0,v_offset,width, v_ref]) else: # SLIDE / ABS ref_width,ref_height = presentation.PageSetup.SlideWidth, presentation.PageSetup.SlideHeight left,top,fill_width,fill_height = self.rect_from_definition(position, ref_frame=[0,0,ref_width, ref_height]) left = left /ref_width * width fill_width = fill_width /ref_width * width top = top /ref_height * height fill_height = fill_height/ref_height * height color = Drawing.ColorTranslator.FromHtml('#ffdd0000') brush = Drawing.SolidBrush(color) g.FillRectangle(brush, Drawing.Rectangle(round(left),round(top), round(fill_width), round(fill_height))) color = Drawing.ColorTranslator.FromHtml('#ff999999') pen = Drawing.Pen(color,1) g.DrawRectangle(pen, Drawing.Rectangle(0,0, width-1, height/5-1)) g.DrawRectangle(pen, Drawing.Rectangle(0,0, width-1, height-1)) return img def rect_from_definition(self, pos_definition, ref_frame=[0,0,640,480]): left = self.length_from_definition(pos_definition[0], ref_frame[2]) + ref_frame[0] top = self.length_from_definition(pos_definition[1], ref_frame[3]) + ref_frame[1] width = self.length_from_definition(pos_definition[2], ref_frame[2]) height = self.length_from_definition(pos_definition[3], ref_frame[3]) return left, top, width, height def length_from_definition(self, length_definition, reference): if type(length_definition) == list: # allow [150, 50%] l = 0 for ldef in length_definition: l += self.length_from_definition(ldef, reference) return l elif type(length_definition) in [int, float, long]: if length_definition < 0: # negative values specify distance 'from right' return reference - self.length_from_definition(-length_definition, reference) elif length_definition <= 1: # percentage values return reference * length_definition else: # absolute values return length_definition else: return 10 ## userdefined area def set_userdefined_area(self, presentation, shapes): if len(shapes) == 1: pplib.ContentArea.define_contentarea(presentation, shapes[0]) else: frame = pplib.BoundingFrame.from_shapes(shapes) pplib.ContentArea.define_contentarea(presentation, frame) self.init_userdefined_area_item(presentation) def init_userdefined_area_item(self, presentation): #due to performance check first if tag exists at all if pplib.ContentArea.isset_contentarea(presentation): left, top, width, height = pplib.ContentArea.read_contentarea(presentation) if len(self.items) == 12: self.items.pop() self.items.append([u"Benutzerdef. Bereich", [left, top, width, height], 'ABS'])
42.512658
242
0.628703
26,605
0.989843
0
0
2,200
0.081851
0
0
6,481
0.241127
bc73adc709a1a6dd422dd898ada82a431739cb7e
34,680
py
Python
sc2/unit.py
guliverza/AdditionalPylons
37336dcd1678c6cdfa22d881c2178ba65cb1fd61
[ "MIT" ]
null
null
null
sc2/unit.py
guliverza/AdditionalPylons
37336dcd1678c6cdfa22d881c2178ba65cb1fd61
[ "MIT" ]
null
null
null
sc2/unit.py
guliverza/AdditionalPylons
37336dcd1678c6cdfa22d881c2178ba65cb1fd61
[ "MIT" ]
null
null
null
from __future__ import annotations import warnings from typing import Any, Dict, List, Optional, Set, Tuple, Union, TYPE_CHECKING from .cache import property_immutable_cache, property_mutable_cache from .constants import ( transforming, IS_STRUCTURE, IS_LIGHT, IS_ARMORED, IS_BIOLOGICAL, IS_MECHANICAL, IS_MASSIVE, IS_PSIONIC, UNIT_BATTLECRUISER, UNIT_ORACLE, TARGET_GROUND, TARGET_AIR, TARGET_BOTH, IS_SNAPSHOT, IS_VISIBLE, IS_MINE, IS_ENEMY, IS_CLOAKED, IS_REVEALED, CAN_BE_ATTACKED, IS_CARRYING_MINERALS, IS_CARRYING_VESPENE, IS_CARRYING_RESOURCES, IS_ATTACKING, IS_PATROLLING, IS_GATHERING, IS_RETURNING, IS_COLLECTING, IS_CONSTRUCTING_SCV, IS_REPAIRING, IS_DETECTOR, UNIT_PHOTONCANNON, UNIT_COLOSSUS, ) from .data import Alliance, Attribute, CloakState, DisplayType, Race, TargetType, warpgate_abilities, TargetType, Target from .ids.ability_id import AbilityId from .ids.buff_id import BuffId from .ids.upgrade_id import UpgradeId from .ids.unit_typeid import UnitTypeId from .position import Point2, Point3 from .unit_command import UnitCommand warnings.simplefilter("once") if TYPE_CHECKING: from .bot_ai import BotAI from .game_data import AbilityData class UnitOrder: @classmethod def from_proto(cls, proto, bot_object: BotAI): return cls( bot_object._game_data.abilities[proto.ability_id], (proto.target_world_space_pos if proto.HasField("target_world_space_pos") else proto.target_unit_tag), proto.progress, ) def __init__(self, ability: AbilityData, target, progress: float = None): """ :param ability: :param target: :param progress: """ self.ability = ability self.target = target self.progress = progress def __repr__(self) -> str: return f"UnitOrder({self.ability}, {self.target}, {self.progress})" class Unit: def __init__(self, proto_data, bot_object: BotAI): """ :param proto_data: :param bot_object: """ self._proto = proto_data self._bot_object = bot_object # Used by property_immutable_cache self.cache = {} def __repr__(self) -> str: """ Returns string of this form: Unit(name='SCV', tag=4396941328). """ return f"Unit(name={self.name !r}, tag={self.tag})" @property_immutable_cache def type_id(self) -> UnitTypeId: """ UnitTypeId found in sc2/ids/unit_typeid. Caches all type_ids of the same unit type. """ unit_type = self._proto.unit_type if unit_type not in self._bot_object._game_data.unit_types: self._bot_object._game_data.unit_types[unit_type] = UnitTypeId(unit_type) return self._bot_object._game_data.unit_types[unit_type] @property_immutable_cache def _type_data(self) -> "UnitTypeData": """ Provides the unit type data. """ return self._bot_object._game_data.units[self._proto.unit_type] @property def name(self) -> str: """ Returns the name of the unit. """ return self._type_data.name @property def race(self) -> Race: """ Returns the race of the unit """ return Race(self._type_data._proto.race) @property def tag(self) -> int: """ Returns the unique tag of the unit. """ return self._proto.tag @property def is_structure(self) -> bool: """ Checks if the unit is a structure. """ return IS_STRUCTURE in self._type_data.attributes @property def is_light(self) -> bool: """ Checks if the unit has the 'light' attribute. """ return IS_LIGHT in self._type_data.attributes @property def is_armored(self) -> bool: """ Checks if the unit has the 'armored' attribute. """ return IS_ARMORED in self._type_data.attributes @property def is_biological(self) -> bool: """ Checks if the unit has the 'biological' attribute. """ return IS_BIOLOGICAL in self._type_data.attributes @property def is_mechanical(self) -> bool: """ Checks if the unit has the 'mechanical' attribute. """ return IS_MECHANICAL in self._type_data.attributes @property def is_massive(self) -> bool: """ Checks if the unit has the 'massive' attribute. """ return IS_MASSIVE in self._type_data.attributes @property def is_psionic(self) -> bool: """ Checks if the unit has the 'psionic' attribute. """ return IS_PSIONIC in self._type_data.attributes @property def tech_alias(self) -> Optional[List[UnitTypeId]]: """ Building tech equality, e.g. OrbitalCommand is the same as CommandCenter For Hive, this returns [UnitTypeId.Hatchery, UnitTypeId.Lair] For SCV, this returns None """ return self._type_data.tech_alias @property def unit_alias(self) -> Optional[UnitTypeId]: """ Building type equality, e.g. FlyingOrbitalCommand is the same as OrbitalCommand For flying OrbitalCommand, this returns UnitTypeId.OrbitalCommand For SCV, this returns None """ return self._type_data.unit_alias @property_immutable_cache def _weapons(self): """ Returns the weapons of the unit. """ try: return self._type_data._proto.weapons except: return None @property_immutable_cache def can_attack(self) -> bool: """ Checks if the unit can attack at all. """ # TODO BATTLECRUISER doesnt have weapons in proto?! return bool(self._weapons) or self.type_id in {UNIT_BATTLECRUISER, UNIT_ORACLE} @property_immutable_cache def can_attack_both(self) -> bool: """ Checks if the unit can attack both ground and air units. """ if self.type_id == UNIT_BATTLECRUISER: return True if self._weapons: return any(weapon.type in TARGET_BOTH for weapon in self._weapons) return False @property_immutable_cache def can_attack_ground(self) -> bool: """ Checks if the unit can attack ground units. """ if self.type_id in {UNIT_BATTLECRUISER, UNIT_ORACLE}: return True if self._weapons: return any(weapon.type in TARGET_GROUND for weapon in self._weapons) return False @property_immutable_cache def ground_dps(self) -> Union[int, float]: """ Returns the dps against ground units. Does not include upgrades. """ if self.can_attack_ground: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_GROUND), None) if weapon: return (weapon.damage * weapon.attacks) / weapon.speed return 0 @property_immutable_cache def ground_range(self) -> Union[int, float]: """ Returns the range against ground units. Does not include upgrades. """ if self.type_id == UNIT_ORACLE: return 4 if self.type_id == UNIT_BATTLECRUISER: return 6 if self.can_attack_ground: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_GROUND), None) if weapon: return weapon.range return 0 @property_immutable_cache def can_attack_air(self) -> bool: """ Checks if the unit can air attack at all. Does not include upgrades. """ if self.type_id == UNIT_BATTLECRUISER: return True if self._weapons: return any(weapon.type in TARGET_AIR for weapon in self._weapons) return False @property_immutable_cache def air_dps(self) -> Union[int, float]: """ Returns the dps against air units. Does not include upgrades. """ if self.can_attack_air: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_AIR), None) if weapon: return (weapon.damage * weapon.attacks) / weapon.speed return 0 @property_immutable_cache def air_range(self) -> Union[int, float]: """ Returns the range against air units. Does not include upgrades. """ if self.type_id == UNIT_BATTLECRUISER: return 6 if self.can_attack_air: weapon = next((weapon for weapon in self._weapons if weapon.type in TARGET_AIR), None) if weapon: return weapon.range return 0 @property_immutable_cache def bonus_damage(self): """ Returns a tuple of form '(bonus damage, armor type)' if unit does 'bonus damage' against 'armor type'. Possible armor typs are: 'Light', 'Armored', 'Biological', 'Mechanical', 'Psionic', 'Massive', 'Structure'. """ # TODO: Consider units with ability attacks (Oracle, Baneling) or multiple attacks (Thor). if self._weapons: for weapon in self._weapons: if weapon.damage_bonus: b = weapon.damage_bonus[0] return (b.bonus, Attribute(b.attribute).name) else: return None @property def armor(self) -> Union[int, float]: """ Returns the armor of the unit. Does not include upgrades """ return self._type_data._proto.armor @property def sight_range(self) -> Union[int, float]: """ Returns the sight range of the unit. """ return self._type_data._proto.sight_range @property def movement_speed(self) -> Union[int, float]: """ Returns the movement speed of the unit. Does not include upgrades or buffs. """ return self._type_data._proto.movement_speed @property def is_mineral_field(self) -> bool: """ Checks if the unit is a mineral field. """ return self._type_data.has_minerals @property def is_vespene_geyser(self) -> bool: """ Checks if the unit is a non-empty vespene geyser or gas extraction building. """ return self._type_data.has_vespene @property def health(self) -> Union[int, float]: """ Returns the health of the unit. Does not include shields. """ return self._proto.health @property def health_max(self) -> Union[int, float]: """ Returns the maximum health of the unit. Does not include shields. """ return self._proto.health_max @property def health_percentage(self) -> Union[int, float]: """ Returns the percentage of health the unit has. Does not include shields. """ if self._proto.health_max == 0: return 0 return self._proto.health / self._proto.health_max @property def shield(self) -> Union[int, float]: """ Returns the shield points the unit has. Returns 0 for non-protoss units. """ return self._proto.shield @property def shield_max(self) -> Union[int, float]: """ Returns the maximum shield points the unit can have. Returns 0 for non-protoss units. """ return self._proto.shield_max @property def shield_percentage(self) -> Union[int, float]: """ Returns the percentage of shield points the unit has. Returns 0 for non-protoss units. """ if self._proto.shield_max == 0: return 0 return self._proto.shield / self._proto.shield_max @property def energy(self) -> Union[int, float]: """ Returns the amount of energy the unit has. Returns 0 for units without energy. """ return self._proto.energy @property def energy_max(self) -> Union[int, float]: """ Returns the maximum amount of energy the unit can have. Returns 0 for units without energy. """ return self._proto.energy_max @property def energy_percentage(self) -> Union[int, float]: """ Returns the percentage of amount of energy the unit has. Returns 0 for units without energy. """ if self._proto.energy_max == 0: return 0 return self._proto.energy / self._proto.energy_max @property def is_snapshot(self) -> bool: """ Checks if the unit is only available as a snapshot for the bot. Enemy buildings that have been scouted and are in the fog of war or attacking enemy units on higher, not visible ground appear this way. """ return self._proto.display_type == IS_SNAPSHOT @property def is_visible(self) -> bool: """ Checks if the unit is visible for the bot. NOTE: This means the bot has vision of the position of the unit! It does not give any information about the cloak status of the unit.""" return self._proto.display_type == IS_VISIBLE @property def alliance(self) -> Alliance: """ Returns the team the unit belongs to. """ return self._proto.alliance @property def is_mine(self) -> bool: """ Checks if the unit is controlled by the bot. """ return self._proto.alliance == IS_MINE @property def is_enemy(self) -> bool: """ Checks if the unit is hostile. """ return self._proto.alliance == IS_ENEMY @property def owner_id(self) -> int: """ Returns the owner of the unit. This is a value of 1 or 2 in a two player game. """ return self._proto.owner @property def position_tuple(self) -> Tuple[float, float]: """ Returns the 2d position of the unit as tuple without conversion to Point2. """ return self._proto.pos.x, self._proto.pos.y @property_immutable_cache def position(self) -> Point2: """ Returns the 2d position of the unit. """ return Point2.from_proto(self._proto.pos) @property_immutable_cache def position3d(self) -> Point3: """ Returns the 3d position of the unit. """ return Point3.from_proto(self._proto.pos) def distance_to(self, p: Union[Unit, Point2, Point3]) -> Union[int, float]: """ Using the 2d distance between self and p. To calculate the 3d distance, use unit.position3d.distance_to(p) :param p: """ if isinstance(p, Unit): return self._bot_object._distance_squared_unit_to_unit(self, p) ** 0.5 return self._bot_object.distance_math_hypot(self.position_tuple, p) def target_in_range(self, target: Unit, bonus_distance: Union[int, float] = 0) -> bool: """ Checks if the target is in range. Includes the target's radius when calculating distance to target. :param target: :param bonus_distance: """ # TODO: Fix this because immovable units (sieged tank, planetary fortress etc.) have a little lower range than this formula if self.can_attack_ground and not target.is_flying: unit_attack_range = self.ground_range elif self.can_attack_air and (target.is_flying or target.type_id == UNIT_COLOSSUS): unit_attack_range = self.air_range else: return False return ( self._bot_object._distance_squared_unit_to_unit(self, target) <= (self.radius + target.radius + unit_attack_range + bonus_distance) ** 2 ) def in_ability_cast_range( self, ability_id: AbilityId, target: Union[Unit, Point2], bonus_distance: float = 0 ) -> bool: """ Test if a unit is able to cast an ability on the target without checking ability cooldown (like stalker blink) or if ability is made available through research (like HT storm). :param ability_id: :param target: :param bonus_distance: """ cast_range = self._bot_object._game_data.abilities[ability_id.value]._proto.cast_range assert cast_range > 0, f"Checking for an ability ({ability_id}) that has no cast range" ability_target_type = self._bot_object._game_data.abilities[ability_id.value]._proto.target # For casting abilities that target other units, like transfuse, feedback, snipe, yamato if ability_target_type in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit): return ( self._bot_object._distance_squared_unit_to_unit(self, target) <= (cast_range + self.radius + target.radius + bonus_distance) ** 2 ) # For casting abilities on the ground, like queen creep tumor, ravager bile, HT storm if ability_target_type in {Target.Point.value, Target.PointOrUnit.value} and isinstance( target, (Point2, tuple) ): return ( self._bot_object._distance_pos_to_pos(self.position_tuple, target) <= cast_range + self.radius + bonus_distance ) return False @property def facing(self) -> Union[int, float]: """ Returns direction the unit is facing as a float in range [0,2π). 0 is in direction of x axis.""" return self._proto.facing # TODO: a function that checks if this unit is facing another unit def is_facing_unit(self, other_unit: Unit, angle_error: float = 1e-3) -> bool: """ Function not completed yet :param other_unit: :param angle_error: """ pass @property def radius(self) -> Union[int, float]: """ Half of unit size. See https://liquipedia.net/starcraft2/Unit_Statistics_(Legacy_of_the_Void) """ return self._proto.radius @property def build_progress(self) -> Union[int, float]: """ Returns completion in range [0,1].""" return self._proto.build_progress @property def is_ready(self) -> bool: """ Checks if the unit is completed. """ return self.build_progress == 1 @property def cloak(self) -> CloakState: """ Returns cloak state. See https://github.com/Blizzard/s2client-api/blob/d9ba0a33d6ce9d233c2a4ee988360c188fbe9dbf/include/sc2api/sc2_unit.h#L95 """ return self._proto.cloak @property def is_cloaked(self) -> bool: """ Checks if the unit is cloaked. """ return self._proto.cloak in IS_CLOAKED @property def is_revealed(self) -> bool: """ Checks if the unit is revealed. """ return self._proto.cloak is IS_REVEALED @property def can_be_attacked(self) -> bool: """ Checks if the unit is revealed or not cloaked and therefore can be attacked. """ return self._proto.cloak in CAN_BE_ATTACKED @property_immutable_cache def buffs(self) -> Set: """ Returns the set of current buffs the unit has. """ return {BuffId(buff_id) for buff_id in self._proto.buff_ids} @property_immutable_cache def is_carrying_minerals(self) -> bool: """ Checks if a worker or MULE is carrying (gold-)minerals. """ return not IS_CARRYING_MINERALS.isdisjoint(self.buffs) @property_immutable_cache def is_carrying_vespene(self) -> bool: """ Checks if a worker is carrying vespene gas. """ return not IS_CARRYING_VESPENE.isdisjoint(self.buffs) @property_immutable_cache def is_carrying_resource(self) -> bool: """ Checks if a worker is carrying a resource. """ return not IS_CARRYING_RESOURCES.isdisjoint(self.buffs) @property def detect_range(self) -> Union[int, float]: """ Returns the detection distance of the unit. """ return self._proto.detect_range @property_immutable_cache def is_detector(self) -> bool: """ Checks if the unit is a detector. Has to be completed in order to detect and Photoncannons also need to be powered. """ return self.is_ready and (self.type_id in IS_DETECTOR or self.type_id == UNIT_PHOTONCANNON and self.is_powered) @property def radar_range(self) -> Union[int, float]: return self._proto.radar_range @property def is_selected(self) -> bool: """ Checks if the unit is currently selected. """ return self._proto.is_selected @property def is_on_screen(self) -> bool: """ Checks if the unit is on the screen. """ return self._proto.is_on_screen @property def is_blip(self) -> bool: """ Checks if the unit is detected by a sensor tower. """ return self._proto.is_blip @property def is_powered(self) -> bool: """ Checks if the unit is powered by a pylon or warppism. """ return self._proto.is_powered @property def is_active(self) -> bool: """ Checks if the unit is currently training or researching. """ return self._proto.is_active # PROPERTIES BELOW THIS COMMENT ARE NOT POPULATED FOR SNAPSHOTS @property def mineral_contents(self) -> int: """ Returns the amount of minerals remaining in a mineral field. """ return self._proto.mineral_contents @property def vespene_contents(self) -> int: """ Returns the amount of gas remaining in a geyser. """ return self._proto.vespene_contents @property def has_vespene(self) -> bool: """ Checks if a geyser has any gas remaining. You can't build extractors on empty geysers. """ return bool(self._proto.vespene_contents) @property def is_flying(self) -> bool: """ Checks if the unit is flying. """ return self._proto.is_flying or self.has_buff(BuffId.GRAVITONBEAM) @property def is_burrowed(self) -> bool: """ Checks if the unit is burrowed. """ return self._proto.is_burrowed @property def is_hallucination(self) -> bool: """ Returns True if the unit is your own hallucination or detected. """ return self._proto.is_hallucination @property def attack_upgrade_level(self) -> int: """ Returns the upgrade level of the units attack. # NOTE: Returns 0 for units without a weapon. """ return self._proto.attack_upgrade_level @property def armor_upgrade_level(self) -> int: """ Returns the upgrade level of the units armor. """ return self._proto.armor_upgrade_level @property def shield_upgrade_level(self) -> int: """ Returns the upgrade level of the units shield. # NOTE: Returns 0 for units without a shield. """ return self._proto.shield_upgrade_level @property def buff_duration_remain(self) -> int: """ Returns the amount of remaining frames of the visible timer bar. # NOTE: Returns 0 for units without a timer bar. """ return self._proto.buff_duration_remain @property def buff_duration_max(self) -> int: """ Returns the maximum amount of frames of the visible timer bar. # NOTE: Returns 0 for units without a timer bar. """ return self._proto.buff_duration_max # PROPERTIES BELOW THIS COMMENT ARE NOT POPULATED FOR ENEMIES @property_mutable_cache def orders(self) -> List[UnitOrder]: """ Returns the a list of the current orders. """ return [UnitOrder.from_proto(order, self._bot_object) for order in self._proto.orders] @property_immutable_cache def order_target(self) -> Optional[Union[int, Point2]]: """ Returns the target tag (if it is a Unit) or Point2 (if it is a Position) from the first order, returns None if the unit is idle """ if self.orders: if isinstance(self.orders[0].target, int): return self.orders[0].target else: return Point2.from_proto(self.orders[0].target) return None @property def noqueue(self) -> bool: """ Checks if the unit is idle. """ warnings.warn("noqueue will be removed soon, please use is_idle instead", DeprecationWarning, stacklevel=2) return self.is_idle @property def is_idle(self) -> bool: """ Checks if unit is idle. """ return not self._proto.orders def is_using_ability(self, abilities: Union[AbilityId, Set[AbilityId]]) -> bool: """ Check if the unit is using one of the given abilities. Only works for own units. """ if not self.orders: return False if isinstance(abilities, AbilityId): abilities = {abilities} return self.orders[0].ability.id in abilities @property_immutable_cache def is_moving(self) -> bool: """ Checks if the unit is moving. Only works for own units. """ return self.is_using_ability(AbilityId.MOVE) @property_immutable_cache def is_attacking(self) -> bool: """ Checks if the unit is attacking. Only works for own units. """ return self.is_using_ability(IS_ATTACKING) @property_immutable_cache def is_patrolling(self) -> bool: """ Checks if a unit is patrolling. Only works for own units. """ return self.is_using_ability(IS_PATROLLING) @property_immutable_cache def is_gathering(self) -> bool: """ Checks if a unit is on its way to a mineral field or vespene geyser to mine. Only works for own units. """ return self.is_using_ability(IS_GATHERING) @property_immutable_cache def is_returning(self) -> bool: """ Checks if a unit is returning from mineral field or vespene geyser to deliver resources to townhall. Only works for own units. """ return self.is_using_ability(IS_RETURNING) @property_immutable_cache def is_collecting(self) -> bool: """ Checks if a unit is gathering or returning. Only works for own units. """ return self.is_using_ability(IS_COLLECTING) @property_immutable_cache def is_constructing_scv(self) -> bool: """ Checks if the unit is an SCV that is currently building. Only works for own units. """ return self.is_using_ability(IS_CONSTRUCTING_SCV) @property_immutable_cache def is_transforming(self) -> bool: """ Checks if the unit transforming. Only works for own units. """ return self.type_id in transforming and self.is_using_ability(transforming[self.type_id]) @property_immutable_cache def is_repairing(self) -> bool: """ Checks if the unit is an SCV or MULE that is currently repairing. Only works for own units. """ return self.is_using_ability(IS_REPAIRING) @property def add_on_tag(self) -> int: """ Returns the tag of the addon of unit. """ return self._proto.add_on_tag @property def has_add_on(self) -> bool: """ Checks if unit has an addon attached. """ return bool(self._proto.add_on_tag) @property_immutable_cache def add_on_land_position(self) -> Point2: """ If unit is addon (techlab or reactor), returns the position where a terran building has to land to connect to addon """ return self.position.offset(Point2((-2.5, 0.5))) @property_mutable_cache def passengers(self) -> Set[Unit]: """ Returns the units inside a Bunker, CommandCenter, PlanetaryFortress, Medivac, Nydus, Overlord or WarpPrism. """ return {Unit(unit, self._bot_object) for unit in self._proto.passengers} @property_mutable_cache def passengers_tags(self) -> Set[int]: """ Returns the tags of the units inside a Bunker, CommandCenter, PlanetaryFortress, Medivac, Nydus, Overlord or WarpPrism. """ return {unit.tag for unit in self._proto.passengers} @property def cargo_used(self) -> Union[float, int]: """ Returns how much cargo space is currently used in the unit. Note that some units take up more than one space. """ return self._proto.cargo_space_taken @property def has_cargo(self) -> bool: """ Checks if this unit has any units loaded. """ return bool(self._proto.cargo_space_taken) @property def cargo_size(self) -> Union[float, int]: """ Returns the amount of cargo space the unit needs. """ return self._type_data.cargo_size @property def cargo_max(self) -> Union[float, int]: """ How much cargo space is available at maximum. """ return self._proto.cargo_space_max @property def cargo_left(self) -> Union[float, int]: """ Returns how much cargo space is currently left in the unit. """ return self._proto.cargo_space_max - self._proto.cargo_space_taken @property def assigned_harvesters(self) -> int: """ Returns the number of workers currently gathering resources at a geyser or mining base.""" return self._proto.assigned_harvesters @property def ideal_harvesters(self) -> int: """ Returns the ideal harverster count for unit. 3 for gas buildings, 2*n for n mineral patches on that base.""" return self._proto.ideal_harvesters @property def surplus_harvesters(self) -> int: """ Returns a positive int if unit has too many harvesters mining, a negative int if it has too few mining.""" return self._proto.assigned_harvesters - self._proto.ideal_harvesters @property_immutable_cache def weapon_cooldown(self) -> Union[int, float]: """ Returns the time until the unit can fire again, returns -1 for units that can't attack. Usage: if unit.weapon_cooldown == 0: self.actions.append(unit.attack(target)) elif unit.weapon_cooldown < 0: self.actions.append(unit.move(closest_allied_unit_because_cant_attack)) else: self.actions.append(unit.move(retreatPosition)) """ if self.can_attack: return self._proto.weapon_cooldown return -1 @property def engaged_target_tag(self) -> int: # TODO What does this do? return self._proto.engaged_target_tag # Unit functions def has_buff(self, buff: BuffId) -> bool: """ Checks if unit has buff 'buff'. """ assert isinstance(buff, BuffId), f"{buff} is no BuffId" return buff in self.buffs def train(self, unit: UnitTypeId, queue: bool = False) -> UnitCommand: """ Orders unit to train another 'unit'. Usage: self.actions.append(COMMANDCENTER.train(SCV)) :param unit: :param queue: """ return self(self._bot_object._game_data.units[unit.value].creation_ability.id, queue=queue) def build(self, unit: UnitTypeId, position: Union[Point2, Point3] = None, queue: bool = False) -> UnitCommand: """ Orders unit to build another 'unit' at 'position'. Usage: self.actions.append(SCV.build(COMMANDCENTER, position)) :param unit: :param position: :param queue: """ return self(self._bot_object._game_data.units[unit.value].creation_ability.id, target=position, queue=queue) def research(self, upgrade: UpgradeId, queue: bool = False) -> UnitCommand: """ Orders unit to research 'upgrade'. Requires UpgradeId to be passed instead of AbilityId. :param upgrade: :param queue: """ return self(self._bot_object._game_data.upgrades[upgrade.value].research_ability.id, queue=queue) def warp_in(self, unit: UnitTypeId, position: Union[Point2, Point3]) -> UnitCommand: """ Orders Warpgate to warp in 'unit' at 'position'. :param unit: :param queue: """ normal_creation_ability = self._bot_object._game_data.units[unit.value].creation_ability.id return self(warpgate_abilities[normal_creation_ability], target=position) def attack(self, target: Union[Unit, Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders unit to attack. Target can be a Unit or Point2. Attacking a position will make the unit move there and attack everything on its way. :param target: :param queue: """ return self(AbilityId.ATTACK, target=target, queue=queue) def gather(self, target: Unit, queue: bool = False) -> UnitCommand: """ Orders a unit to gather minerals or gas. 'Target' must be a mineral patch or a gas extraction building. :param target: :param queue: """ return self(AbilityId.HARVEST_GATHER, target=target, queue=queue) def return_resource(self, target: Unit = None, queue: bool = False) -> UnitCommand: """ Orders the unit to return resource. Does not need a 'target'. :param target: :param queue: """ return self(AbilityId.HARVEST_RETURN, target=target, queue=queue) def move(self, position: Union[Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders the unit to move to 'position'. Target can be a Unit (to follow that unit) or Point2. :param position: :param queue: """ return self(AbilityId.MOVE_MOVE, target=position, queue=queue) def scan_move(self, *args, **kwargs) -> UnitCommand: """ Deprecated: This ability redirects to 'AbilityId.ATTACK' """ return self(AbilityId.SCAN_MOVE, *args, **kwargs) def hold_position(self, queue: bool = False) -> UnitCommand: """ Orders a unit to stop moving. It will not move until it gets new orders. :param queue: """ return self(AbilityId.HOLDPOSITION, queue=queue) def stop(self, queue: bool = False) -> UnitCommand: """ Orders a unit to stop, but can start to move on its own if it is attacked, enemy unit is in range or other friendly units need the space. :param queue: """ return self(AbilityId.STOP, queue=queue) def patrol(self, position: Union[Point2, Point3], queue: bool = False) -> UnitCommand: """ Orders a unit to patrol between position it has when the command starts and the target position. Can be queued up to seven patrol points. If the last point is the same as the starting point, the unit will patrol in a circle. :param position: :param queue: """ return self(AbilityId.PATROL, target=position, queue=queue) def repair(self, repair_target: Unit, queue: bool = False) -> UnitCommand: """ Order an SCV or MULE to repair. :param repair_target: :param queue: """ return self(AbilityId.EFFECT_REPAIR, target=repair_target, queue=queue) def __hash__(self): return self.tag def __eq__(self, other): try: return self.tag == other.tag except: return False def __call__(self, ability, target=None, queue: bool = False): return UnitCommand(ability, self, target=target, queue=queue)
37.37069
188
0.647953
33,371
0.962227
0
0
23,357
0.673481
0
0
12,636
0.364349
bc73bb29476960582e88da68ad24bf687cb2dd0e
65
py
Python
healthy_candies/load/__init__.py
striantafyllouEPFL/healthy-candies
fc7d9e05d54ba207e15d997acea44ff0bf9edb13
[ "BSD-2-Clause" ]
1
2018-11-04T21:46:29.000Z
2018-11-04T21:46:29.000Z
healthy_candies/load/__init__.py
striantafyllouEPFL/healthy-candies
fc7d9e05d54ba207e15d997acea44ff0bf9edb13
[ "BSD-2-Clause" ]
null
null
null
healthy_candies/load/__init__.py
striantafyllouEPFL/healthy-candies
fc7d9e05d54ba207e15d997acea44ff0bf9edb13
[ "BSD-2-Clause" ]
null
null
null
from .load import load_data, NUTRI_COLS, load_clean_rel_to_nutri
32.5
64
0.861538
0
0
0
0
0
0
0
0
0
0
bc74af5f799cda766e2f5e64ed34c0e410d241a2
1,402
py
Python
simglucose/sensor/cgm.py
mia-jingyi/simglucose
a90bd8750fce362be91668ed839b3b252bc0d58d
[ "MIT" ]
null
null
null
simglucose/sensor/cgm.py
mia-jingyi/simglucose
a90bd8750fce362be91668ed839b3b252bc0d58d
[ "MIT" ]
null
null
null
simglucose/sensor/cgm.py
mia-jingyi/simglucose
a90bd8750fce362be91668ed839b3b252bc0d58d
[ "MIT" ]
null
null
null
# from .noise_gen import CGMNoiseGenerator from .noise_gen import CGMNoise import pandas as pd import logging logger = logging.getLogger(__name__) class CGMSensor(object): def __init__(self, params, seed=None): self._params = params self.name = params.Name self.sample_time = params.sample_time self.seed = seed self._last_CGM = 0 @classmethod def withName(cls, name, sensor_para_file, **kwargs): sensor_params = pd.read_csv(sensor_para_file) params = sensor_params.loc[sensor_params.Name == name].squeeze() return cls(params, **kwargs) def measure(self, patient): if patient.t % self.sample_time == 0: BG = patient.observation.Gsub CGM = BG + next(self._noise_generator) CGM = max(CGM, self._params["min"]) CGM = min(CGM, self._params["max"]) self._last_CGM = CGM return CGM # Zero-Order Hold return self._last_CGM @property def seed(self): return self._seed @seed.setter def seed(self, seed): self._seed = seed self._noise_generator = CGMNoise(self._params, seed=seed) def reset(self): logger.debug('Resetting CGM sensor ...') self._noise_generator = CGMNoise(self._params, seed=self.seed) self._last_CGM = 0 if __name__ == '__main__': pass
26.961538
72
0.624108
1,213
0.865193
0
0
418
0.298146
0
0
105
0.074893
bc7580cf9a167be668d4a125b31c0b817e88571f
5,731
py
Python
var/spack/repos/builtin/packages/thepeg/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2020-10-20T08:57:12.000Z
2020-10-20T08:57:12.000Z
var/spack/repos/builtin/packages/thepeg/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2022-03-09T09:15:39.000Z
2022-03-09T09:15:42.000Z
var/spack/repos/builtin/packages/thepeg/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2021-01-05T20:00:52.000Z
2021-01-05T20:00:52.000Z
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Thepeg(AutotoolsPackage): """Toolkit for High Energy Physics Event Generation""" homepage = "http://home.thep.lu.se/~leif/ThePEG/" url = "https://thepeg.hepforge.org/downloads/?f=ThePEG-2.2.1.tar.bz2" # The commented out versions exist, but may need patches # and/or recipe changes version('2.2.1', sha256='63abc7215e6ad45c11cf9dac013738e194cc38556a8368b850b70ab1b57ea58f') version('2.2.0', sha256='d3e1474811b7d9f61a4a98db1e9d60d8ef8f913a50de4cae4dc2cc4f98e6fbf8') # version('2.1.7', sha256='2e15727afc1fbfb158fa42ded31c4b1e5b51c25ed6bb66a38233e1fc594329c8') version('2.1.6', sha256='c1e51f83716bfca815b55100fbab3805ef5f9b9215e4373b22762693f5353f4f') version('2.1.5', sha256='c61a00fb6cf406f0f98e8c934683d8d5efcb655747842113abc92e9526e4b5e6') # version('2.1.4', sha256='400c37319aa967ed993fdbec84fc65b24f6cb3779fb1b173d7f5d7a56b772df5') version('2.1.3', sha256='16e8f6507530c2b80ed873ad22946efefed7355d15c7026f3465f18acebc1c0c') # version('2.1.2', sha256='6a0f675a27e10863d495de069f25b892e532beb32e9cbfe5a58317d015387f49') version('2.1.1', sha256='e1b0bdc116fbc9a6e598b601f2aa670530cf2e1cd46b4572814a9b0130b10281') # version('2.1.0', sha256='fe6e7740ce3cd4a3ce3d7a0079a16c9214ad18f432e29d034ae763bfc40f3d39') # version('2.0.4', sha256='f3b625b411667e2708995f1d1379b5b8691406853c8c2cca2f4e4e6e062da0e4') # version('2.0.3', sha256='c57ba68fbfda06a0ba256e06f276f91434bf2529a13f6287c051a4cd6da44634') # version('2.0.2', sha256='d4249e019543d5c7520733292d2edfb0bdd9733177200a63837781ed6194789b') # version('2.0.1', sha256='ec284abdc82ceaf10a8736f908e7955f49f872b79aaa62d22aa33bc5c7679bdb') # version('2.0.0', sha256='571730cc956027dc82780dc04ef6e7382ab5ea853fcfebe259e488c6df302a04') version('1.9.2', sha256='ff7bbb256866f994dae04ade1f57c92d2670edaac3df11c9a300419a5343faf4') # version('1.9.1', sha256='8ec6d0669eba51e308be4e33aeb219999418170eae3aad93ec1491c942c2a4e9') version('1.9.0', sha256='3ee58e5e3a26184567df1b9a10ca70df228e86f322e72f018dd7d8d5a4700a5d') version('1.8.3', sha256='55ede3a3dd0bd07b90d0d49cf7ae28c18cd965780fdf53528508b97d57152fc7') # version('1.8.2', sha256='44ccd0d70e42bb6ecd801a51bade6c25b3953c56f33017402d4f52ee6492dffa') # version('1.8.1', sha256='84c2a212a681545cddd541dca191eb65d96f41df86c87480b6f4f7d4f9683562') # version('1.8.0', sha256='4b22fda1078f410b999a23a17f611c9ae3a7f0f4cee4e83dc82c9336b7adf037') # version('1.7.3', sha256='066d5df74118d6e984bb60e1c0bea08a8edcbcf917d83d8bc32ec6fea0726187') # version('1.7.2', sha256='3b885c6c5a39b7399ccd45d1f5a866b7a65c96174a56a7ff4ae423347843d013') # version('1.7.1', sha256='13434dc7a8623cacb94c0b5c8d7e15b4c5d5187fe9322d1afc1c91b2c940102e') # version('1.7.0', sha256='40eb7196139a8bf4c35f5bb69818135943d534457df64aeb1cf60b6621435312') # version('1.6.1', sha256='5bc074b78f8b663a6a33df9c94dcaa3100269f8da59f9553a565298e55af270f') # version('1.6.0', sha256='c0ac06b70f3e8046fce4e49ba5916c9b49450f528d0e25f8f7f1427c62fec680') # version('1.5.0', sha256='ccbf102cf1d350a21487518d12e7e03e6e50010e5604f0201f256fa46a7a50c2') # version('1.4.2', sha256='40444304e40e07fd417a8ebf8e5c1cf07e895ceac52ef4f7c1eecc911f6f775c') # version('1.4.1', sha256='156d06fd1ce68466d1f2adb9cc13f412b8b87073ec6a1d02102b173c34c29b8a') # version('1.4.0', sha256='b1f55e9a3bec713e9abf2fe71c5bd8cf8df936ea00b09f96df9123d0d5ab233f') # version('1.3.0', sha256='f731ebf3ce5a52b6d750d6e3c282fdc74d8ffd78bccb47b68f10a4daf44c7045') patch('thepeg-1.8.3.patch', when='@1.8.3', level=0) patch('thepeg-1.9.0.patch', when='@1.9.0', level=0) patch('thepeg-1.9.2.patch', when='@1.9.2', level=0) patch('thepeg-2.1.1.patch', when='@2.1.1:2.2.1', level=0) depends_on('gsl') depends_on('lhapdf') depends_on('lhapdf@:6.2.999', when='@:1.9.999') depends_on('hepmc', when='hepmc=2') depends_on('hepmc3', when='hepmc=3') conflicts('hepmc=3', when='@:2.1.999', msg='HepMC3 support was added in 2.2.0') depends_on('fastjet', when='@2.0.0:') depends_on('rivet', when='@2.0.3:') depends_on('boost', when='@2.1.1:') depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') variant('hepmc', default='2', values=('2', '3'), description='HepMC interface to build ') install_targets = ['install-strip'] def configure_args(self): args = ['--with-gsl=' + self.spec['gsl'].prefix, '--without-javagui'] if self.spec.satisfies('@:1.8.999'): args += ['--with-LHAPDF=' + self.spec['lhapdf'].prefix] else: args += ['--with-lhapdf=' + self.spec['lhapdf'].prefix] if self.spec.satisfies('hepmc=2'): args += ['--with-hepmc=' + self.spec['hepmc'].prefix] else: args += ['--with-hepmc=' + self.spec['hepmc3'].prefix] if self.spec.satisfies('@2.2.0:'): args += ['--with-hepmcversion=' + self.spec.variants['hepmc'].value] if self.spec.satisfies('@2.0.0:'): args += ['--with-fastjet=' + self.spec['fastjet'].prefix] if self.spec.satisfies('@2.0.3:'): args += ['--with-rivet=' + self.spec['rivet'].prefix] if self.spec.satisfies('@:2.1.999'): args += ['--with-boost=' + self.spec['boost'].prefix] args += ['CFLAGS=-O2', 'CXXFLAGS=-O2', 'FFLAGS=-O2'] return args
55.105769
97
0.716105
5,510
0.961438
0
0
0
0
0
0
4,057
0.707904
bc7679c1660ef9ceb329970fcb693da9107e9ae5
9,258
py
Python
vmca/python/get_cert.py
wfu8/lightwave
cf6a7417cd9807bfcf9bcd99c43c5b2eecf2d298
[ "Apache-2.0" ]
357
2015-04-20T00:16:30.000Z
2022-03-17T05:34:09.000Z
vmca/python/get_cert.py
wfu8/lightwave
cf6a7417cd9807bfcf9bcd99c43c5b2eecf2d298
[ "Apache-2.0" ]
38
2015-11-19T05:20:53.000Z
2022-03-31T07:21:59.000Z
vmca/python/get_cert.py
wfu8/lightwave
cf6a7417cd9807bfcf9bcd99c43c5b2eecf2d298
[ "Apache-2.0" ]
135
2015-04-21T15:23:21.000Z
2022-03-30T11:46:36.000Z
#!/usr/bin/env python # # Copyright © 2012-2016 VMware, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the “License”); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an “AS IS” BASIS, without # warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the # License for the specific language governing permissions and limitations # under the License. # # Helper function that gets certificates from VMWare Certificate Authority # More details. If this module can be used as a main program, include usage information. """ certool.py : This is the standard library function for cloudVM/vcenterwindows first boot to integrate with VMCA Certificate Generation. if not running under a cloudVM, then it is assumed that the OS.Environment has the following defined. VMWARE_SKIP_VISL = True system.urlhostname vmdir.ldu-guid system.hostname.type vmca.cert.password vmca.cert.dir """ __copyright__ = "Copyright 2012, VMware Inc." __version__ = 0.1 __author__ = "VMware, Inc." import logging import os import subprocess class CerTool: __vislInstall__ = "" __systemUrlHostname__ = "" __systemHosttype__ = "" __vmcaPassword__ = "" __vmcaCertPath__ = "" __skipInstallParams__ = False __certfileName__ = "" __privateKeyFileName__ = "" __publicKeyFileName__ = "" __pfxFileName__ = "" def __init__(self): self.FindEnvParams() self.GetVislParams() def GetHostName(self): return self.__systemUrlHostname__ def GetHostType(self): return self.__systemHosttype__ def GetPassword(self): return self.__vmcaPassword__ def GetCertDir(self): return self.__vmcaCertPath__ def GetCertFileName(self): return self.__certfileName__ def GetPrivateKeyFileName(self): return self.__privateKeyFile__ def GetPublicKeyFileName(self): return self.__publicKeyFile__ def GetPfxFileName(self): return self.__pfxFileName__ def GenCert(self, componentName): """ Generates the Certificates in the Cert directory""" # Generate full file names for all artifacts self.__certfileName__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".crt") logging.debug("cert File Name : " + self.GetCertFileName()) self.__privateKeyFile__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".priv") logging.debug("Private Key Name : " + self.GetPrivateKeyFileName()) self.__publicKeyFile__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".pub") logging.debug("Public Key Name : " + self.GetPublicKeyFileName()) self.__pfxFileName__ = \ os.path.join(self.GetCertDir(), componentName, componentName + ".pfx") logging.debug("pfx file Name : " + self.GetPfxFileName()) dir = os.path.join(self.GetCertDir(),componentName) logging.debug("Target Dir : " + dir) try: if not os.path.exists(dir): os.makedirs(dir) logging.debug("Created directory") except OSError as e: raise Exception("I/O error({0}): {1}".format(e.errno, e.strerror)) # Generate Private Key and Public Keys First cmd = [self.GetCertToolPath(), '--genkey', '--priv=' + self.GetPrivateKeyFileName(), '--pub=' + self.GetPublicKeyFileName()] output = self.RunCmd(cmd) logging.info(output) cmd = [self.GetCertToolPath(), '--genCIScert', '--priv=' + self.GetPrivateKeyFileName(), '--cert=' + self.GetCertFileName(), '--Name=' + componentName] # if we know the host name, put that into the certificate if (self.GetHostType() == 'fqdn'): cmd.append('--FQDN=' + self.GetHostName()) # elif (self.GetHostType() == 'ipv4'): # # Possible TODO : support IPv4 in certificates # elif (self.GetHostType() == 'ipv6'): # # Possible TODO : support IPv6 in certificates output = self.RunCmd(cmd) logging.info(output) # TODO : Replace this with certool PKCS12 capabilities cmd = [self.GetOpenSSLPath(), 'pkcs12', '-export', '-in', self.GetCertFileName(), '-inkey', self.GetPrivateKeyFileName(), '-out', self.GetPfxFileName(), '-name', componentName, '-passout', 'pass:' + self.GetPassword()] output = self.RunCmd(cmd) logging.info(output) def FindEnvParams(self): """ Finds the Default Environment parameters. if you are not running inside the cloudVM, set VMWARE_SKIP_VISL = True in your environment. This will enable this script to look for values in the env. block instead of VISL namespace.""" # Find VISL Install Parameter INSTALL_PARAM_ENV_VAR = 'VMWARE_INSTALL_PARAMETER' VMWARE_SKIP_VISL = 'VMWARE_SKIP_VISL' if INSTALL_PARAM_ENV_VAR in os.environ: self.__vislInstall__ = os.environ[INSTALL_PARAM_ENV_VAR] if VMWARE_SKIP_VISL in os.environ: skip = os.environ[VMWARE_SKIP_VISL] if (skip in ['true', 'True', 'yes', '1', 'skip']): self.__skipInstallParams__ = True if (not self.__vislInstall__ and self.__skipInstallParams__ is False): errString = 'Unable to find install param script' logging.error(errString) raise Exception(errString) logging.debug('Using install param script : ' + self.__vislInstall__) def GetInstallParams(self, key): """ Waits on Install Parameter to return the value from visl. Or if the VMWARE_SKIP_VISL = True, then reads the value from the os environment""" if (self.__skipInstallParams__ is False): cmd = [self.__vislInstall__, '-d', key] output = self.RunCmd(cmd) logging.debug('Install param found :' + output) return output else: if val in os.environ: param = os.environ[key] logging.debug('Env. param found : ' + param) return param else: raise Exception('Requested Value not found in Env : ' + key) def RunCmd(self, args): """ Runs a given command""" logging.info('running %s' % args) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if p.returncode: raise Exception('Failed to execute last cmd') else: return p.communicate()[0].rstrip() def GetVislParams(self): """ Waits for all VISL parameters that VMCA certool needs""" INSTALL_PARAM_SYSTEM_URL_HOSTNAME = "system.urlhostname" INSTALL_PARAM_LDU_GUID = "vmdir.ldu-guid" INSTALL_PARAM_SYSTEM_HOST_TYPE = "system.hostname.type" INSTALL_PARAM_PASSWORD = "vmca.cert.password" INSTALL_PARAM_CERT_DIR = "vmca.cert.dir" # Please note that each of this is a blocking call. # VISL will wait until these value are populated by the # appropriate Script self.__systemUrlHostname__ = \ self.GetInstallParams(INSTALL_PARAM_SYSTEM_URL_HOSTNAME) self.__systemHosttype__ = \ self.GetInstallParams(INSTALL_PARAM_SYSTEM_HOST_TYPE) self.__vmcaPassword__ = \ self.GetInstallParams(INSTALL_PARAM_PASSWORD) self.__vmcaCertPath__ = \ self.GetInstallParams(INSTALL_PARAM_CERT_DIR) # We really don't need this value, # it is a technique on waiting for directory # first boot to finish. discardldu = self.GetInstallParams(INSTALL_PARAM_LDU_GUID) def GetCertToolPath(self): """returns the path to certool""" #TODO : Publish Certool Path from VMCA First Boot if(os.name == "nt"): PROGRAM_FILES = os.environ['PROGRAMFILES'] return os.path.normpath(PROGRAM_FILES + '/VMware/CIS/Vmcad/certool.exe') elif (os.name == 'posix'): return '/opt/vmware/bin/certool' def GetOpenSSLPath(self): if(os.name == "nt"): PROGRAM_FILES = os.environ['PROGRAMFILES'] return os.path.normpath(PROGRAM_FILES + '/VMware/CIS/OpenSSL/openssl.exe') elif (os.name == 'posix'): return '/usr/lib/vmware-openSSL/openssl' def main(): """ Example Code Usage """ testComponent = 'sso' VmcaCertool = CerTool() VmcaCertool.GenCert(testComponent) print 'Generated a pfx file : %s' % VmcaCertool.GetPfxFileName() print 'Using Password : %s' % VmcaCertool.GetPassword() if __name__ == "__main__": main()
34.935849
89
0.625081
7,613
0.821517
0
0
0
0
0
0
3,442
0.371425
bc783a7352b8476e222dafa470f894420847e079
22,670
py
Python
sdk/python/pulumi_gcp/securitycenter/notification_config.py
sisisin/pulumi-gcp
af6681d70ea457843409110c1324817fe55f68ad
[ "ECL-2.0", "Apache-2.0" ]
121
2018-06-18T19:16:42.000Z
2022-03-31T06:06:48.000Z
sdk/python/pulumi_gcp/securitycenter/notification_config.py
sisisin/pulumi-gcp
af6681d70ea457843409110c1324817fe55f68ad
[ "ECL-2.0", "Apache-2.0" ]
492
2018-06-22T19:41:03.000Z
2022-03-31T15:33:53.000Z
sdk/python/pulumi_gcp/securitycenter/notification_config.py
sisisin/pulumi-gcp
af6681d70ea457843409110c1324817fe55f68ad
[ "ECL-2.0", "Apache-2.0" ]
43
2018-06-19T01:43:13.000Z
2022-03-23T22:43:37.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['NotificationConfigArgs', 'NotificationConfig'] @pulumi.input_type class NotificationConfigArgs: def __init__(__self__, *, config_id: pulumi.Input[str], organization: pulumi.Input[str], pubsub_topic: pulumi.Input[str], streaming_config: pulumi.Input['NotificationConfigStreamingConfigArgs'], description: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a NotificationConfig resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input['NotificationConfigStreamingConfigArgs'] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). """ pulumi.set(__self__, "config_id", config_id) pulumi.set(__self__, "organization", organization) pulumi.set(__self__, "pubsub_topic", pubsub_topic) pulumi.set(__self__, "streaming_config", streaming_config) if description is not None: pulumi.set(__self__, "description", description) @property @pulumi.getter(name="configId") def config_id(self) -> pulumi.Input[str]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @config_id.setter def config_id(self, value: pulumi.Input[str]): pulumi.set(self, "config_id", value) @property @pulumi.getter def organization(self) -> pulumi.Input[str]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @organization.setter def organization(self, value: pulumi.Input[str]): pulumi.set(self, "organization", value) @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> pulumi.Input[str]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @pubsub_topic.setter def pubsub_topic(self, value: pulumi.Input[str]): pulumi.set(self, "pubsub_topic", value) @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> pulumi.Input['NotificationConfigStreamingConfigArgs']: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config") @streaming_config.setter def streaming_config(self, value: pulumi.Input['NotificationConfigStreamingConfigArgs']): pulumi.set(self, "streaming_config", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @pulumi.input_type class _NotificationConfigState: def __init__(__self__, *, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, service_account: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']] = None): """ Input properties used for looking up and filtering NotificationConfig resources. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] name: The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[str] service_account: The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. :param pulumi.Input['NotificationConfigStreamingConfigArgs'] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ if config_id is not None: pulumi.set(__self__, "config_id", config_id) if description is not None: pulumi.set(__self__, "description", description) if name is not None: pulumi.set(__self__, "name", name) if organization is not None: pulumi.set(__self__, "organization", organization) if pubsub_topic is not None: pulumi.set(__self__, "pubsub_topic", pubsub_topic) if service_account is not None: pulumi.set(__self__, "service_account", service_account) if streaming_config is not None: pulumi.set(__self__, "streaming_config", streaming_config) @property @pulumi.getter(name="configId") def config_id(self) -> Optional[pulumi.Input[str]]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @config_id.setter def config_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "config_id", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def organization(self) -> Optional[pulumi.Input[str]]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @organization.setter def organization(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "organization", value) @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> Optional[pulumi.Input[str]]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @pubsub_topic.setter def pubsub_topic(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "pubsub_topic", value) @property @pulumi.getter(name="serviceAccount") def service_account(self) -> Optional[pulumi.Input[str]]: """ The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. """ return pulumi.get(self, "service_account") @service_account.setter def service_account(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "service_account", value) @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']]: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config") @streaming_config.setter def streaming_config(self, value: Optional[pulumi.Input['NotificationConfigStreamingConfigArgs']]): pulumi.set(self, "streaming_config", value) class NotificationConfig(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None, __props__=None): """ A Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC resource that contains the configuration to send notifications for create/update events of findings, assets and etc. > **Note:** In order to use Cloud SCC resources, your organization must be enrolled in [SCC Standard/Premium](https://cloud.google.com/security-command-center/docs/quickstart-security-command-center). Without doing so, you may run into errors during resource creation. To get more information about NotificationConfig, see: * [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/organizations.notificationConfigs) * How-to Guides * [Official Documentation](https://cloud.google.com/security-command-center/docs) ## Example Usage ### Scc Notification Config Basic ```python import pulumi import pulumi_gcp as gcp scc_notification = gcp.pubsub.Topic("sccNotification") custom_notification_config = gcp.securitycenter.NotificationConfig("customNotificationConfig", config_id="my-config", organization="123456789", description="My custom Cloud Security Command Center Finding Notification Configuration", pubsub_topic=scc_notification.id, streaming_config=gcp.securitycenter.NotificationConfigStreamingConfigArgs( filter="category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"", )) ``` ## Import NotificationConfig can be imported using any of these accepted formats ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default organizations/{{organization}}/notificationConfigs/{{name}} ``` ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default {{organization}}/{{name}} ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ ... @overload def __init__(__self__, resource_name: str, args: NotificationConfigArgs, opts: Optional[pulumi.ResourceOptions] = None): """ A Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC resource that contains the configuration to send notifications for create/update events of findings, assets and etc. > **Note:** In order to use Cloud SCC resources, your organization must be enrolled in [SCC Standard/Premium](https://cloud.google.com/security-command-center/docs/quickstart-security-command-center). Without doing so, you may run into errors during resource creation. To get more information about NotificationConfig, see: * [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/organizations.notificationConfigs) * How-to Guides * [Official Documentation](https://cloud.google.com/security-command-center/docs) ## Example Usage ### Scc Notification Config Basic ```python import pulumi import pulumi_gcp as gcp scc_notification = gcp.pubsub.Topic("sccNotification") custom_notification_config = gcp.securitycenter.NotificationConfig("customNotificationConfig", config_id="my-config", organization="123456789", description="My custom Cloud Security Command Center Finding Notification Configuration", pubsub_topic=scc_notification.id, streaming_config=gcp.securitycenter.NotificationConfigStreamingConfigArgs( filter="category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"", )) ``` ## Import NotificationConfig can be imported using any of these accepted formats ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default organizations/{{organization}}/notificationConfigs/{{name}} ``` ```sh $ pulumi import gcp:securitycenter/notificationConfig:NotificationConfig default {{organization}}/{{name}} ``` :param str resource_name: The name of the resource. :param NotificationConfigArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(NotificationConfigArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = NotificationConfigArgs.__new__(NotificationConfigArgs) if config_id is None and not opts.urn: raise TypeError("Missing required property 'config_id'") __props__.__dict__["config_id"] = config_id __props__.__dict__["description"] = description if organization is None and not opts.urn: raise TypeError("Missing required property 'organization'") __props__.__dict__["organization"] = organization if pubsub_topic is None and not opts.urn: raise TypeError("Missing required property 'pubsub_topic'") __props__.__dict__["pubsub_topic"] = pubsub_topic if streaming_config is None and not opts.urn: raise TypeError("Missing required property 'streaming_config'") __props__.__dict__["streaming_config"] = streaming_config __props__.__dict__["name"] = None __props__.__dict__["service_account"] = None super(NotificationConfig, __self__).__init__( 'gcp:securitycenter/notificationConfig:NotificationConfig', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, config_id: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, organization: Optional[pulumi.Input[str]] = None, pubsub_topic: Optional[pulumi.Input[str]] = None, service_account: Optional[pulumi.Input[str]] = None, streaming_config: Optional[pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']]] = None) -> 'NotificationConfig': """ Get an existing NotificationConfig resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] config_id: This must be unique within the organization. :param pulumi.Input[str] description: The description of the notification config (max of 1024 characters). :param pulumi.Input[str] name: The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. :param pulumi.Input[str] organization: The organization whose Cloud Security Command Center the Notification Config lives in. :param pulumi.Input[str] pubsub_topic: The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". :param pulumi.Input[str] service_account: The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. :param pulumi.Input[pulumi.InputType['NotificationConfigStreamingConfigArgs']] streaming_config: The config for triggering streaming-based notifications. Structure is documented below. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _NotificationConfigState.__new__(_NotificationConfigState) __props__.__dict__["config_id"] = config_id __props__.__dict__["description"] = description __props__.__dict__["name"] = name __props__.__dict__["organization"] = organization __props__.__dict__["pubsub_topic"] = pubsub_topic __props__.__dict__["service_account"] = service_account __props__.__dict__["streaming_config"] = streaming_config return NotificationConfig(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="configId") def config_id(self) -> pulumi.Output[str]: """ This must be unique within the organization. """ return pulumi.get(self, "config_id") @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: """ The description of the notification config (max of 1024 characters). """ return pulumi.get(self, "description") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The resource name of this notification config, in the format 'organizations/{{organization}}/notificationConfigs/{{config_id}}'. """ return pulumi.get(self, "name") @property @pulumi.getter def organization(self) -> pulumi.Output[str]: """ The organization whose Cloud Security Command Center the Notification Config lives in. """ return pulumi.get(self, "organization") @property @pulumi.getter(name="pubsubTopic") def pubsub_topic(self) -> pulumi.Output[str]: """ The Pub/Sub topic to send notifications to. Its format is "projects/[project_id]/topics/[topic]". """ return pulumi.get(self, "pubsub_topic") @property @pulumi.getter(name="serviceAccount") def service_account(self) -> pulumi.Output[str]: """ The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. """ return pulumi.get(self, "service_account") @property @pulumi.getter(name="streamingConfig") def streaming_config(self) -> pulumi.Output['outputs.NotificationConfigStreamingConfig']: """ The config for triggering streaming-based notifications. Structure is documented below. """ return pulumi.get(self, "streaming_config")
44.714004
161
0.661226
22,186
0.97865
0
0
19,452
0.85805
0
0
12,607
0.556109
bc7927d63159c18366a26d654024afa30b73946a
1,893
py
Python
malib/agents/tabular/q_learning/base_tabular_agent.py
wwxFromTju/malib
7cd2a4af55cf1f56da8854e26ea7a4f3782ceea2
[ "MIT" ]
6
2021-05-19T10:25:36.000Z
2021-12-27T03:30:33.000Z
malib/agents/tabular/q_learning/base_tabular_agent.py
wwxFromTju/malib
7cd2a4af55cf1f56da8854e26ea7a4f3782ceea2
[ "MIT" ]
1
2021-05-29T04:51:37.000Z
2021-05-30T06:18:10.000Z
malib/agents/tabular/q_learning/base_tabular_agent.py
wwxFromTju/malib
7cd2a4af55cf1f56da8854e26ea7a4f3782ceea2
[ "MIT" ]
1
2021-06-30T10:53:03.000Z
2021-06-30T10:53:03.000Z
from abc import ABCMeta, abstractmethod import numpy as np class Agent(object): __metaclass__ = ABCMeta def __init__(self, name, id_, action_num, env): self.name = name self.id_ = id_ self.action_num = action_num # len(env.action_space[id_]) # self.opp_action_space = env.action_space[0:id_] + env.action_space[id_:-1] def set_pi(self, pi): # assert len(pi) == self.actin_num self.pi = pi def done(self, env): pass @abstractmethod def act(self, s, exploration, env): pass def update(self, s, a, o, r, s2, env): pass @staticmethod def format_time(n): return "" # s = humanfriendly.format_size(n) # return s.replace(' ', '').replace('bytes', '').replace('byte', '').rstrip('B') def full_name(self, env): return "{}_{}_{}".format(env.name, self.name, self.id_) class StationaryAgent(Agent): def __init__(self, id_, action_num, env, pi=None): super().__init__("stationary", id_, action_num, env) if pi is None: pi = np.random.dirichlet([1.0] * self.action_num) self.pi = np.array(pi, dtype=np.double) StationaryAgent.normalize(self.pi) def act(self, s, exploration, env): if self.verbose: print("pi of agent {}: {}".format(self.id_, self.pi)) return StationaryAgent.sample(self.pi) @staticmethod def normalize(pi): minprob = np.min(pi) if minprob < 0.0: pi -= minprob pi /= np.sum(pi) @staticmethod def sample(pi): return np.random.choice(pi.size, size=1, p=pi)[0] class RandomAgent(StationaryAgent): def __init__(self, id_, action_num, env): assert action_num > 0 super().__init__(id_, env, action_num, pi=[1.0 / action_num] * action_num) self.name = "random"
27.434783
88
0.590597
1,825
0.964078
0
0
488
0.257792
0
0
304
0.160592
bc796051d35cf6cd654ce6528d4ed35ac535ec1b
1,523
py
Python
290.word-pattern.py
Lonitch/hackerRank
84991b8340e725422bc47eec664532cc84a3447e
[ "MIT" ]
null
null
null
290.word-pattern.py
Lonitch/hackerRank
84991b8340e725422bc47eec664532cc84a3447e
[ "MIT" ]
null
null
null
290.word-pattern.py
Lonitch/hackerRank
84991b8340e725422bc47eec664532cc84a3447e
[ "MIT" ]
null
null
null
# # @lc app=leetcode id=290 lang=python3 # # [290] Word Pattern # # https://leetcode.com/problems/word-pattern/description/ # # algorithms # Easy (35.86%) # Likes: 825 # Dislikes: 113 # Total Accepted: 164K # Total Submissions: 455.9K # Testcase Example: '"abba"\n"dog cat cat dog"' # # Given a pattern and a string str, find if str follows the same pattern. # # Here follow means a full match, such that there is a bijection between a # letter in pattern and a non-empty word in str. # # Example 1: # # # Input: pattern = "abba", str = "dog cat cat dog" # Output: true # # Example 2: # # # Input:pattern = "abba", str = "dog cat cat fish" # Output: false # # Example 3: # # # Input: pattern = "aaaa", str = "dog cat cat dog" # Output: false # # Example 4: # # # Input: pattern = "abba", str = "dog dog dog dog" # Output: false # # Notes: # You may assume pattern contains only lowercase letters, and str contains # lowercase letters that may be separated by a single space. # # # @lc code=start from collections import defaultdict class Solution: def wordPattern(self, pattern: str, str1: str) -> bool: if len(pattern)!=len(str1.split()): return False abmap = defaultdict(str) bamap = defaultdict(str) for a,b in zip(pattern, str1.split()): if abmap[a]=='' and bamap[b]=='': abmap[a]=b bamap[b]=a elif abmap[a]!=b or bamap[b]!=a: return False return True # @lc code=end
22.397059
74
0.61392
451
0.296126
0
0
0
0
0
0
986
0.647406
bc79d0b1cabca396208cd2aeb132525a435758f4
705
py
Python
s1_getting_started/exercise_files/final_exercise/model.py
jaschn/dtu_mlops
59f404cffc756739433b5ccebb46ef6bfd467436
[ "Apache-2.0" ]
null
null
null
s1_getting_started/exercise_files/final_exercise/model.py
jaschn/dtu_mlops
59f404cffc756739433b5ccebb46ef6bfd467436
[ "Apache-2.0" ]
null
null
null
s1_getting_started/exercise_files/final_exercise/model.py
jaschn/dtu_mlops
59f404cffc756739433b5ccebb46ef6bfd467436
[ "Apache-2.0" ]
null
null
null
from torch import nn class MyAwesomeModel(nn.Module): def __init__(self): super().__init__() self.cnn = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=5, kernel_size=3), nn.ReLU(), nn.Conv2d(in_channels=5, out_channels=3, kernel_size=3, stride=2) ) self.fc = nn.Sequential(nn.Linear(432, 100), nn.ReLU(), nn.Linear(100,10), nn.LogSoftmax(dim=1) ) def forward(self, x): x = self.cnn(x).view(x.size(0), -1) return self.fc(x)
32.045455
97
0.438298
680
0.964539
0
0
0
0
0
0
0
0
bc7aed95070ea2718e44219b9db81ddfb927929e
5,036
py
Python
musket_core/tests/coders_test.py
dreamflyer/musket_core
1bdf1b4715a3b5c63bf687799d7b977fdf49053f
[ "MIT" ]
16
2019-09-25T14:58:45.000Z
2020-04-04T22:03:27.000Z
musket_core/tests/coders_test.py
dreamflyer/musket_core
1bdf1b4715a3b5c63bf687799d7b977fdf49053f
[ "MIT" ]
17
2019-06-28T06:46:31.000Z
2020-01-23T10:01:12.000Z
musket_core/tests/coders_test.py
dreamflyer/musket_core
1bdf1b4715a3b5c63bf687799d7b977fdf49053f
[ "MIT" ]
2
2019-11-22T15:09:18.000Z
2019-12-17T03:17:25.000Z
import unittest from musket_core import coders import numpy as np import pandas as pd import os import math fl=__file__ fl=os.path.dirname(fl) class TestCoders(unittest.TestCase): def test_binary_num(self): a=np.array([0,1,0,1]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, 1, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, 0, "should be zero") pass def test_binary_str(self): a=np.array(["0","1","0","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "0", "should be zero") pass def test_binary_str2(self): a=np.array(["","1","","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "", "should be zero") pass def test_binary_bool(self): a=np.array([True,False,True,False]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 1, "should be zero") self.assertEqual(bc[1], 0, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, True, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, False, "should be zero") pass def test_categorical_num(self): a=np.array([0,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, 2, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 0, "should be zero") pass def test_categorical_str(self): a=np.array(["a","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "a", "should be zero") pass def test_categorical_str2(self): a=np.array(["","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "", "should be zero") pass def test_categorical_pd(self): a=np.array([math.nan,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][2], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(math.isnan(v),True, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 1, "should be zero") pass def test_multiclass(self): a=np.array(["1 2","0 2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass1(self): a=np.array(["1_2","0_2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass2(self): a=np.array(["1","","",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([True])).sum(), 1,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass
37.029412
86
0.538721
4,881
0.969222
0
0
0
0
0
0
883
0.175338
bc7b31007719919e0de3183e896e2da210eb63a7
1,706
py
Python
manage.py
isijara/zulip
403f4dafcc71369f3b1143b9f7073cd5d76bf357
[ "Apache-2.0" ]
1
2019-04-14T20:31:55.000Z
2019-04-14T20:31:55.000Z
manage.py
hcxiong/zulip
bf22eefedebd50b25f32b22988217c13a89b65d1
[ "Apache-2.0" ]
7
2020-09-06T14:54:30.000Z
2022-02-10T18:51:14.000Z
manage.py
hcxiong/zulip
bf22eefedebd50b25f32b22988217c13a89b65d1
[ "Apache-2.0" ]
9
2019-11-04T18:59:29.000Z
2022-03-22T17:46:37.000Z
#!/usr/bin/env python3 import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import scripts.lib.setup_path_on_import if __name__ == "__main__": if 'posix' in os.name and os.geteuid() == 0: print("manage.py should not be run as root. Use `su zulip` to drop root.") sys.exit(1) if (os.access('/etc/zulip/zulip.conf', os.R_OK) and not os.access('/etc/zulip/zulip-secrets.conf', os.R_OK)): # The best way to detect running manage.py as another user in # production before importing anything that would require that # access is to check for access to /etc/zulip/zulip.conf (in # which case it's a production server, not a dev environment) # and lack of access for /etc/zulip/zulip-secrets.conf (which # should be only readable by root and zulip) print("Error accessing Zulip secrets; manage.py in production must be run as the zulip user.") sys.exit(1) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zproject.settings") from django.conf import settings from django.core.management import execute_from_command_line from django.core.management.base import CommandError from scripts.lib.zulip_tools import log_management_command log_management_command(" ".join(sys.argv), settings.MANAGEMENT_LOG_PATH) os.environ.setdefault("PYTHONSTARTUP", os.path.join(BASE_DIR, "scripts/lib/pythonrc.py")) if "--no-traceback" not in sys.argv and len(sys.argv) > 1: sys.argv.append("--traceback") try: execute_from_command_line(sys.argv) except CommandError as e: print(e, file=sys.stderr) sys.exit(1)
42.65
102
0.694607
0
0
0
0
0
0
0
0
712
0.417351
bc7b521791f08dc13fece1c31003d055797c5819
2,385
py
Python
core/scripts/fetch_instructions_specs.py
merwaaan/mr.system
0b3ff1b1fd726c6fd525a3f03f361dcac678344a
[ "MIT" ]
null
null
null
core/scripts/fetch_instructions_specs.py
merwaaan/mr.system
0b3ff1b1fd726c6fd525a3f03f361dcac678344a
[ "MIT" ]
null
null
null
core/scripts/fetch_instructions_specs.py
merwaaan/mr.system
0b3ff1b1fd726c6fd525a3f03f361dcac678344a
[ "MIT" ]
null
null
null
import json, requests from bs4 import BeautifulSoup def fetch(): r = requests.get('http://clrhome.org/table/') if not r.ok: print('Cannot fetch {})'.format(r.url)) return None # remove newlines text = r.text.replace('\n', '') # Return the data as a BeautifulSoup object for easy querying return BeautifulSoup(text, 'html.parser') def table_title(table): return 'main' if table['title'] == '' else table['title'].lower() def parse_tables(page): return {table_title(table): parse_table(table) for table in page.find_all('table')} def parse_table(table): print('Table {}'.format(table_title(table))) opcodes = [] for td in table.find_all('td', axis=True): hi = int(td.parent.find('th').text, 16) # row lo = td.parent.index(td) - 1 # column code = hi << 4 | lo specs = td['axis'].split('|') # Conditional instructions have different durations depending on how they # branch so the possible durations are stored in an array. Otherwise, the # duration is just stored as a single value. cycles = list(map(int, specs[2].split('/'))) if '/' in specs[2] else int(specs[2]) opcodes.append({ 'opcode': code, 'mnemonics': normalize(td.text).strip(), 'size': int(specs[1]), 'cycles': cycles, 'flags': specs[0], 'description': specs[3] }) print(' {}: {}'.format(hex(code), td.text)) return opcodes def normalize(mnemonics): parts = mnemonics.split(' ') name = parts[0] operands = parts[1].split(',') if len(parts) > 1 else [] return '{} {}'.format(name, ','.join(normalize_operand(o, name) for o in operands)) def normalize_operand(operand, instr_name): # Flag condition if instr_name in ['jr', 'jp', 'ret', 'call'] and operand in ['c', 'nc', 'z', 'nz', 'po', 'pe', 'p', 'm']: operand = 'f_' + { 'po': 'np', 'pe': 'p', 'p': 'ns', 'm': 's' }.get(operand, operand) # Alt registers elif operand == 'af\'': operand = 'af_' return operand if __name__ == '__main__': """ This scripts fetches the contents of a webpage that contains nicely formatted data about the Z80 opcodes and outputs it to JSON. """ page = fetch() if page is not None: opcodes = parse_tables(page) with open('opcodes.json', 'w') as output: json.dump(opcodes, output, indent=2)
24.84375
107
0.607547
0
0
0
0
0
0
0
0
778
0.326205
bc7c42367a8432fba7810ae50ee93f6f9fc12d32
2,516
py
Python
unittests/tools/test_intsights_parser.py
M-Rod101/django-DefectDojo
7b09a00b1a526abaf40455c2ddec16aaa06b16e2
[ "BSD-3-Clause" ]
249
2016-09-06T21:04:40.000Z
2018-01-19T15:59:44.000Z
unittests/tools/test_intsights_parser.py
OWASP/django-DefectDojo
c101e47b294863877cd68a82d0cc60f8017b45b1
[ "BSD-3-Clause" ]
255
2016-09-06T21:36:37.000Z
2018-01-19T19:57:57.000Z
unittests/tools/test_intsights_parser.py
M-Rod101/django-DefectDojo
7b09a00b1a526abaf40455c2ddec16aaa06b16e2
[ "BSD-3-Clause" ]
152
2016-09-06T21:04:54.000Z
2018-01-18T08:52:24.000Z
from ..dojo_test_case import DojoTestCase from dojo.models import Test from dojo.tools.intsights.parser import IntSightsParser class TestIntSightsParser(DojoTestCase): def test_intsights_parser_with_one_critical_vuln_has_one_findings_json( self): testfile = open("unittests/scans/intsights/intsights_one_vul.json") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(1, len(findings)) finding = list(findings)[0] self.assertEqual( '5c80dbf83b4a3900078b6be6', finding.unique_id_from_tool) self.assertEqual( 'HTTP headers weakness in initech.com web server', finding.title) self.assertEquals('Critical', finding.severity) self.assertEquals( "https://dashboard.intsights.com/#/threat-command/alerts?search=5c80dbf83b4a3900078b6be6", finding.references) def test_intsights_parser_with_one_critical_vuln_has_one_findings_csv( self): testfile = open("unittests/scans/intsights/intsights_one_vuln.csv") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(1, len(findings)) finding = list(findings)[0] self.assertEqual( "mn7xy83finmmth4ja363rci9", finding.unique_id_from_tool) self.assertEqual( "HTTP headers weakness in company-domain.com web server", finding.title) def test_intsights_parser_with_many_vuln_has_many_findings_json(self): testfile = open("unittests/scans/intsights/intsights_many_vul.json") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(3, len(findings)) def test_intsights_parser_with_many_vuln_has_many_findings_csv(self): testfile = open("unittests/scans/intsights/intsights_many_vuln.csv") parser = IntSightsParser() findings = parser.get_findings(testfile, Test()) testfile.close() self.assertEqual(9, len(findings)) def test_intsights_parser_invalid_text_with_error_csv(self): with self.assertRaises(ValueError): testfile = open( "unittests/scans/intsights/intsights_invalid_file.txt") parser = IntSightsParser() findings = parser.get_findings(testfile, Test())
38.121212
102
0.677663
2,386
0.948331
0
0
0
0
0
0
512
0.203498
bc7fdbab2e2a6960b77a8cd250963e5c2c2a372b
5,046
py
Python
tools/testutils.py
sktollman/p4c
380830f6c26135d1d65e1312e3ba2da628c18145
[ "Apache-2.0" ]
1
2019-01-01T21:46:03.000Z
2019-01-01T21:46:03.000Z
tools/testutils.py
cslev/p4c
008f01ebc4bc0fcada4e674e9916b156427512ca
[ "Apache-2.0" ]
null
null
null
tools/testutils.py
cslev/p4c
008f01ebc4bc0fcada4e674e9916b156427512ca
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2013-present Barefoot Networks, Inc. # Copyright 2018 VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Defines helper functions for a general testing framework. Used by multiple Python testing scripts in the backends folder.""" from __future__ import print_function import subprocess from subprocess import Popen from threading import Timer import sys import os TIMEOUT = 10 * 60 SUCCESS = 0 FAILURE = 1 SKIPPED = 2 # used occasionally to indicate that a test was not executed def is_err(p4filename): """ True if the filename represents a p4 program that should fail. """ return "_errors" in p4filename def report_err(file, *message): """ Write message to given file, report to stderr if verbose """ print("***", file=sys.stderr, *message) if (file and file != sys.stderr): err_file = open(file, "a+") print("***", file=err_file, *message) err_file.close() def report_output(file, verbose, *message): """ Write message to given file, report to stdout if verbose """ if (verbose): print(file=sys.stdout, *message) if (file and file != sys.stdout): out_file = open(file, "a+") print("", file=out_file, *message) out_file.close() def byte_to_hex(byteStr): """ Convert byte sequences to a hex string. """ return ''.join(["%02X " % ord(x) for x in byteStr]).strip() def hex_to_byte(hexStr): """ Convert hex strings to bytes. """ bytes = [] hexStr = ''.join(hexStr.split(" ")) for i in range(0, len(hexStr), 2): bytes.append(chr(int(hexStr[i:i + 2], 16))) return ''.join(bytes) def compare_pkt(outputs, expected, received): """ Compare two given byte sequences and check if they are the same. Report errors if this is not the case. """ received = ''.join(byte_to_hex(str(received)).split()).upper() expected = ''.join(expected.split()).upper() if len(received) < len(expected): report_err(outputs["stderr"], "Received packet too short", len(received), "vs", len(expected)) return FAILURE for i in range(0, len(expected)): if expected[i] == "*": continue if expected[i] != received[i]: report_err(outputs["stderr"], "Received packet ", received) report_err(outputs["stderr"], "Packet different at position", i, ": expected", expected[i], ", received", received[i]) report_err(outputs["stderr"], "Expected packet ", expected) return FAILURE return SUCCESS def open_process(verbose, args, outputs): """ Run the given arguments as a subprocess. Time out after TIMEOUT seconds and report failures or stdout. """ report_output(outputs["stdout"], verbose, "Writing", args) proc = None if outputs["stderr"] is not None: try: proc = Popen(args, stdout=subprocess.PIPE, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) except OSError as e: report_err(outputs["stderr"], "Failed executing: ", e) if proc is None: # Never even started report_err(outputs["stderr"], "Process failed to start") return proc def run_process(verbose, proc, timeout, outputs, errmsg): def kill(process): process.kill() timer = Timer(TIMEOUT, kill, [proc]) try: timer.start() out, err = proc.communicate() finally: timer.cancel() if out: msg = ("\n########### PROCESS OUTPUT BEGIN:\n" "%s########### PROCESS OUTPUT END\n" % out) report_output(outputs["stdout"], verbose, msg) if proc.returncode != SUCCESS: report_err(outputs["stderr"], "Error %d: %s\n%s" % (proc.returncode, errmsg, err)) else: # Also report non fatal warnings in stdout if err: report_err(outputs["stderr"], err) return proc.returncode def run_timeout(verbose, args, timeout, outputs, errmsg): proc = open_process(verbose, args, outputs) if proc is None: return FAILURE report_output(outputs["stdout"], verbose, "Executing", args) return run_process(verbose, proc, timeout, outputs, errmsg) def check_root(): """ This function returns False if the user does not have root privileges. Caution: Only works on Unix systems """ return (os.getuid() == 0)
33.865772
78
0.630202
0
0
0
0
0
0
0
0
1,956
0.387634
bc8027a9a53c2f0f832850a598757b1b43c5255c
6,237
py
Python
AlgorithmsAndDataStructures/mod2/Heap.py
BootyAss/bmstu
bea202cbdff159d3840335b2a2a5c3bd632a7393
[ "FSFAP" ]
null
null
null
AlgorithmsAndDataStructures/mod2/Heap.py
BootyAss/bmstu
bea202cbdff159d3840335b2a2a5c3bd632a7393
[ "FSFAP" ]
null
null
null
AlgorithmsAndDataStructures/mod2/Heap.py
BootyAss/bmstu
bea202cbdff159d3840335b2a2a5c3bd632a7393
[ "FSFAP" ]
1
2021-09-15T18:39:33.000Z
2021-09-15T18:39:33.000Z
class Heap: def __init__(self): self.items = dict() # key - (value, index) self.indexes = [] # index - key // to know indexes # Usefull functions def swap(self, i, j): x = self.indexes[i] # key of 1 item y = self.indexes[j] # key of 2 item # swap keys in index array self.indexes[i] = y self.indexes[j] = x temp = self.items[x][1] # index of 1 item # swap indexes in dictionary self.items.update({x: (self.items[x][0], self.items[y][1])}) self.items.update({y: (self.items[y][0], temp)}) def bigger(self, i, j): if self.indexes[i] <= self.indexes[j]: return False else: return True # Check family UwU def hasParent(self, i): if (i - 1)/2 >= 0: return True return False def parentIndex(self, i): return int((i - 1)/2) def hasLeft(self, i): if i*2 + 1 < len(self.indexes): return True return False def leftIndex(self, i): return int(i*2 + 1) def hasRight(self, i): if i*2 + 2 < len(self.indexes): return True return False def rightIndex(self, i): return int(i*2 + 2) # heapifys def heapifyUp(self, i=None): if i: index = i else: index = len(self.indexes) - 1 while self.hasParent(index) and self.bigger(self.parentIndex(index), index): self.swap(self.parentIndex(index), index) index = self.parentIndex(index) def heapifyDown(self, i=0): index = i while self.hasLeft(index): smaller = self.leftIndex(index) if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)): smaller = self.rightIndex(index) if self.bigger(smaller, index): break else: self.swap(index, smaller) index = smaller # all needed methods def add(self, key, data): if self.items.get(key, None): raise(Exception) self.items[key] = (data, int(len(self.indexes))) self.indexes.append(key) self.heapifyUp() def set(self, key, data): temp = self.items.get(key, None) if not temp: raise(Exception) self.items[key] = (data, temp[1]) def delete(self, key): temp = self.items.get(key, None) if not temp: raise(Exception) if len(self.indexes) > 1: lastKey = self.indexes[-1] last = self.items.get(lastKey, None) # set last item index of deleted self.items.update({lastKey: (last[0], temp[1])}) # set key of last item to deleted index self.indexes[temp[1]] = lastKey self.indexes.pop() del self.items[key] if temp[1] < len(self.indexes): # dont heapify if deleted last element self.heapifyDown(i=temp[1]) self.heapifyUp(i=temp[1]) def search(self, key): temp = self.items.get(key, None) if temp: print('1', temp[1], temp[0]) else: print('0') def min(self): if len(self.indexes) == 0: raise(Exception) key = self.indexes[0] print(key, '0', self.items[key][0]) def max(self): if len(self.indexes) == 0: raise(Exception) i = int(len(self.indexes)/2) maxKey = self.indexes[i] index = i while i < len(self.indexes): if maxKey < self.indexes[i]: maxKey = self.indexes[i] index = i i += 1 print(maxKey, index, self.items[maxKey][0]) def extract(self): if len(self.indexes) == 0: raise(Exception) rootKey = self.indexes[0] rootData = self.items[rootKey][0] del self.items[rootKey] if len(self.indexes) > 1: self.indexes[0] = self.indexes.pop() # set top item index to 0 self.items.update({self.indexes[0] : (self.items[self.indexes[0]][0], 0)}) self.heapifyDown() else: self.indexes.pop() print(rootKey, rootData) def print(self): height = 0 index = 0 out = '' i = 0 if len(self.indexes) == 0: out += '_\n' print('_') return while i < len(self.indexes): lineLen = 1 << height index += 1 key = self.indexes[i] out += '[' + str(key) + ' ' + self.items[key][0] if height != 0: out += ' ' + str(self.indexes[self.parentIndex(i)]) out += ']' if index == lineLen: out += '\n' index = 0 height += 1 else: out += ' ' i += 1 if index != 0 and index < lineLen: out += '_ ' * (lineLen - index) print(out[0:-1]) else: print(out, end='') cycle = True heap = Heap() while cycle: try: line = input() cmd = line.split(' ', 2) try: if len(cmd) == 1 and cmd[0] == '': continue if len(cmd) == 2 and cmd[0] == '' and cmd[1] == '': continue if cmd[0] == 'add': heap.add(int(cmd[1]), cmd[2]) elif cmd[0] == 'set': heap.set(int(cmd[1]), cmd[2]) elif cmd[0] == 'delete': heap.delete(int(cmd[1])) elif cmd[0] == 'search': heap.search(int(cmd[1])) elif cmd[0] == 'min': heap.min() elif cmd[0] == 'max': heap.max() elif cmd[0] == 'extract': heap.extract() elif cmd[0] == 'print': heap.print() else: raise(Exception) except Exception: print('error') continue except Exception: cycle = False
25.048193
99
0.467372
5,194
0.832772
0
0
0
0
0
0
470
0.075357
bc807e3864743112b7b85584b7afbab826c8463a
2,332
py
Python
django_comments_xtd/tests/test_api_views.py
Boondockers-Welcome/django-comments-xtd
8edd68350803bfc351345820ccc4289077918e91
[ "BSD-2-Clause" ]
1
2021-01-27T03:20:45.000Z
2021-01-27T03:20:45.000Z
django_comments_xtd/tests/test_api_views.py
Boondockers-Welcome/django-comments-xtd
8edd68350803bfc351345820ccc4289077918e91
[ "BSD-2-Clause" ]
null
null
null
django_comments_xtd/tests/test_api_views.py
Boondockers-Welcome/django-comments-xtd
8edd68350803bfc351345820ccc4289077918e91
[ "BSD-2-Clause" ]
1
2020-03-24T21:28:31.000Z
2020-03-24T21:28:31.000Z
from __future__ import unicode_literals try: from unittest.mock import patch except ImportError: from mock import patch from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django.urls import reverse from rest_framework.test import APIRequestFactory, force_authenticate from django_comments_xtd import django_comments from django_comments_xtd.api.views import CommentCreate from django_comments_xtd.tests.models import Article, Diary request_factory = APIRequestFactory() def post_comment(data, auth_user=None): request = request_factory.post(reverse('comments-xtd-api-create'), data) if auth_user: force_authenticate(request, user=auth_user) view = CommentCreate.as_view() return view(request) class CommentCreateTestCase(TestCase): def setUp(self): patcher = patch('django_comments_xtd.views.send_mail') self.mock_mailer = patcher.start() self.article = Article.objects.create( title="October", slug="october", body="What I did on October...") self.form = django_comments.get_form()(self.article) def test_post_returns_2xx_response(self): data = {"name": "Bob", "email": "[email protected]", "followup": True, "reply_to": 0, "level": 1, "order": 1, "comment": "Es war einmal eine kleine...", "honeypot": ""} data.update(self.form.initial) response = post_comment(data) self.assertEqual(response.status_code, 204) self.assertEqual(self.mock_mailer.call_count, 1) def test_post_returns_4xx_response(self): # It uses an authenticated user, but the user has no mail address. self.user = User.objects.create_user("bob", "", "pwd") data = {"name": "", "email": "", "followup": True, "reply_to": 0, "level": 1, "order": 1, "comment": "Es war einmal eine kleine...", "honeypot": ""} data.update(self.form.initial) response = post_comment(data, auth_user=self.user) self.assertEqual(response.status_code, 400) self.assertTrue('name' in response.data) self.assertTrue('email' in response.data) self.assertEqual(self.mock_mailer.call_count, 0)
37.612903
77
0.677959
1,506
0.645798
0
0
0
0
0
0
422
0.180961
bc8126cdbc2e20b53b03bc4d747c2a82d0fde975
892
py
Python
LC/358.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
2
2018-02-24T17:20:02.000Z
2018-02-24T17:25:43.000Z
LC/358.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
null
null
null
LC/358.py
szhu3210/LeetCode_Solutions
64747eb172c2ecb3c889830246f3282669516e10
[ "MIT" ]
null
null
null
class Solution(object): def rearrangeString(self, str, k): """ :type str: str :type k: int :rtype: str """ ## greedy: count keeps the # of chars, valid keeps the leftmost valid index of a char. res=[] # count # of chars d=collections.defaultdict(int) for c in str: d[c]+=1 # create a valid dict v=collections.defaultdict(int) # add char one by one, that with max # first, must have valid leftmost index for i in range(len(str)): c=None for key in d: if (not c or d[key]>d[c]) and d[key]>0 and v[key]<=i: # get c with max # and be valid c=key if not c: return '' res.append(c) d[c]-=1 v[c]=i+k return ''.join(res)
29.733333
101
0.465247
892
1
0
0
0
0
0
0
315
0.353139
bc82ef8de803f7a119ffe50ddde0e017fafeacd2
16,041
py
Python
momentumopt/python/momentumopt/kinoptpy/momentum_kinematics_optimizer.py
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
null
null
null
momentumopt/python/momentumopt/kinoptpy/momentum_kinematics_optimizer.py
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
null
null
null
momentumopt/python/momentumopt/kinoptpy/momentum_kinematics_optimizer.py
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
null
null
null
''' @file momentum_kinematics_optimizer.py @package momentumopt @author Brahayam Ponton ([email protected]) @license License BSD-3-Clause @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft. @date 2019-10-08 ''' import os import numpy as np from momentumopt.kinoptpy.qp import QpSolver from momentumopt.kinoptpy.inverse_kinematics import PointContactInverseKinematics from pinocchio import RobotWrapper import pinocchio as se3 from pinocchio.utils import zero from pymomentum import * from momentumopt.quadruped.quadruped_wrapper import QuadrupedWrapper from momentumopt.kinoptpy.min_jerk_traj import * from pymomentum import \ PlannerVectorParam_KinematicDefaultJointPositions, \ PlannerIntParam_NumTimesteps, \ PlannerDoubleParam_TimeStep class Contact(object): def __init__(self, position, start_time, end_time): self.pos = position self.init_time = start_time self.final_time = end_time def position(self): return self.pos def start_time(self): return self.init_time def end_time(self): return self.final_time def get_contact_plan(contact_states, effs): contacts = {} for i, eff in enumerate(effs): num_contacts = len(contact_states(i)) contacts[eff] = [] for j in range(num_contacts): contact_ = contact_states(i)[j] start_time = contact_.start_time end_time = contact_.end_time position = contact_.position contacts[eff].append(Contact(position, start_time, end_time)) return contacts def generate_eff_traj(contacts, z_offset): effs = contacts.keys() eff_traj_poly = {} for eff in effs: cnt = contacts[eff] num_contacts = len(cnt) poly_traj = [ PolynominalList(), PolynominalList(), PolynominalList() ] for i in range(num_contacts): # Create a constant polynominal for endeffector on the ground. t = [cnt[i].start_time(), cnt[i].end_time()] for idx in range(3): poly_traj[idx].append(t, constant_poly(cnt[i].position()[idx])) # If there is a contact following, add the transition between # the two contact points. if i < num_contacts - 1: t = [cnt[i].end_time(), cnt[i+1].start_time()] for idx in range(3): via = None if idx == 2: via = z_offset + cnt[i].position()[idx] poly = poly_points(t, cnt[i].position()[idx], cnt[i+1].position()[idx], via) poly_traj[idx].append(t, poly) eff_traj_poly[eff] = poly_traj # returns end eff trajectories return eff_traj_poly class EndeffectorTrajectoryGenerator(object): def __init__(self): self.z_offset = 0.1 def get_z_bound(self, mom_kin_optimizer): z_max = min(max(mom_kin_optimizer.com_dyn[:, 2]), self.max_bound) z_min = max(min(mom_kin_optimizer.com_dyn[:, 2]), self.min_bound) return z_max, z_min def __call__(self, mom_kin_optimizer): ''' Computes the endeffector positions and velocities. Returns endeff_pos_ref, endeff_vel_ref [0]: endeff_pos_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] [1]: endeff_vel_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] ''' dt = mom_kin_optimizer.dt num_eff = len(mom_kin_optimizer.eff_names) num_time_steps = mom_kin_optimizer.num_time_steps contacts = get_contact_plan(mom_kin_optimizer.contact_sequence.contact_states, mom_kin_optimizer.eff_names) # Generate minimum jerk trajectories eff_traj_poly = generate_eff_traj(contacts, self.z_offset) # Compute the endeffector position and velocity trajectories. endeff_pos_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_vel_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_contact = np.zeros((num_time_steps, num_eff)) for it in range(num_time_steps): for eff, name in enumerate(mom_kin_optimizer.eff_names): endeff_pos_ref[it][eff] = [eff_traj_poly[name][i].eval(it * dt) for i in range(3)] endeff_vel_ref[it][eff] = [eff_traj_poly[name][i].deval(it * dt) for i in range(3)] # HACK: If the velocity is zero, assume the endeffector is in # contact with the ground. if np.all(endeff_vel_ref[it][eff] == 0.): endeff_contact[it][eff] = 1. else: endeff_contact[it][eff] = 0. return endeff_pos_ref, endeff_vel_ref, endeff_contact class JointTrajectoryGenerator(object): def __init__(self): self.dt =.01 self.num_time_steps = None self.q_init = None self.poly_traj = None def joint_traj(self, q_via): self.poly_traj = [] for i in range(len(self.q_init)): self.poly_traj = np.append(self.poly_traj, [PolynominalList()]) for j in range(len(self.q_init)): for i in range (len(q_via[:,0])+1): if i==0: t = [0, q_via[0,0]/self.dt] poly = poly_points(t, self.q_init[j], q_via[i,j+1]) self.poly_traj[j].append(t, poly) elif(i==len(q_via[:,0])): t = [q_via[i-1,0]/self.dt, self.num_time_steps] poly = poly_points(t, q_via[i-1,j+1], self.q_init[j]) self.poly_traj[j].append(t, poly) else: t = [q_via[i-1,0]/self.dt, q_via[i,0]/self.dt] poly = poly_points(t, q_via[i-1,j+1], q_via[i,j+1]) self.poly_traj[j].append(t, poly) def eval_traj(self,t): q = np.zeros((1,len(self.q_init)),float) for j in range(len(self.q_init)): q[0,j] = self.poly_traj[j].eval(t) return np.matrix(q) class MomentumKinematicsOptimizer(object): def __init__(self): self.q_init = None self.dq_init = None self.reg_orientation = 1e-2 self.reg_joint_position = 2. self.joint_des = None def reset(self): self.kinematics_sequence = KinematicsSequence() self.kinematics_sequence.resize(self.planner_setting.get(PlannerIntParam_NumTimesteps), self.planner_setting.get(PlannerIntParam_NumDofs)) def initialize(self, planner_setting, max_iterations=50, eps=0.001, endeff_traj_generator=None, RobotWrapper=QuadrupedWrapper): self.planner_setting = planner_setting if endeff_traj_generator is None: endeff_traj_generator = EndeffectorTrajectoryGenerator() self.endeff_traj_generator = endeff_traj_generator self.dt = planner_setting.get(PlannerDoubleParam_TimeStep) self.num_time_steps = planner_setting.get(PlannerIntParam_NumTimesteps) self.max_iterations = max_iterations self.eps = eps self.robot = RobotWrapper() self.reset() # Holds dynamics and kinematics results self.com_dyn = np.zeros((self.num_time_steps, 3)) self.lmom_dyn = np.zeros((self.num_time_steps, 3)) self.amom_dyn = np.zeros((self.num_time_steps, 3)) self.com_kin = np.zeros((self.num_time_steps, 3)) self.lmom_kin = np.zeros((self.num_time_steps, 3)) self.amom_kin = np.zeros((self.num_time_steps, 3)) self.q_kin = np.zeros((self.num_time_steps, self.robot.model.nq)) self.dq_kin = np.zeros((self.num_time_steps, self.robot.model.nv)) self.hip_names = ['{}_HFE'.format(eff) for eff in self.robot.effs] self.hip_ids = [self.robot.model.getFrameId(name) for name in self.hip_names] self.eff_names = ['{}_{}'.format(eff, self.robot.joints_list[-1]) for eff in self.robot.effs] self.inv_kin = PointContactInverseKinematics(self.robot.model, self.eff_names) self.motion_eff = { 'trajectory': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'trajectory_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)) } def fill_data_from_dynamics(self): # The centroidal information for it in range(self.num_time_steps): self.com_dyn[it] = self.dynamic_sequence.dynamics_states[it].com self.lmom_dyn[it] = self.dynamic_sequence.dynamics_states[it].lmom self.amom_dyn[it] = self.dynamic_sequence.dynamics_states[it].amom def fill_endeffector_trajectory(self): self.endeff_pos_ref, self.endeff_vel_ref, self.endeff_contact = \ self.endeff_traj_generator(self) def fill_kinematic_result(self, it, q, dq): def framesPos(frames): return np.vstack([data.oMf[idx].translation for idx in frames]).reshape(-1) def framesVel(frames): return np.vstack([ self.inv_kin.get_world_oriented_frame_jacobian(q, idx).dot(dq)[:3] for idx in frames ]).reshape(-1) data = self.inv_kin.robot.data hg = self.inv_kin.robot.centroidalMomentum(q, dq) # Storing on the internal array. self.com_kin[it] = self.inv_kin.robot.com(q).T self.lmom_kin[it] = hg.linear.T self.amom_kin[it] = hg.angular.T self.q_kin[it] = q.T self.dq_kin[it] = dq.T # The endeffector informations as well. self.motion_eff['trajectory'][it] = framesPos(self.inv_kin.endeff_ids) self.motion_eff['velocity'][it] = self.inv_kin.J[6:(self.inv_kin.ne + 2) * 3].dot(dq).T self.motion_eff['trajectory_wrt_base'][it] = \ self.motion_eff['trajectory'][it] - framesPos(self.hip_ids) self.motion_eff['velocity_wrt_base'][it] = \ self.motion_eff['velocity'][it] - framesVel(self.hip_ids) # Storing on the kinematic sequence. kinematic_state = self.kinematics_sequence.kinematics_states[it] kinematic_state.com = self.com_kin[it] kinematic_state.lmom = self.lmom_kin[it] kinematic_state.amom = self.amom_kin[it] kinematic_state.robot_posture.base_position = q[:3] kinematic_state.robot_posture.base_orientation = q[3:7] kinematic_state.robot_posture.joint_positions = q[7:] kinematic_state.robot_velocity.base_linear_velocity = dq[:3] kinematic_state.robot_velocity.base_angular_velocity = dq[3:6] kinematic_state.robot_velocity.joint_velocities = dq[6:] def optimize_initial_position(self, init_state): # Optimize the initial configuration q = se3.neutral(self.robot.model) plan_joint_init_pos = self.planner_setting.get( PlannerVectorParam_KinematicDefaultJointPositions) if len(plan_joint_init_pos) != self.robot.num_ctrl_joints: raise ValueError( 'Number of joints in config file not same as required for robot\n' + 'Got %d joints but robot expects %d joints.' % ( len(plan_joint_init_pos), self.robot.num_ctrl_joints)) q[7:] = np.matrix(plan_joint_init_pos).T q[2] = self.robot.floor_height + 0.32 dq = np.matrix(np.zeros(self.robot.robot.nv)).T com_ref = init_state.com lmom_ref = np.zeros(3) amom_ref = np.zeros(3) endeff_pos_ref = np.array([init_state.effPosition(i) for i in range(init_state.effNum())]) endeff_vel_ref = np.matrix(np.zeros((init_state.effNum(), 3))) endeff_contact = np.ones(init_state.effNum()) quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) q[3:7] = quad_goal.coeffs() for iters in range(self.max_iterations): # Adding small P controller for the base orientation to always start with flat # oriented base. quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = 1e-1 * se3.log((quad_goal * quad_q.inverse()).matrix()) res = self.inv_kin.compute(q, dq, com_ref, lmom_ref, amom_ref, endeff_pos_ref, endeff_vel_ref, endeff_contact, None) q = se3.integrate(self.robot.model, q, res) if np.linalg.norm(res) < 1e-3: print('Found initial configuration after {} iterations'.format(iters + 1)) break if iters == self.max_iterations - 1: print('Failed to converge for initial setup.') print("initial configuration: \n", q) self.q_init = q.copy() self.dq_init = dq.copy() def optimize(self, init_state, contact_sequence, dynamic_sequence, plotting=False): self.init_state = init_state self.contact_sequence = contact_sequence self.dynamic_sequence = dynamic_sequence self.q_via = None # Create array with centroidal and endeffector informations. self.fill_data_from_dynamics() self.fill_endeffector_trajectory() # Run the optimization for the initial configuration only once. if self.q_init is None: self.optimize_initial_position(init_state) # Get the desired joint trajectory # print "num_joint_via:",self.planner_setting.get(PlannerIntParam_NumJointViapoints) # print "joint_via:",self.planner_setting.get(PlannerCVectorParam_JointViapoints) # TODO: this is for jump, should go to config file # q_jump = [1., 0.1, -0.2 ,0.1, -0.2 ,-0.1, 0.2 ,-0.1, 0.2] # q_via = np.matrix([.75, np.pi/2, -np.pi, np.pi/2, -np.pi, -np.pi/2, np.pi, -np.pi/2, np.pi]).T # q_max = np.matrix([1.35, .7*np.pi/2, -.7*np.pi, .7*np.pi/2, -.7*np.pi, -.7*np.pi/2, .7*np.pi, -.7*np.pi/2, .7*np.pi]).T # q_via0 = np.vstack((q_via.T, q_jump)) # self.q_via = np.vstack((q_via0, q_max.T)) joint_traj_gen = JointTrajectoryGenerator() joint_traj_gen.num_time_steps = self.num_time_steps joint_traj_gen.q_init = self.q_init[7:] self.joint_des = np.zeros((len(self.q_init[7:]),self.num_time_steps), float) if self.q_via is None: for i in range (self.num_time_steps): self.joint_des[:,i] = self.q_init[7 : ].T else: joint_traj_gen.joint_traj(self.q_via) for it in range(self.num_time_steps): self.joint_des[:,it] = joint_traj_gen.eval_traj(it) # Compute inverse kinematics over the full trajectory. self.inv_kin.is_init_time = 0 q, dq = self.q_init.copy(), self.dq_init.copy() for it in range(self.num_time_steps): quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = (self.reg_orientation * se3.log((quad_goal * quad_q.inverse()).matrix()).T + self.amom_dyn[it]).reshape(-1) joint_regularization_ref = self.reg_joint_position * (np.matrix(self.joint_des[:,it]).T - q[7 : ]) # joint_regularization_ref = self.reg_joint_position * (self.q_init[7 : ] - q[7 : ]) # Fill the kinematics results for it. self.inv_kin.forward_robot(q, dq) self.fill_kinematic_result(it, q, dq) dq = self.inv_kin.compute( q, dq, self.com_dyn[it], self.lmom_dyn[it], amom_ref, self.endeff_pos_ref[it], self.endeff_vel_ref[it], self.endeff_contact[it], joint_regularization_ref) # Integrate to the next state. q = se3.integrate(self.robot.model, q, dq * self.dt)
41.342784
130
0.625335
13,565
0.845646
0
0
0
0
0
0
2,538
0.15822
bc831b7e95388ec378c7efd07e50c5540c59f285
435
py
Python
gullveig/web/__init__.py
Addvilz/gullveig
6ac5e66062c1b5ea8ad7c66f69be9e3d99ac0825
[ "Apache-2.0" ]
8
2020-08-24T14:53:14.000Z
2021-03-16T03:58:01.000Z
gullveig/web/__init__.py
Addvilz/gullveig
6ac5e66062c1b5ea8ad7c66f69be9e3d99ac0825
[ "Apache-2.0" ]
6
2020-08-25T13:19:02.000Z
2021-02-21T21:55:34.000Z
gullveig/web/__init__.py
Addvilz/gullveig
6ac5e66062c1b5ea8ad7c66f69be9e3d99ac0825
[ "Apache-2.0" ]
null
null
null
import logging from gullveig import bootstrap_default_logger # Configure default logging def _configure_default_web_logger(): logger = logging.getLogger('gullveig-web') bootstrap_default_logger(logger) api_logger = logging.getLogger('gullveig-api') bootstrap_default_logger(api_logger) aio_logger = logging.getLogger('aiohttp.server') bootstrap_default_logger(aio_logger) _configure_default_web_logger()
22.894737
52
0.795402
0
0
0
0
0
0
0
0
71
0.163218
bc84db3b22d112c3d8e47827ed44b0cdb57ad39d
1,482
py
Python
jupyterhub_http_authenticator/httpauthenticator.py
clockfly/jupterhub_http_authenticator
88185e4677836129cd1bd15af368b7070103b1bf
[ "BSD-3-Clause" ]
null
null
null
jupyterhub_http_authenticator/httpauthenticator.py
clockfly/jupterhub_http_authenticator
88185e4677836129cd1bd15af368b7070103b1bf
[ "BSD-3-Clause" ]
null
null
null
jupyterhub_http_authenticator/httpauthenticator.py
clockfly/jupterhub_http_authenticator
88185e4677836129cd1bd15af368b7070103b1bf
[ "BSD-3-Clause" ]
null
null
null
import json import urllib import os import jupyterhub from tornado.httpclient import HTTPRequest, AsyncHTTPClient from traitlets import Unicode from jupyterhub.auth import Authenticator from tornado import gen class HttpAuthenticator(Authenticator): server = Unicode( None, allow_none=True, config=True, help=""" Http authentication server. """ ) appid = Unicode( None, allow_none=True, config=True, help=""" Application Id recognized by the http authentication server """ ) @gen.coroutine def authenticate(self, handler, data): http_client = AsyncHTTPClient() headers = { "Accept": "application/json", "User-Agent": "JupyterHub", } params = dict( type="json", appid=self.appid, ac=data['username'], pw=data['password'] ) req = HTTPRequest(self.server, method="POST", headers=headers, body=urllib.parse.urlencode(params), validate_cert = False ) resp = yield http_client.fetch(req) reply = json.loads(resp.body.decode('utf8', 'replace')) if reply.get("code") == 200: return (reply.get("data").get("UserCN")) else: return None
23.52381
68
0.524966
1,268
0.855601
860
0.580297
879
0.593117
0
0
253
0.170715
bc85621d3dca3de545ceeff3a1f12920ad9784b4
9,912
py
Python
src/lr_find.py
KushajveerSingh/fastai_without_fastai
9a7c71b92c49be1e05858dc0e7ce63901c3c1bd2
[ "MIT" ]
12
2019-03-30T16:43:53.000Z
2022-03-21T19:49:12.000Z
src/lr_find.py
KushajveerSingh/fastai_without_fastai
9a7c71b92c49be1e05858dc0e7ce63901c3c1bd2
[ "MIT" ]
null
null
null
src/lr_find.py
KushajveerSingh/fastai_without_fastai
9a7c71b92c49be1e05858dc0e7ce63901c3c1bd2
[ "MIT" ]
null
null
null
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # NOT -> ParameterModule # NOT -> children_and_parameters # NOT -> flatten_model # NOT -> lr_range # NOT -> scheduling functions # NOT -> SmoothenValue # YES -> lr_find # NOT -> plot_lr_find # NOT TO BE MODIFIED class ParameterModule(nn.Module): "Register a lone parameter 'p' in a module" def __init__(self, p:nn.Parameter): super().__init__() self.val = p def forward(self, x): return x # NOT TO BE MODIFIED # To be used to flatten_model def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[]) for p in m.parameters(): if id(p) not in children_p: children.append(ParameterModule(p)) return children # NOT TO BE MODIFIED flatten_model = lambda m: sum(map(flatten_model,children_and_parameters(m)),[]) if len(list(m.children())) else [m] # NOT TO BE MODIFIED def lr_range(model, lr): """ Build differential learning rate from lr. It will give you the Arguments: model :- torch.nn.Module lr :- float or slice Returns: Depending upon lr """ if not isinstance(lr, slice): return lr num_layer = len([nn.Sequential(*flatten_model(model))]) if lr.start: mult = lr.stop / lr.start step = mult**(1/(num_layer-1)) res = np.array([lr.start*(step**i) for i in range(num_layer)]) else: res = [lr.stop/10.]*(num_layer-1) + [lr.stop] return np.array(res) # NOT TO BE MODIFIED # These are the functions that would give us the values of lr. Liks for linearly # increasing lr we would use annealing_linear. # You can add your own custom function, for producing lr. # By defualt annealing_exp is used for both lr and momentum def annealing_no(start, end, pct:float): "No annealing, always return `start`." return start def annealing_linear(start, end, pct:float): "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start + pct * (end-start) def annealing_exp(start, end, pct:float): "Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start * (end/start) ** pct def annealing_cos(start, end, pct:float): "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start-end)/2 * cos_out def do_annealing_poly(start, end, pct:float, degree): return end + (start-end) * (1-pct)**degree # NOT TO BE MODIFIED class Stepper(): """ Used to step from start, end ('vals') over 'n_iter' iterations on a schedule. We will create a stepper object and then use one of the above annelaing functions, to step from start lr to end lr. """ def __init__(self, vals, n_iter:int, func=None): self.start, self.end = (vals[0], vals[1]) if isinstance(vals, tuple) else (vals,0) self.n_iter = max(1, n_iter) if func is None: self.func = annealing_linear if isinstance(vals, tuple) else annealing_no else: self.func = func self.n = 0 def step(self): "Return next value along annealed schedule" self.n += 1 return self.func(self.start, self.end, self.n/self.n_iter) @property def is_done(self)->bool: "Return 'True' if schedule completed" return self.n >= self.n_iter # NOT TO BE MODIFIED class SmoothenValue(): "Create a smooth moving average for a value (loss, etc) using `beta`." def __init__(self, beta:float): self.beta,self.n,self.mov_avg = beta,0,0 def add_value(self, val:float)->None: "Add `val` to calculate updated smoothed value." self.n += 1 self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val self.smooth = self.mov_avg / (1 - self.beta ** self.n) # TO BE MODIFIED IN SOME CASES def lr_find(data_loader, model, loss_fn, opt, wd:int=0, start_lr:float=1e-7, end_lr:float=10, num_it:int=100, stop_div:bool=True, smooth_beta:float=0.98, use_gpu:bool=True, device=torch.device('cuda'), anneal_func=annealing_exp): """ The main function that you will call to plot learning_rate vs losses graph. It is the only function from lr_find.py that you will call. By default it will use GPU. It assumes your model is already on GPU if you use use_gpu. Arguments:- data_loader :- torch.utils.data.DataLoader model :- torch.nn.Module loss_fn :- torch.nn.LossFunction opt :- torch.optim.Optimizer wd :- weight decay (default=0). start_lr :- The learning rate from where to start in lr_find (default=1e-7) end_lr :- The learning rate at which to end lr_find (default=10) num_it :- Number of iterations for lr_find (default=100) stop_div :- If the loss diverges, then stop early (default=True) smooth_beta :- The beta value to smoothen the running avergae of the loss function (default=0.98) use_gpu :- True (train on GPU) else CPU anneal_func :- The step function you want to use (default exp) device :- Torch device to use for training model (default GPU) Returns: losses :- list of smoothened version of losses lrs :- list of all lrs that we test """ model.train() stop = False flag = False best_loss = 0. iteration = 0 losses = [] lrs = [] lrs.append(start_lr) start_lr = lr_range(model, start_lr) start_lr = np.array(start_lr) if isinstance(start_lr, (tuple, list)) else start_lr end_lr = lr_range(model, end_lr) end_lr = np.array(end_lr) if isinstance(end_lr, (tuple, list)) else end_lr sched = Stepper((start_lr, end_lr), num_it, anneal_func) smoothener = SmoothenValue(smooth_beta) epochs = int(np.ceil(num_it/len(data_loader))) # save model_dict model_state = model.state_dict() opt_state = opt.state_dict() # Set optimizer learning_rate = start_lr for group in opt.param_groups: group['lr'] = sched.start for i in range(epochs): for data in data_loader: opt.zero_grad() ################### TO BE MODIFIED ################### # Depending on your model, you will have to modify your # data pipeline and how you give inputs to your model. inputs, labels = data if use_gpu: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = loss_fn(outputs, labels) ##################################################### if use_gpu: smoothener.add_value(loss.detach().cpu()) else: smoothener.add_value(loss.detach()) smooth_loss = smoothener.smooth losses.append(smooth_loss) loss.backward() ################### TO BE MODIFIED ################### # For AdamW. If you want to use Adam, comment these lines for group in opt.param_groups: for param in group['params']: param.data = param.data.add(-wd * group['lr'], param.data) ##################################################### opt.step() # Change lr new_lr = sched.step() lrs.append(new_lr) for group in opt.param_groups: group['lr'] = new_lr ################### TO BE MODIFIED ################### # You necessarily don't want to change it. But in cases # when you are maximizing the loss, then you will have # to change it. if iteration == 0 or smooth_loss < best_loss: best_loss = smooth_loss iteration += 1 if sched.is_done or (stop_div and (smooth_loss > 4*best_loss or torch.isnan(loss))): flag = True break ##################################################### if iteration%10 == 0: print(f'Iteration: {iteration}') if flag: break # Load state dict model.load_state_dict(model_state) opt.load_state_dict(opt_state) lrs.pop() print(f'LR Finder is complete.') return losses, lrs # NOT TO BE MODIFIED def plot_lr_find(losses, lrs, skip_start:int=10, skip_end:int=5, suggestion:bool=False, return_fig:bool=None): """ It will take the losses and lrs returned by lr_find as input. Arguments:- skip_start -> It will skip skip_start lrs from the start skip_end -> It will skip skip_end lrs from the end suggestion -> If you want to see the point where the gradient changes most return_fig -> True then get the fig in the return statement """ lrs = lrs[skip_start:-skip_end] if skip_end > 0 else lrs[skip_start:] losses = losses[skip_start:-skip_end] if skip_end > 0 else losses[skip_start:] losses = [x.item() for x in losses] fig, ax = plt.subplots(1, 1) ax.plot(lrs, losses) ax.set_ylabel("Loss") ax.set_xlabel("Learning Rate") ax.set_xscale('log') ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0e')) if suggestion: try: mg = (np.gradient(np.array(losses))).argmin() except: print("Failed to compute the gradients, there might not be enough points.") return print(f"Min numerical gradient: {lrs[mg]:.2E}") ax.plot(lrs[mg], losses[mg], markersize=10, marker='o', color='red') if return_fig is not None: return fig
36.307692
115
0.601392
1,541
0.155468
0
0
121
0.012207
0
0
4,082
0.411824
bc85ba5181e5203592287503621708b994737b25
3,905
py
Python
SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
""" Test the lldb disassemble command on each call frame when stopped on C's ctor. """ from __future__ import print_function import os import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class IterateFrameAndDisassembleTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_and_run_command(self): """Disassemble each call frame when stopped on C's constructor.""" self.build() self.breakOnCtor() raw_output = self.res.GetOutput() frameRE = re.compile(r""" ^\s\sframe # heading for the frame info, .* # wildcard, and 0x[0-9a-f]{16} # the frame pc, and \sa.out`(.+) # module`function, and \s\+\s # the rest ' + ....' """, re.VERBOSE) for line in raw_output.split(os.linesep): match = frameRE.search(line) if match: function = match.group(1) #print("line:", line) #print("function:", function) self.runCmd("disassemble -n '%s'" % function) @add_test_categories(['pyapi']) def test_and_python_api(self): """Disassemble each call frame when stopped on C's constructor.""" self.build() self.breakOnCtor() # Now use the Python API to get at each function on the call stack and # disassemble it. target = self.dbg.GetSelectedTarget() process = target.GetProcess() thread = lldbutil.get_stopped_thread( process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) depth = thread.GetNumFrames() for i in range(depth - 1): frame = thread.GetFrameAtIndex(i) function = frame.GetFunction() # Print the function header. if self.TraceOn(): print() print(function) if function: # Get all instructions for this function and print them out. insts = function.GetInstructions(target) for inst in insts: # We could simply do 'print inst' to print out the disassembly. # But we want to print to stdout only if self.TraceOn() is # True. disasm = str(inst) if self.TraceOn(): print(disasm) def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. self.line = line_number('main.cpp', '// Set break point at this line.') def breakOnCtor(self): """Setup/run the program so it stops on C's constructor.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. bpno = lldbutil.run_break_set_by_file_and_line( self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, substrs=['stopped', 'stop reason = breakpoint %d.' % (bpno)]) # This test was failing because we fail to put the C:: in front of constructore. # We should maybe make another testcase to cover that specifically, but we shouldn't # fail this whole testcase for an inessential issue. # We should be stopped on the ctor function of class C. # self.expect("thread backtrace", BACKTRACE_DISPLAYED_CORRECTLY, # substrs = ['C::C'])
38.663366
92
0.56338
3,626
0.928553
0
0
1,302
0.333419
0
0
1,689
0.432522
bc87838b315ca1f64fa986f62a70ee610e20d306
1,116
py
Python
reservedwords.py
irinaid/MAlice
02740d661020866c3927b9ee7ee4523aaaafcb7e
[ "MIT" ]
1
2021-04-25T22:53:36.000Z
2021-04-25T22:53:36.000Z
reservedwords.py
irinaid/MAlice
02740d661020866c3927b9ee7ee4523aaaafcb7e
[ "MIT" ]
null
null
null
reservedwords.py
irinaid/MAlice
02740d661020866c3927b9ee7ee4523aaaafcb7e
[ "MIT" ]
null
null
null
''' All the reserved, individual words used in MAlice. ''' A = "a" ALICE = "Alice" AND = "and" ATE = "ate" BECAME = "became" BECAUSE = "because" BUT = "but" CLOSED = "closed" COMMA = "," CONTAINED = "contained" DOT = "." DRANK = "drank" EITHER = "either" ENOUGH = "enough" EVENTUALLY = "eventually" FOUND = "found" HAD = "had" HATTA = "hatta" LETTER = "letter" LOOKING_GLASS = "looking-glass" LPAR = "(" MAYBE = "maybe" NUMBER = "number" OF = "of" OPENED = "opened" OR = "or" PERHAPS = "perhaps" PIECE = "piece" QUESTION = "?" ROOM = "room" RPAR = ")" S = "'s" SAID = "said" SENTENCE = "sentence" SO = "so" SPIDER = "spider" SPOKE = "spoke" THE = "The" THEN = "then" TIMES = "times" TOO = "too" UNDERSCORE = "_" UNSURE = "unsure" WAS = "was" WHAT = "what" WHICH = "which" RESTRICTED = [ A, ALICE, AND, ATE, BECAME ,BECAUSE ,BUT ,CLOSED ,COMMA ,CONTAINED ,DOT ,DRANK ,EITHER ,ENOUGH ,EVENTUALLY ,FOUND ,HAD ,HATTA ,LETTER ,LOOKING_GLASS ,LPAR ,MAYBE ,NUMBER ,OF ,OPENED ,OR ,PERHAPS ,PIECE ,QUESTION ,ROOM ,RPAR ,S ,SAID, SENTENCE ,SO ,SPIDER ,SPOKE ,THE ,THEN ,TIMES ,TOO ,UNDERSCORE ,UNSURE ,WAS ,WHAT ,WHICH]
21.056604
338
0.638889
0
0
0
0
0
0
0
0
358
0.320789
bc88724609a6f077241f73613153365855b09321
853
py
Python
leetcode/0057_Insert_Interval/result.py
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0057_Insert_Interval/result.py
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0057_Insert_Interval/result.py
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
# !/usr/bin/env python3 # Author: C.K # Email: [email protected] # DateTime:2021-04-12 18:35:15 # Description: import os import sys class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: res, i = [], 0 for interval in intervals: if interval[1] < newInterval[0]: res.append(interval) elif interval[0] > newInterval[1]: res.append(newInterval) newInterval = interval elif interval[1] >= newInterval[0] or newInterval[1] >= interval[0]: newInterval = [ min(interval[0], newInterval[0]), max(interval[1], newInterval[1]) ] res.append(newInterval) return res if __name__ == "__main__": pass
24.371429
80
0.534584
681
0.798359
0
0
0
0
0
0
114
0.133646
bc889aea13c53b5ac47e25b4727f37433f19b834
322
py
Python
src/pymortests/benchmarks.py
TiKeil/pymor
5c6b3b6e1714b5ede11ce7cf03399780ab29d252
[ "Unlicense" ]
1
2021-08-17T15:55:12.000Z
2021-08-17T15:55:12.000Z
src/pymortests/benchmarks.py
TreeerT/pymor
e8b18d2d4c4b5998f0bd84f6728e365e0693b753
[ "Unlicense" ]
4
2022-03-17T10:07:38.000Z
2022-03-30T12:41:06.000Z
src/pymortests/benchmarks.py
TreeerT/pymor
e8b18d2d4c4b5998f0bd84f6728e365e0693b753
[ "Unlicense" ]
null
null
null
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2020 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymortests.base import runmodule if __name__ == "__main__": runmodule(filename=__file__)
32.2
77
0.76087
0
0
0
0
0
0
0
0
228
0.708075
bc89b98301ba0f533627b829ae7b31f9ab29c245
756
py
Python
storage3/_sync/client.py
anand2312/storage-py
75c9c43ea373cb58970255b8e7438c2ec67e7f25
[ "MIT" ]
null
null
null
storage3/_sync/client.py
anand2312/storage-py
75c9c43ea373cb58970255b8e7438c2ec67e7f25
[ "MIT" ]
null
null
null
storage3/_sync/client.py
anand2312/storage-py
75c9c43ea373cb58970255b8e7438c2ec67e7f25
[ "MIT" ]
null
null
null
from ..utils import SyncClient, __version__ from .bucket import SyncStorageBucketAPI from .file_api import SyncBucketProxy __all__ = [ "SyncStorageClient", ] class SyncStorageClient(SyncStorageBucketAPI): """Manage storage buckets and files.""" def __init__(self, url: str, headers: dict[str, str]) -> None: super().__init__( url, {"User-Agent": f"supabase-py/storage3 v{__version__}", **headers}, SyncClient(), ) def from_(self, id: str) -> SyncBucketProxy: """Run a storage file operation. Parameters ---------- id The unique identifier of the bucket """ return SyncBucketProxy(id, self.url, self.headers, self._client)
26.068966
78
0.613757
590
0.780423
0
0
0
0
0
0
250
0.330688
bc8a0406013c9abeb99153a42725a7e4225fc35e
1,755
py
Python
repo/script.module.liveresolver/lib/js2py/translators/__init__.py
Hades01/Addons
710da97ac850197498a3cd64be1811c593610add
[ "Apache-2.0" ]
3
2020-03-03T13:21:44.000Z
2021-07-21T09:53:31.000Z
repo/script.module.liveresolver/lib/js2py/translators/__init__.py
Hades01/Addons
710da97ac850197498a3cd64be1811c593610add
[ "Apache-2.0" ]
null
null
null
repo/script.module.liveresolver/lib/js2py/translators/__init__.py
Hades01/Addons
710da97ac850197498a3cd64be1811c593610add
[ "Apache-2.0" ]
2
2020-04-01T22:11:12.000Z
2020-05-07T23:54:52.000Z
# The MIT License # # Copyright 2014, 2015 Piotr Dabkowski # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the 'Software'), # to deal in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, subject # to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE __all__ = ['PyJsParser', 'Node', 'WrappingNode', 'node_to_dict', 'parse', 'translate_js', 'translate', 'syntax_tree_translate', 'DEFAULT_HEADER'] __author__ = 'Piotr Dabkowski' __version__ = '2.2.0' from pyjsparser import PyJsParser, Node, WrappingNode, node_to_dict from translator import translate_js, trasnlate, syntax_tree_translate, DEFAULT_HEADER def parse(javascript_code): """Returns syntax tree of javascript_code. Syntax tree has the same structure as syntax tree produced by esprima.js Same as PyJsParser().parse For your convenience :) """ p = PyJsParser() return p.parse(javascript_code)
45
127
0.764672
0
0
0
0
0
0
0
0
1,418
0.807977
bc8acb8ede34bacdf376a2fc95f5b2c7c78ede61
141,721
py
Python
src/test/python/test_scc_pacs.py
xchange11/ttconv-1
6e67172af126fa0e90690044848f300c0173715c
[ "BSD-2-Clause" ]
66
2020-09-25T11:38:28.000Z
2022-03-23T15:15:34.000Z
src/test/python/test_scc_pacs.py
xchange11/ttconv-1
6e67172af126fa0e90690044848f300c0173715c
[ "BSD-2-Clause" ]
217
2020-09-22T22:45:22.000Z
2022-03-31T23:02:15.000Z
src/test/python/test_scc_pacs.py
xchange11/ttconv-1
6e67172af126fa0e90690044848f300c0173715c
[ "BSD-2-Clause" ]
5
2020-09-25T09:24:17.000Z
2021-08-08T20:52:26.000Z
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2020, Sandflow Consulting LLC # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit tests for the SCC PACs""" # pylint: disable=R0201,C0115,C0116 import unittest from ttconv.scc.codes.preambles_address_codes import SccPreambleAddressCode from ttconv.style_properties import TextDecorationType, NamedColors, FontStyleType class SCCPreambleAddressCodesTest(unittest.TestCase): def test_scc_pac_values(self): channel_1_byte_1 = [0x11, 0x12, 0x15, 0x16, 0x17, 0x10, 0x13, 0x14] channel_2_byte_1 = [0x19, 0x1A, 0x1D, 0x1E, 0x1F, 0x18, 0x1B, 0x1C] all_range = list(range(0x00, 0XFF)) byte_2_range = range(0x40, 0x80) other_bytes_1 = [item for item in all_range if item not in channel_1_byte_1 and item not in channel_2_byte_1] other_bytes_2 = [item for item in all_range if item not in list(byte_2_range)] for b1 in channel_1_byte_1: for b2 in byte_2_range: pac = SccPreambleAddressCode.find(b1, b2) if b2 > 0x5F and b1 % 0x08 == 0: # row 11 case self.assertIsNone(pac) else: self.assertIsNotNone(pac) for b2 in other_bytes_2: self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) for b1 in channel_2_byte_1: for b2 in byte_2_range: pac = SccPreambleAddressCode.find(b1, b2) if b2 > 0x5F and b1 % 0x08 == 0: # row 11 case self.assertIsNone(pac) else: self.assertIsNotNone(pac) for b2 in other_bytes_2: self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) for b1 in other_bytes_1: for b2 in range(0x00, 0xFF): self.assertIsNone(SccPreambleAddressCode.find(b1, b2)) def check_scc_pac_attributes(self, pac, channel, row, indent, color, font_style, text_decoration): self.assertEqual(channel, pac.get_channel()) self.assertEqual(row, pac.get_row()) self.assertEqual(indent, pac.get_indent()) self.assertEqual(color, pac.get_color()) self.assertEqual(font_style, pac.get_font_style()) self.assertEqual(text_decoration, pac.get_text_decoration()) def test_scc_pac_white(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x40), 1, 1, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x60), 1, 2, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x40), 1, 3, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x60), 1, 4, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x40), 1, 5, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x60), 1, 6, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x40), 1, 7, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x60), 1, 8, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x40), 1, 9, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x60), 1, 10, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x40), 1, 11, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x40), 1, 12, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x60), 1, 13, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x40), 1, 14, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x60), 1, 15, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x40), 2, 1, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x60), 2, 2, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x40), 2, 3, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x60), 2, 4, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x40), 2, 5, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x60), 2, 6, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x40), 2, 7, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x60), 2, 8, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x40), 2, 9, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x60), 2, 10, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x40), 2, 11, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x40), 2, 12, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x60), 2, 13, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x40), 2, 14, None, NamedColors.white.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x60), 2, 15, None, NamedColors.white.value, None, None) def test_scc_pac_white_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x41), 1, 1, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x61), 1, 2, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x41), 1, 3, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x61), 1, 4, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x41), 1, 5, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x61), 1, 6, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x41), 1, 7, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x61), 1, 8, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x41), 1, 9, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x61), 1, 10, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x41), 1, 11, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x41), 1, 12, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x61), 1, 13, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x41), 1, 14, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x61), 1, 15, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x41), 2, 1, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x61), 2, 2, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x41), 2, 3, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x61), 2, 4, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x41), 2, 5, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x61), 2, 6, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x41), 2, 7, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x61), 2, 8, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x41), 2, 9, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x61), 2, 10, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x41), 2, 11, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x41), 2, 12, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x61), 2, 13, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x41), 2, 14, None, NamedColors.white.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x61), 2, 15, None, NamedColors.white.value, None, TextDecorationType(underline=True)) def test_scc_pac_green(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x42), 1, 1, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x62), 1, 2, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x42), 1, 3, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x62), 1, 4, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x42), 1, 5, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x62), 1, 6, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x42), 1, 7, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x62), 1, 8, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x42), 1, 9, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x62), 1, 10, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x42), 1, 11, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x42), 1, 12, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x62), 1, 13, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x42), 1, 14, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x62), 1, 15, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x42), 2, 1, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x62), 2, 2, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x42), 2, 3, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x62), 2, 4, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x42), 2, 5, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x62), 2, 6, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x42), 2, 7, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x62), 2, 8, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x42), 2, 9, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x62), 2, 10, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x42), 2, 11, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x42), 2, 12, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x62), 2, 13, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x42), 2, 14, None, NamedColors.green.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x62), 2, 15, None, NamedColors.green.value, None, None) def test_scc_pac_green_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x43), 1, 1, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x63), 1, 2, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x43), 1, 3, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x63), 1, 4, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x43), 1, 5, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x63), 1, 6, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x43), 1, 7, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x63), 1, 8, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x43), 1, 9, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x63), 1, 10, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x43), 1, 11, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x43), 1, 12, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x63), 1, 13, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x43), 1, 14, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x63), 1, 15, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x43), 2, 1, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x63), 2, 2, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x43), 2, 3, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x63), 2, 4, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x43), 2, 5, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x63), 2, 6, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x43), 2, 7, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x63), 2, 8, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x43), 2, 9, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x63), 2, 10, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x43), 2, 11, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x43), 2, 12, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x63), 2, 13, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x43), 2, 14, None, NamedColors.green.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x63), 2, 15, None, NamedColors.green.value, None, TextDecorationType(underline=True)) def test_scc_pac_blue(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x44), 1, 1, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x64), 1, 2, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x44), 1, 3, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x64), 1, 4, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x44), 1, 5, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x64), 1, 6, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x44), 1, 7, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x64), 1, 8, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x44), 1, 9, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x64), 1, 10, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x44), 1, 11, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x44), 1, 12, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x64), 1, 13, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x44), 1, 14, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x64), 1, 15, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x44), 2, 1, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x64), 2, 2, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x44), 2, 3, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x64), 2, 4, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x44), 2, 5, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x64), 2, 6, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x44), 2, 7, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x64), 2, 8, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x44), 2, 9, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x64), 2, 10, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x44), 2, 11, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x44), 2, 12, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x64), 2, 13, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x44), 2, 14, None, NamedColors.blue.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x64), 2, 15, None, NamedColors.blue.value, None, None) def test_scc_pac_blue_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x45), 1, 1, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x65), 1, 2, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x45), 1, 3, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x65), 1, 4, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x45), 1, 5, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x65), 1, 6, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x45), 1, 7, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x65), 1, 8, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x45), 1, 9, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x65), 1, 10, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x45), 1, 11, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x45), 1, 12, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x65), 1, 13, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x45), 1, 14, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x65), 1, 15, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x45), 2, 1, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x65), 2, 2, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x45), 2, 3, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x65), 2, 4, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x45), 2, 5, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x65), 2, 6, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x45), 2, 7, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x65), 2, 8, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x45), 2, 9, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x65), 2, 10, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x45), 2, 11, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x45), 2, 12, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x65), 2, 13, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x45), 2, 14, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x65), 2, 15, None, NamedColors.blue.value, None, TextDecorationType(underline=True)) def test_scc_pac_cyan(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x46), 1, 1, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x66), 1, 2, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x46), 1, 3, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x66), 1, 4, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x46), 1, 5, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x66), 1, 6, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x46), 1, 7, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x66), 1, 8, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x46), 1, 9, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x66), 1, 10, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x46), 1, 11, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x46), 1, 12, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x66), 1, 13, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x46), 1, 14, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x66), 1, 15, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x46), 2, 1, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x66), 2, 2, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x46), 2, 3, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x66), 2, 4, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x46), 2, 5, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x66), 2, 6, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x46), 2, 7, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x66), 2, 8, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x46), 2, 9, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x66), 2, 10, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x46), 2, 11, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x46), 2, 12, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x66), 2, 13, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x46), 2, 14, None, NamedColors.cyan.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x66), 2, 15, None, NamedColors.cyan.value, None, None) def test_scc_pac_cyan_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x47), 1, 1, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x67), 1, 2, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x47), 1, 3, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x67), 1, 4, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x47), 1, 5, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x67), 1, 6, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x47), 1, 7, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x67), 1, 8, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x47), 1, 9, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x67), 1, 10, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x47), 1, 11, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x47), 1, 12, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x67), 1, 13, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x47), 1, 14, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x67), 1, 15, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x47), 2, 1, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x67), 2, 2, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x47), 2, 3, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x67), 2, 4, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x47), 2, 5, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x67), 2, 6, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x47), 2, 7, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x67), 2, 8, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x47), 2, 9, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x67), 2, 10, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x47), 2, 11, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x47), 2, 12, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x67), 2, 13, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x47), 2, 14, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x67), 2, 15, None, NamedColors.cyan.value, None, TextDecorationType(underline=True)) def test_scc_pac_red(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x48), 1, 1, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x68), 1, 2, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x48), 1, 3, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x68), 1, 4, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x48), 1, 5, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x68), 1, 6, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x48), 1, 7, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x68), 1, 8, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x48), 1, 9, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x68), 1, 10, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x48), 1, 11, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x48), 1, 12, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x68), 1, 13, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x48), 1, 14, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x68), 1, 15, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x48), 2, 1, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x68), 2, 2, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x48), 2, 3, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x68), 2, 4, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x48), 2, 5, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x68), 2, 6, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x48), 2, 7, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x68), 2, 8, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x48), 2, 9, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x68), 2, 10, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x48), 2, 11, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x48), 2, 12, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x68), 2, 13, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x48), 2, 14, None, NamedColors.red.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x68), 2, 15, None, NamedColors.red.value, None, None) def test_scc_pac_red_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x49), 1, 1, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x69), 1, 2, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x49), 1, 3, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x69), 1, 4, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x49), 1, 5, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x69), 1, 6, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x49), 1, 7, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x69), 1, 8, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x49), 1, 9, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x69), 1, 10, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x49), 1, 11, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x49), 1, 12, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x69), 1, 13, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x49), 1, 14, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x69), 1, 15, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x49), 2, 1, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x69), 2, 2, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x49), 2, 3, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x69), 2, 4, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x49), 2, 5, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x69), 2, 6, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x49), 2, 7, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x69), 2, 8, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x49), 2, 9, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x69), 2, 10, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x49), 2, 11, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x49), 2, 12, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x69), 2, 13, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x49), 2, 14, None, NamedColors.red.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x69), 2, 15, None, NamedColors.red.value, None, TextDecorationType(underline=True)) def test_scc_pac_yellow(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4A), 1, 1, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6A), 1, 2, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4A), 1, 3, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6A), 1, 4, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4A), 1, 5, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6A), 1, 6, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4A), 1, 7, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6A), 1, 8, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4A), 1, 9, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6A), 1, 10, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4A), 1, 11, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4A), 1, 12, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6A), 1, 13, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4A), 1, 14, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6A), 1, 15, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4A), 2, 1, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6A), 2, 2, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4A), 2, 3, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6A), 2, 4, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4A), 2, 5, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6A), 2, 6, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4A), 2, 7, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6A), 2, 8, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4A), 2, 9, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6A), 2, 10, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4A), 2, 11, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4A), 2, 12, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6A), 2, 13, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4A), 2, 14, None, NamedColors.yellow.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6A), 2, 15, None, NamedColors.yellow.value, None, None) def test_scc_pac_yellow_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4B), 1, 1, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6B), 1, 2, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4B), 1, 3, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6B), 1, 4, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4B), 1, 5, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6B), 1, 6, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4B), 1, 7, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6B), 1, 8, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4B), 1, 9, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6B), 1, 10, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4B), 1, 11, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4B), 1, 12, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6B), 1, 13, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4B), 1, 14, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6B), 1, 15, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4B), 2, 1, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6B), 2, 2, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4B), 2, 3, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6B), 2, 4, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4B), 2, 5, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6B), 2, 6, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4B), 2, 7, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6B), 2, 8, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4B), 2, 9, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6B), 2, 10, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4B), 2, 11, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4B), 2, 12, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6B), 2, 13, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4B), 2, 14, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6B), 2, 15, None, NamedColors.yellow.value, None, TextDecorationType(underline=True)) def test_scc_pac_magenta(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4C), 1, 1, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6C), 1, 2, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4C), 1, 3, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6C), 1, 4, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4C), 1, 5, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6C), 1, 6, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4C), 1, 7, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6C), 1, 8, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4C), 1, 9, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6C), 1, 10, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4C), 1, 11, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4C), 1, 12, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6C), 1, 13, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4C), 1, 14, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6C), 1, 15, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4C), 2, 1, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6C), 2, 2, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4C), 2, 3, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6C), 2, 4, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4C), 2, 5, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6C), 2, 6, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4C), 2, 7, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6C), 2, 8, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4C), 2, 9, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6C), 2, 10, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4C), 2, 11, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4C), 2, 12, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6C), 2, 13, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4C), 2, 14, None, NamedColors.magenta.value, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6C), 2, 15, None, NamedColors.magenta.value, None, None) def test_scc_pac_magenta_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4D), 1, 1, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6D), 1, 2, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4D), 1, 3, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6D), 1, 4, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4D), 1, 5, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6D), 1, 6, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4D), 1, 7, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6D), 1, 8, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4D), 1, 9, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6D), 1, 10, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4D), 1, 11, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4D), 1, 12, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6D), 1, 13, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4D), 1, 14, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6D), 1, 15, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4D), 2, 1, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6D), 2, 2, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4D), 2, 3, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6D), 2, 4, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4D), 2, 5, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6D), 2, 6, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4D), 2, 7, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6D), 2, 8, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4D), 2, 9, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6D), 2, 10, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4D), 2, 11, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4D), 2, 12, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6D), 2, 13, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4D), 2, 14, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6D), 2, 15, None, NamedColors.magenta.value, None, TextDecorationType(underline=True)) def test_scc_pac_white_italics(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4E), 1, 1, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6E), 1, 2, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4E), 1, 3, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6E), 1, 4, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4E), 1, 5, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6E), 1, 6, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4E), 1, 7, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6E), 1, 8, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4E), 1, 9, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6E), 1, 10, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4E), 1, 11, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4E), 1, 12, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6E), 1, 13, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4E), 1, 14, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6E), 1, 15, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4E), 2, 1, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6E), 2, 2, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4E), 2, 3, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6E), 2, 4, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4E), 2, 5, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6E), 2, 6, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4E), 2, 7, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6E), 2, 8, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4E), 2, 9, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6E), 2, 10, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4E), 2, 11, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4E), 2, 12, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6E), 2, 13, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4E), 2, 14, None, NamedColors.white.value, FontStyleType.italic, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6E), 2, 15, None, NamedColors.white.value, FontStyleType.italic, None) def test_scc_pac_white_italics_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x4F), 1, 1, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x6F), 1, 2, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x4F), 1, 3, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x6F), 1, 4, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x4F), 1, 5, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x6F), 1, 6, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x4F), 1, 7, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x6F), 1, 8, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x4F), 1, 9, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x6F), 1, 10, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x4F), 1, 11, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x4F), 1, 12, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x6F), 1, 13, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x4F), 1, 14, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x6F), 1, 15, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x4F), 2, 1, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x6F), 2, 2, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x4F), 2, 3, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x6F), 2, 4, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x4F), 2, 5, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x6F), 2, 6, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x4F), 2, 7, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x6F), 2, 8, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x4F), 2, 9, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x6F), 2, 10, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x4F), 2, 11, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x4F), 2, 12, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x6F), 2, 13, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x4F), 2, 14, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x6F), 2, 15, None, NamedColors.white.value, FontStyleType.italic, TextDecorationType(underline=True)) def test_scc_pac_indent_0(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x50), 1, 1, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x70), 1, 2, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x50), 1, 3, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x70), 1, 4, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x50), 1, 5, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x70), 1, 6, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x50), 1, 7, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x70), 1, 8, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x50), 1, 9, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x70), 1, 10, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x50), 1, 11, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x50), 1, 12, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x70), 1, 13, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x50), 1, 14, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x70), 1, 15, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x50), 2, 1, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x70), 2, 2, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x50), 2, 3, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x70), 2, 4, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x50), 2, 5, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x70), 2, 6, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x50), 2, 7, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x70), 2, 8, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x50), 2, 9, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x70), 2, 10, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x50), 2, 11, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x50), 2, 12, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x70), 2, 13, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x50), 2, 14, 0, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x70), 2, 15, 0, None, None, None) def test_scc_pac_indent_0_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x51), 1, 1, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x71), 1, 2, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x51), 1, 3, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x71), 1, 4, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x51), 1, 5, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x71), 1, 6, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x51), 1, 7, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x71), 1, 8, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x51), 1, 9, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x71), 1, 10, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x51), 1, 11, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x51), 1, 12, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x71), 1, 13, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x51), 1, 14, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x71), 1, 15, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x51), 2, 1, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x71), 2, 2, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x51), 2, 3, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x71), 2, 4, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x51), 2, 5, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x71), 2, 6, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x51), 2, 7, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x71), 2, 8, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x51), 2, 9, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x71), 2, 10, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x51), 2, 11, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x51), 2, 12, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x71), 2, 13, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x51), 2, 14, 0, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x71), 2, 15, 0, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_4(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x52), 1, 1, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x72), 1, 2, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x52), 1, 3, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x72), 1, 4, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x52), 1, 5, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x72), 1, 6, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x52), 1, 7, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x72), 1, 8, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x52), 1, 9, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x72), 1, 10, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x52), 1, 11, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x52), 1, 12, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x72), 1, 13, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x52), 1, 14, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x72), 1, 15, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x52), 2, 1, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x72), 2, 2, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x52), 2, 3, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x72), 2, 4, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x52), 2, 5, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x72), 2, 6, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x52), 2, 7, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x72), 2, 8, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x52), 2, 9, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x72), 2, 10, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x52), 2, 11, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x52), 2, 12, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x72), 2, 13, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x52), 2, 14, 4, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x72), 2, 15, 4, None, None, None) def test_scc_pac_indent_4_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x53), 1, 1, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x73), 1, 2, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x53), 1, 3, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x73), 1, 4, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x53), 1, 5, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x73), 1, 6, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x53), 1, 7, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x73), 1, 8, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x53), 1, 9, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x73), 1, 10, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x53), 1, 11, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x53), 1, 12, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x73), 1, 13, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x53), 1, 14, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x73), 1, 15, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x53), 2, 1, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x73), 2, 2, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x53), 2, 3, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x73), 2, 4, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x53), 2, 5, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x73), 2, 6, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x53), 2, 7, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x73), 2, 8, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x53), 2, 9, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x73), 2, 10, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x53), 2, 11, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x53), 2, 12, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x73), 2, 13, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x53), 2, 14, 4, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x73), 2, 15, 4, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_8(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x54), 1, 1, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x74), 1, 2, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x54), 1, 3, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x74), 1, 4, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x54), 1, 5, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x74), 1, 6, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x54), 1, 7, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x74), 1, 8, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x54), 1, 9, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x74), 1, 10, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x54), 1, 11, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x54), 1, 12, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x74), 1, 13, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x54), 1, 14, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x74), 1, 15, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x54), 2, 1, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x74), 2, 2, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x54), 2, 3, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x74), 2, 4, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x54), 2, 5, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x74), 2, 6, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x54), 2, 7, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x74), 2, 8, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x54), 2, 9, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x74), 2, 10, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x54), 2, 11, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x54), 2, 12, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x74), 2, 13, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x54), 2, 14, 8, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x74), 2, 15, 8, None, None, None) def test_scc_pac_indent_8_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x55), 1, 1, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x75), 1, 2, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x55), 1, 3, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x75), 1, 4, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x55), 1, 5, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x75), 1, 6, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x55), 1, 7, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x75), 1, 8, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x55), 1, 9, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x75), 1, 10, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x55), 1, 11, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x55), 1, 12, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x75), 1, 13, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x55), 1, 14, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x75), 1, 15, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x55), 2, 1, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x75), 2, 2, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x55), 2, 3, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x75), 2, 4, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x55), 2, 5, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x75), 2, 6, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x55), 2, 7, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x75), 2, 8, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x55), 2, 9, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x75), 2, 10, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x55), 2, 11, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x55), 2, 12, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x75), 2, 13, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x55), 2, 14, 8, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x75), 2, 15, 8, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_12(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x56), 1, 1, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x76), 1, 2, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x56), 1, 3, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x76), 1, 4, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x56), 1, 5, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x76), 1, 6, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x56), 1, 7, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x76), 1, 8, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x56), 1, 9, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x76), 1, 10, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x56), 1, 11, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x56), 1, 12, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x76), 1, 13, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x56), 1, 14, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x76), 1, 15, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x56), 2, 1, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x76), 2, 2, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x56), 2, 3, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x76), 2, 4, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x56), 2, 5, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x76), 2, 6, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x56), 2, 7, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x76), 2, 8, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x56), 2, 9, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x76), 2, 10, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x56), 2, 11, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x56), 2, 12, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x76), 2, 13, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x56), 2, 14, 12, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x76), 2, 15, 12, None, None, None) def test_scc_pac_indent_12_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x57), 1, 1, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x77), 1, 2, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x57), 1, 3, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x77), 1, 4, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x57), 1, 5, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x77), 1, 6, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x57), 1, 7, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x77), 1, 8, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x57), 1, 9, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x77), 1, 10, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x57), 1, 11, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x57), 1, 12, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x77), 1, 13, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x57), 1, 14, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x77), 1, 15, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x57), 2, 1, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x77), 2, 2, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x57), 2, 3, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x77), 2, 4, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x57), 2, 5, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x77), 2, 6, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x57), 2, 7, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x77), 2, 8, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x57), 2, 9, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x77), 2, 10, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x57), 2, 11, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x57), 2, 12, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x77), 2, 13, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x57), 2, 14, 12, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x77), 2, 15, 12, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_16(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x58), 1, 1, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x78), 1, 2, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x58), 1, 3, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x78), 1, 4, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x58), 1, 5, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x78), 1, 6, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x58), 1, 7, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x78), 1, 8, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x58), 1, 9, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x78), 1, 10, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x58), 1, 11, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x58), 1, 12, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x78), 1, 13, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x58), 1, 14, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x78), 1, 15, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x58), 2, 1, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x78), 2, 2, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x58), 2, 3, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x78), 2, 4, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x58), 2, 5, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x78), 2, 6, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x58), 2, 7, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x78), 2, 8, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x58), 2, 9, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x78), 2, 10, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x58), 2, 11, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x58), 2, 12, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x78), 2, 13, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x58), 2, 14, 16, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x78), 2, 15, 16, None, None, None) def test_scc_pac_indent_16_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x59), 1, 1, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x79), 1, 2, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x59), 1, 3, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x79), 1, 4, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x59), 1, 5, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x79), 1, 6, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x59), 1, 7, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x79), 1, 8, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x59), 1, 9, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x79), 1, 10, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x59), 1, 11, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x59), 1, 12, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x79), 1, 13, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x59), 1, 14, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x79), 1, 15, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x59), 2, 1, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x79), 2, 2, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x59), 2, 3, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x79), 2, 4, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x59), 2, 5, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x79), 2, 6, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x59), 2, 7, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x79), 2, 8, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x59), 2, 9, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x79), 2, 10, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x59), 2, 11, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x59), 2, 12, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x79), 2, 13, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x59), 2, 14, 16, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x79), 2, 15, 16, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_20(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5A), 1, 1, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7A), 1, 2, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5A), 1, 3, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7A), 1, 4, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5A), 1, 5, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7A), 1, 6, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5A), 1, 7, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7A), 1, 8, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5A), 1, 9, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7A), 1, 10, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5A), 1, 11, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5A), 1, 12, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7A), 1, 13, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5A), 1, 14, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7A), 1, 15, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5A), 2, 1, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7A), 2, 2, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5A), 2, 3, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7A), 2, 4, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5A), 2, 5, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7A), 2, 6, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5A), 2, 7, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7A), 2, 8, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5A), 2, 9, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7A), 2, 10, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5A), 2, 11, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5A), 2, 12, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7A), 2, 13, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5A), 2, 14, 20, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7A), 2, 15, 20, None, None, None) def test_scc_pac_indent_20_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5B), 1, 1, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7B), 1, 2, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5B), 1, 3, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7B), 1, 4, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5B), 1, 5, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7B), 1, 6, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5B), 1, 7, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7B), 1, 8, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5B), 1, 9, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7B), 1, 10, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5B), 1, 11, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5B), 1, 12, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7B), 1, 13, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5B), 1, 14, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7B), 1, 15, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5B), 2, 1, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7B), 2, 2, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5B), 2, 3, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7B), 2, 4, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5B), 2, 5, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7B), 2, 6, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5B), 2, 7, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7B), 2, 8, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5B), 2, 9, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7B), 2, 10, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5B), 2, 11, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5B), 2, 12, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7B), 2, 13, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5B), 2, 14, 20, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7B), 2, 15, 20, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_24(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5C), 1, 1, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7C), 1, 2, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5C), 1, 3, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7C), 1, 4, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5C), 1, 5, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7C), 1, 6, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5C), 1, 7, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7C), 1, 8, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5C), 1, 9, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7C), 1, 10, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5C), 1, 11, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5C), 1, 12, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7C), 1, 13, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5C), 1, 14, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7C), 1, 15, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5C), 2, 1, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7C), 2, 2, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5C), 2, 3, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7C), 2, 4, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5C), 2, 5, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7C), 2, 6, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5C), 2, 7, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7C), 2, 8, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5C), 2, 9, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7C), 2, 10, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5C), 2, 11, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5C), 2, 12, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7C), 2, 13, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5C), 2, 14, 24, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7C), 2, 15, 24, None, None, None) def test_scc_pac_indent_24_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5D), 1, 1, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7D), 1, 2, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5D), 1, 3, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7D), 1, 4, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5D), 1, 5, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7D), 1, 6, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5D), 1, 7, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7D), 1, 8, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5D), 1, 9, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7D), 1, 10, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5D), 1, 11, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5D), 1, 12, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7D), 1, 13, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5D), 1, 14, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7D), 1, 15, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5D), 2, 1, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7D), 2, 2, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5D), 2, 3, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7D), 2, 4, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5D), 2, 5, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7D), 2, 6, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5D), 2, 7, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7D), 2, 8, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5D), 2, 9, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7D), 2, 10, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5D), 2, 11, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5D), 2, 12, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7D), 2, 13, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5D), 2, 14, 24, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7D), 2, 15, 24, None, None, TextDecorationType(underline=True)) def test_scc_pac_indent_28(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5E), 1, 1, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7E), 1, 2, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5E), 1, 3, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7E), 1, 4, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5E), 1, 5, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7E), 1, 6, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5E), 1, 7, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7E), 1, 8, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5E), 1, 9, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7E), 1, 10, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5E), 1, 11, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5E), 1, 12, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7E), 1, 13, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5E), 1, 14, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7E), 1, 15, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5E), 2, 1, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7E), 2, 2, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5E), 2, 3, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7E), 2, 4, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5E), 2, 5, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7E), 2, 6, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5E), 2, 7, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7E), 2, 8, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5E), 2, 9, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7E), 2, 10, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5E), 2, 11, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5E), 2, 12, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7E), 2, 13, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5E), 2, 14, 28, None, None, None) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7E), 2, 15, 28, None, None, None) def test_scc_pac_indent_28_underline(self): self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x5F), 1, 1, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x11, 0x7F), 1, 2, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x5F), 1, 3, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x12, 0x7F), 1, 4, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x5F), 1, 5, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x15, 0x7F), 1, 6, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x5F), 1, 7, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x16, 0x7F), 1, 8, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x5F), 1, 9, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x17, 0x7F), 1, 10, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x10, 0x5F), 1, 11, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x5F), 1, 12, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x13, 0x7F), 1, 13, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x5F), 1, 14, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x14, 0x7F), 1, 15, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x5F), 2, 1, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x19, 0x7F), 2, 2, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x5F), 2, 3, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1A, 0x7F), 2, 4, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x5F), 2, 5, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1D, 0x7F), 2, 6, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x5F), 2, 7, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1E, 0x7F), 2, 8, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x5F), 2, 9, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1F, 0x7F), 2, 10, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x18, 0x5F), 2, 11, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x5F), 2, 12, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1B, 0x7F), 2, 13, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x5F), 2, 14, 28, None, None, TextDecorationType(underline=True)) self.check_scc_pac_attributes(SccPreambleAddressCode(0x1C, 0x7F), 2, 15, 28, None, None, TextDecorationType(underline=True)) if __name__ == '__main__': unittest.main()
87.374229
129
0.689333
140,048
0.988195
0
0
0
0
0
0
1,454
0.01026
bc8adf2af330cf7308b0b0e25463ed5a44b45099
1,484
py
Python
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/custom_image_properties_custom.py
NMijat1024/azure-sdk-for-python
c49e1d6d797dceaca81813cafb1a486d67185182
[ "MIT" ]
1
2022-03-30T22:39:15.000Z
2022-03-30T22:39:15.000Z
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/custom_image_properties_custom.py
NMijat1024/azure-sdk-for-python
c49e1d6d797dceaca81813cafb1a486d67185182
[ "MIT" ]
54
2016-03-25T17:25:01.000Z
2018-10-22T17:27:54.000Z
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/custom_image_properties_custom.py
NMijat1024/azure-sdk-for-python
c49e1d6d797dceaca81813cafb1a486d67185182
[ "MIT" ]
2
2017-01-20T18:25:46.000Z
2017-05-12T21:31:47.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class CustomImagePropertiesCustom(Model): """Properties for creating a custom image from a VHD. :param image_name: The image name. :type image_name: str :param sys_prep: Indicates whether sysprep has been run on the VHD. :type sys_prep: bool :param os_type: The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows', 'Linux', 'None' :type os_type: str or ~azure.mgmt.devtestlabs.models.CustomImageOsType """ _validation = { 'os_type': {'required': True}, } _attribute_map = { 'image_name': {'key': 'imageName', 'type': 'str'}, 'sys_prep': {'key': 'sysPrep', 'type': 'bool'}, 'os_type': {'key': 'osType', 'type': 'str'}, } def __init__(self, os_type, image_name=None, sys_prep=None): super(CustomImagePropertiesCustom, self).__init__() self.image_name = image_name self.sys_prep = sys_prep self.os_type = os_type
35.333333
76
0.6031
968
0.652291
0
0
0
0
0
0
1,021
0.688005
bc8c55932d28aa8c9253fefe76b11ab1d6dbc13a
1,886
py
Python
distance_torch_no_compile/chamfer.py
nicolalandro/softpool
ca77161ab70e5fe6c6505dc40f448bd8e1d78a48
[ "Apache-2.0" ]
null
null
null
distance_torch_no_compile/chamfer.py
nicolalandro/softpool
ca77161ab70e5fe6c6505dc40f448bd8e1d78a48
[ "Apache-2.0" ]
null
null
null
distance_torch_no_compile/chamfer.py
nicolalandro/softpool
ca77161ab70e5fe6c6505dc40f448bd8e1d78a48
[ "Apache-2.0" ]
null
null
null
import torch def expanded_pairwise_distances(x, y): ''' Input: x is a bxNxd matrix y is an optional bxMxd matirx Output: dist is a bxNxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:] if y is not given then use 'y=x'. i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2 ''' differences = x.unsqueeze(2) - y.unsqueeze(1) distances = torch.sum(differences * differences, -1) return distances def chamfer_distance(x, y): ''' input x and y are bxNxM matrix, b: batch, N:number of point, M: point dim (ex. 2 for 2D or 3 for 3D) output is a bx1 Matrix with the value of the chamfer distance for each sample of the batch ''' dist_vec = expanded_pairwise_distances(x, y) min_distances = torch.topk(dist_vec, k=1, dim=2, largest=False).values chamfer = torch.sum(min_distances, dim=1) / torch.tensor(x.shape[1]) return chamfer class ChamferLoss(torch.nn.Module): def forward(self, x, y): chamfer = chamfer_distance(x, y) return torch.sum(chamfer) if __name__ == "__main__": x = torch.tensor([ [ [0., 0., 0.], [0., 1., 0.], [0., 1., 0.], ], [ [1., 1., 0.], [1., 2., 0.], [0., 1., 0.], ] ]) y = torch.tensor([ [ [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], ], [ [1., 1., 0.], [1., 2., 0.], [0., 1., 0.], ] ]) chamfer = ChamferLoss() print('chamfer loss torch (cpu):', chamfer(x, y)) print('chamfer loss torch (cuda):', chamfer(x.cuda(), y.cuda())) # import sys # sys.path.append("../distance/chamfer/") # import dist_chamfer as cd # CD = cd.chamferDist() # dist1, dist2, _, _= CD(x, y) # print('orig', dist1)
27.735294
104
0.507423
139
0.073701
0
0
0
0
0
0
700
0.371156
bc8c6ccfc24c9f2c6b892349f506c390ec4d676f
8,400
py
Python
isiscb/curation/authority_views/relation_views.py
crispzips/IsisCB
72f5ad47bbc2c615f995df148f5b86550835efdb
[ "MIT" ]
4
2016-01-25T20:35:33.000Z
2020-04-07T15:39:52.000Z
isiscb/curation/authority_views/relation_views.py
crispzips/IsisCB
72f5ad47bbc2c615f995df148f5b86550835efdb
[ "MIT" ]
41
2015-08-19T17:34:41.000Z
2022-03-11T23:19:01.000Z
isiscb/curation/authority_views/relation_views.py
crispzips/IsisCB
72f5ad47bbc2c615f995df148f5b86550835efdb
[ "MIT" ]
2
2020-11-25T20:18:18.000Z
2021-06-24T15:15:41.000Z
from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, QueryDict #, HttpResponseForbidden, Http404, , JsonResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.admin.views.decorators import staff_member_required, user_passes_test from rules.contrib.views import permission_required, objectgetter from isisdata.models import * from isisdata.utils import strip_punctuation, normalize from isisdata import operations from isisdata.filters import * from isisdata import tasks as data_tasks from curation import p3_port_utils from curation.forms import * from curation.contrib.views import check_rules @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def create_acrelation_for_authority(request, authority_id): authority = get_object_or_404(Authority, pk=authority_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': initial = { 'authority': authority.id, 'name_for_display_in_citation': authority.name } type_controlled = request.GET.get('type_controlled', None) if type_controlled: initial.update({'type_controlled': type_controlled.upper()}) form = ACRelationForm(prefix='acrelation', initial=initial) elif request.method == 'POST': form = ACRelationForm(request.POST, prefix='acrelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=acrelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_acrelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def create_aarelation_for_authority(request, authority_id): authority = get_object_or_404(Authority, pk=authority_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': initial = { 'subject': authority.id } aarelation=AARelation() aarelation.subject = authority type_controlled = request.GET.get('type_controlled', None) if type_controlled: aarelation = dict(AARelation.TYPE_CHOICES)[type_controlled] form = AARelationForm(prefix='aarelation', instance=aarelation) elif request.method == 'POST': form = AARelationForm(request.POST, prefix='aarelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_aarelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def acrelation_for_authority(request, authority_id, acrelation_id): authority = get_object_or_404(Authority, pk=authority_id) acrelation = get_object_or_404(ACRelation, pk=acrelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'acrelation': acrelation, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': form = ACRelationForm(instance=acrelation, prefix='acrelation') elif request.method == 'POST': form = ACRelationForm(request.POST, instance=acrelation, prefix='acrelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=acrelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_acrelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def aarelation_for_authority(request, authority_id, aarelation_id): authority = get_object_or_404(Authority, pk=authority_id) aarelation = get_object_or_404(AARelation, pk=aarelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'aarelation': aarelation, 'search_key': search_key, 'current_index': current_index } if request.method == 'GET': form = AARelationForm(instance=aarelation, prefix='aarelation') elif request.method == 'POST': form = AARelationForm(request.POST, instance=aarelation, prefix='aarelation') if form.is_valid(): form.save() target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) context.update({ 'form': form, }) template = 'curation/authority_aarelation_changeview.html' return render(request, template, context) @user_passes_test(lambda u: u.is_superuser or u.is_staff) @check_rules('can_access_view_edit', fn=objectgetter(Authority, 'authority_id')) def delete_aarelation_for_authority(request, authority_id, aarelation_id, format=None): authority = get_object_or_404(Authority, pk=authority_id) aarelation = get_object_or_404(AARelation, pk=aarelation_id) search_key = request.GET.get('search', request.POST.get('search')) current_index = request.GET.get('current', request.POST.get('current')) context = { 'curation_section': 'datasets', 'curation_subsection': 'authorities', 'instance': authority, 'aarelation': aarelation, 'search_key': search_key, 'current_index': current_index } if request.POST.get('confirm', False) == 'true': if not aarelation.modified_on: aarelation.modified_on = datetime.datetime.now() aarelation.delete() if format == 'json': return JsonResponse({'result': True}) target = reverse('curation:curate_authority', args=(authority.id,)) + '?tab=aarelations' if search_key and current_index: target += '&search=%s&current=%s' % (search_key, current_index) return HttpResponseRedirect(target) if format == 'json': return JsonResponse({'result': False}) template = 'curation/authority_aarelation_delete.html' return render(request, template, context)
39.810427
133
0.68619
0
0
0
0
7,547
0.898452
0
0
1,809
0.215357
bc8efe8d75934b61443e05664bf142fdc9790c04
6,351
py
Python
run_tests.py
silx-kit/silx
360f890a617676a92f0bed6a28b718d09e70ec03
[ "CC0-1.0", "MIT" ]
94
2016-03-04T17:25:53.000Z
2022-03-18T18:05:23.000Z
run_tests.py
silx-kit/silx
360f890a617676a92f0bed6a28b718d09e70ec03
[ "CC0-1.0", "MIT" ]
2,841
2016-01-21T09:06:49.000Z
2022-03-18T14:53:56.000Z
run_tests.py
silx-kit/silx
360f890a617676a92f0bed6a28b718d09e70ec03
[ "CC0-1.0", "MIT" ]
71
2015-09-30T08:35:35.000Z
2022-03-16T07:16:28.000Z
#!/usr/bin/env python3 # coding: utf8 # /*########################################################################## # # Copyright (c) 2015-2021 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # ###########################################################################*/ """Run the tests of the project. This script expects a suite function in <project_package>.test, which returns a unittest.TestSuite. Test coverage dependencies: coverage, lxml. """ __authors__ = ["Jérôme Kieffer", "Thomas Vincent"] __date__ = "30/09/2020" __license__ = "MIT" import distutils.util import logging import os import subprocess import sys import importlib # Capture all default warnings logging.captureWarnings(True) import warnings warnings.simplefilter('default') logger = logging.getLogger("run_tests") logger.setLevel(logging.WARNING) logger.info("Python %s %s", sys.version, tuple.__itemsize__ * 8) try: import numpy except Exception as error: logger.warning("Numpy missing: %s", error) else: logger.info("Numpy %s", numpy.version.version) try: import h5py except Exception as error: logger.warning("h5py missing: %s", error) else: logger.info("h5py %s", h5py.version.version) def get_project_name(root_dir): """Retrieve project name by running python setup.py --name in root_dir. :param str root_dir: Directory where to run the command. :return: The name of the project stored in root_dir """ logger.debug("Getting project name in %s", root_dir) p = subprocess.Popen([sys.executable, "setup.py", "--name"], shell=False, cwd=root_dir, stdout=subprocess.PIPE) name, _stderr_data = p.communicate() logger.debug("subprocess ended with rc= %s", p.returncode) return name.split()[-1].decode('ascii') def is_debug_python(): """Returns true if the Python interpreter is in debug mode.""" try: import sysconfig except ImportError: # pragma nocover # Python < 2.7 import distutils.sysconfig as sysconfig if sysconfig.get_config_var("Py_DEBUG"): return True return hasattr(sys, "gettotalrefcount") def build_project(name, root_dir): """Run python setup.py build for the project. Build directory can be modified by environment variables. :param str name: Name of the project. :param str root_dir: Root directory of the project :return: The path to the directory were build was performed """ platform = distutils.util.get_platform() architecture = "lib.%s-%i.%i" % (platform, sys.version_info[0], sys.version_info[1]) if is_debug_python(): architecture += "-pydebug" if os.environ.get("PYBUILD_NAME") == name: # we are in the debian packaging way home = os.environ.get("PYTHONPATH", "").split(os.pathsep)[-1] elif os.environ.get("BUILDPYTHONPATH"): home = os.path.abspath(os.environ.get("BUILDPYTHONPATH", "")) else: home = os.path.join(root_dir, "build", architecture) logger.warning("Building %s to %s", name, home) p = subprocess.Popen([sys.executable, "setup.py", "build"], shell=False, cwd=root_dir) logger.debug("subprocess ended with rc= %s", p.wait()) if os.path.isdir(home): return home alt_home = os.path.join(os.path.dirname(home), "lib") if os.path.isdir(alt_home): return alt_home def import_project_module(project_name, project_dir): """Import project module, from the system of from the project directory""" if "--installed" in sys.argv: try: module = importlib.import_module(project_name) except Exception: logger.error("Cannot run tests on installed version: %s not installed or raising error.", project_name) raise else: # Use built source build_dir = build_project(project_name, project_dir) if build_dir is None: logging.error("Built project is not available !!! investigate") sys.path.insert(0, build_dir) logger.warning("Patched sys.path, added: '%s'", build_dir) module = importlib.import_module(project_name) return module if __name__ == "__main__": # Needed for multiprocessing support on Windows import pytest PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_NAME = get_project_name(PROJECT_DIR) logger.info("Project name: %s", PROJECT_NAME) project_module = import_project_module(PROJECT_NAME, PROJECT_DIR) PROJECT_VERSION = getattr(project_module, 'version', '') PROJECT_PATH = project_module.__path__[0] def normalize_option(option): option_parts = option.split(os.path.sep) if option_parts == ["src", "silx"]: return PROJECT_PATH if option_parts[:2] == ["src", "silx"]: return os.path.join(PROJECT_PATH, *option_parts[2:]) return option args = [normalize_option(p) for p in sys.argv[1:] if p != "--installed"] # Run test on PROJECT_PATH if nothing is specified without_options = [a for a in args if not a.startswith("-")] if len(without_options) == 0: args += [PROJECT_PATH] argv = ["--rootdir", PROJECT_PATH] + args sys.exit(pytest.main(argv))
34.895604
101
0.668714
0
0
0
0
0
0
0
0
2,976
0.46844
bc8faa6c50d7d1921cb25f63e39e57127594a8e6
7,072
py
Python
src/robot/utils/error.py
vprashanth777/Selenium
b3c48b75e73322891bb697f251b32a9a9d8b4dbe
[ "ECL-2.0", "Apache-2.0" ]
1
2018-03-10T11:10:20.000Z
2018-03-10T11:10:20.000Z
src/robot/utils/error.py
vprashanth777/Selenium
b3c48b75e73322891bb697f251b32a9a9d8b4dbe
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/robot/utils/error.py
vprashanth777/Selenium
b3c48b75e73322891bb697f251b32a9a9d8b4dbe
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# Copyright 2008-2015 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys import traceback from robot.errors import RobotError from .platform import JYTHON, RERAISED_EXCEPTIONS from .unic import unic EXCLUDE_ROBOT_TRACES = not os.getenv('ROBOT_INTERNAL_TRACES') if JYTHON: from java.io import StringWriter, PrintWriter from java.lang import Throwable, OutOfMemoryError else: Throwable = () def get_error_message(): """Returns error message of the last occurred exception. This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ return ErrorDetails().message def get_error_details(exclude_robot_traces=EXCLUDE_ROBOT_TRACES): """Returns error message and details of the last occurred exception.""" details = ErrorDetails(exclude_robot_traces=exclude_robot_traces) return details.message, details.traceback def ErrorDetails(exc_info=None, exclude_robot_traces=EXCLUDE_ROBOT_TRACES): """This factory returns an object that wraps the last occurred exception It has attributes `message`, `traceback` and `error`, where `message` contains type and message of the original error, `traceback` contains the traceback/stack trace and `error` contains the original error instance. """ exc_type, exc_value, exc_traceback = exc_info or sys.exc_info() if exc_type in RERAISED_EXCEPTIONS: raise exc_value details = PythonErrorDetails \ if not isinstance(exc_value, Throwable) else JavaErrorDetails return details(exc_type, exc_value, exc_traceback, exclude_robot_traces) class _ErrorDetails(object): _generic_exception_names = ('AssertionError', 'AssertionFailedError', 'Exception', 'Error', 'RuntimeError', 'RuntimeException') def __init__(self, exc_type, exc_value, exc_traceback, exclude_robot_traces=True): self.error = exc_value self._exc_type = exc_type self._exc_traceback = exc_traceback self._exclude_robot_traces = exclude_robot_traces self._message = None self._traceback = None @property def message(self): if self._message is None: self._message = self._get_message() return self._message def _get_message(self): raise NotImplementedError @property def traceback(self): if self._traceback is None: self._traceback = self._get_details() return self._traceback def _get_details(self): raise NotImplementedError def _get_name(self, exc_type): try: return exc_type.__name__ except AttributeError: return unic(exc_type) def _format_message(self, name, message): message = unic(message or '') message = self._clean_up_message(message, name) name = name.split('.')[-1] # Use only last part of the name if not message: return name if self._is_generic_exception(name): return message return '%s: %s' % (name, message) def _is_generic_exception(self, name): return (name in self._generic_exception_names or isinstance(self.error, RobotError) or getattr(self.error, 'ROBOT_SUPPRESS_NAME', False)) def _clean_up_message(self, message, name): return message class PythonErrorDetails(_ErrorDetails): def _get_message(self): name = self._get_name(self._exc_type) return self._format_message(name, unic(self.error)) def _get_details(self): if isinstance(self.error, RobotError): return self.error.details return 'Traceback (most recent call last):\n' + self._get_traceback() def _get_traceback(self): tb = self._exc_traceback while tb and self._is_excluded_traceback(tb): tb = tb.tb_next return ''.join(traceback.format_tb(tb)).rstrip() or ' None' def _is_excluded_traceback(self, traceback): if not self._exclude_robot_traces: return False module = traceback.tb_frame.f_globals.get('__name__') return module and module.startswith('robot.') class JavaErrorDetails(_ErrorDetails): _java_trace_re = re.compile('^\s+at (\w.+)') _ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.', 'sun.reflect.', 'java.lang.reflect.') def _get_message(self): exc_name = self._get_name(self._exc_type) # OOME.getMessage and even toString seem to throw NullPointerException if not self._is_out_of_memory_error(self._exc_type): exc_msg = self.error.getMessage() else: exc_msg = str(self.error) return self._format_message(exc_name, exc_msg) def _is_out_of_memory_error(self, exc_type): return exc_type is OutOfMemoryError def _get_details(self): # OOME.printStackTrace seems to throw NullPointerException if self._is_out_of_memory_error(self._exc_type): return '' output = StringWriter() self.error.printStackTrace(PrintWriter(output)) details = '\n'.join(line for line in output.toString().splitlines() if not self._is_ignored_stack_trace_line(line)) msg = unic(self.error.getMessage() or '') if msg: details = details.replace(msg, '', 1) return details def _is_ignored_stack_trace_line(self, line): if not line: return True res = self._java_trace_re.match(line) if res is None: return False location = res.group(1) for entry in self._ignored_java_trace: if location.startswith(entry): return True return False def _clean_up_message(self, msg, name): msg = self._remove_stack_trace_lines(msg) return self._remove_exception_name(msg, name).strip() def _remove_stack_trace_lines(self, msg): lines = msg.splitlines() while lines: if self._java_trace_re.match(lines[-1]): lines.pop() else: break return '\n'.join(lines) def _remove_exception_name(self, msg, name): tokens = msg.split(':', 1) if len(tokens) == 2 and tokens[0] == name: msg = tokens[1] return msg
34.330097
78
0.662472
4,822
0.681844
0
0
294
0.041572
0
0
1,685
0.238264
bc90147c820b8957a1562bdb12623216308ec658
308
py
Python
dedupe/_init.py
neozhangthe1/dedupe
aff99e6bd027291eecfb78eae08aa73877f4fff0
[ "MIT" ]
null
null
null
dedupe/_init.py
neozhangthe1/dedupe
aff99e6bd027291eecfb78eae08aa73877f4fff0
[ "MIT" ]
null
null
null
dedupe/_init.py
neozhangthe1/dedupe
aff99e6bd027291eecfb78eae08aa73877f4fff0
[ "MIT" ]
null
null
null
from dedupe.api import StaticDedupe, Dedupe from dedupe.api import StaticRecordLink, RecordLink from dedupe.api import StaticGazetteer, Gazetteer from dedupe.core import randomPairs, randomPairsMatch, frozendict from dedupe.convenience import consoleLabel, trainingDataDedupe, trainingDataLink, canonicalize
51.333333
95
0.866883
0
0
0
0
0
0
0
0
0
0
bc926bb3d7c2f20a37f4cae0b86f7455ebdb913c
1,430
py
Python
scalability/tests/test_misc.py
ggreif/ic
ac56ec91f077c00d59eea3f73f51e14a1b3ea882
[ "Apache-2.0" ]
941
2021-05-10T08:14:14.000Z
2022-03-31T11:40:24.000Z
scalability/tests/test_misc.py
ggreif/ic
ac56ec91f077c00d59eea3f73f51e14a1b3ea882
[ "Apache-2.0" ]
3
2022-02-16T12:24:20.000Z
2022-03-23T12:05:41.000Z
scalability/tests/test_misc.py
ggreif/ic
ac56ec91f077c00d59eea3f73f51e14a1b3ea882
[ "Apache-2.0" ]
122
2021-05-10T08:21:23.000Z
2022-03-25T20:34:12.000Z
import unittest from unittest import TestCase from misc import verify class TestVerify(TestCase): """Tests misc.py verifies function.""" def test_verify__with_zero_threshold_and_expected_succeeds(self): """Test passes when expected rate, actual rate and threshold are all zero.""" result = verify(metric="Query failure rate", actual=0.0, expected=0.0, threshold=0.0) self.assertEqual(result, 0) def test_verify__fails_when_positive_delta_is_larger_than_postive_threshold(self): """Test fails when positive delta between actual rate and expected rate exceeds positive threshold.""" result = verify(metric="Update latency", actual=200, expected=100, threshold=0.1) self.assertEqual(result, 1) def test_verify__fails_when_negative_delta_is_smaller_than_negative_threshold(self): """Test fails when negative delta between actual rate and expected rate exceeds negative threshold.""" result = verify(metric="Update latency", actual=50, expected=100, threshold=-0.01) self.assertEqual(result, 1) def test_verify__fails_when_negative_delta_and_positive_threshold(self): """Test fails when delta between actual rate and expected rate exceeds threshold.""" result = verify(metric="Update latency", actual=50, expected=100, threshold=0.01) self.assertEqual(result, 0) if __name__ == "__main__": unittest.main()
43.333333
110
0.735664
1,307
0.913986
0
0
0
0
0
0
481
0.336364
bc92877f15ab8c1e45e6b3f0628b4c9b556c0100
4,271
py
Python
mars/tensor/fft/ifft.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
2
2019-03-29T04:11:10.000Z
2020-07-08T10:19:54.000Z
mars/tensor/fft/ifft.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
null
null
null
mars/tensor/fft/ifft.py
tomzhang/mars-1
6f1d85e37eb1b383251314cb0ba13e06288af03d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from ... import opcodes as OperandDef from ..datasource import tensor as astensor from .core import TensorComplexFFTMixin, validate_fft, TensorStandardFFT class TensorIFFT(TensorStandardFFT, TensorComplexFFTMixin): _op_type_ = OperandDef.IFFT def __init__(self, n=None, axis=-1, norm=None, dtype=None, **kw): super().__init__(_n=n, _axis=axis, _norm=norm, _dtype=dtype, **kw) def ifft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional inverse discrete Fourier Transform. This function computes the inverse of the one-dimensional *n*-point discrete Fourier transform computed by `fft`. In other words, ``ifft(fft(a)) == a`` to within numerical accuracy. For a general description of the algorithm and definitions, see `mt.fft`. The input should be ordered in the same way as is returned by `fft`, i.e., * ``a[0]`` should contain the zero frequency term, * ``a[1:n//2]`` should contain the positive-frequency terms, * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in increasing order starting from the most negative frequency. For an even number of input points, ``A[n//2]`` represents the sum of the values at the positive and negative Nyquist frequencies, as the two are aliased together. See `numpy.fft` for details. Parameters ---------- a : array_like Input tensor, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. See notes about padding issues. axis : int, optional Axis over which to compute the inverse DFT. If not given, the last axis is used. norm : {None, "ortho"}, optional Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex Tensor The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError If `axes` is larger than the last axis of `a`. See Also -------- mt.fft : An introduction, with definitions and general explanations. fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse ifft2 : The two-dimensional inverse FFT. ifftn : The n-dimensional inverse FFT. Notes ----- If the input parameter `n` is larger than the size of the input, the input is padded by appending zeros at the end. Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it must be performed before calling `ifft`. Examples -------- >>> import mars.tensor as mt >>> mt.fft.ifft([0, 4, 0, 0]).execute() array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) Create and plot a band-limited signal with random phases: >>> import matplotlib.pyplot as plt >>> t = mt.arange(400) >>> n = mt.zeros((400,), dtype=complex) >>> n[40:60] = mt.exp(1j*mt.random.uniform(0, 2*mt.pi, (20,))) >>> s = mt.fft.ifft(n) >>> plt.plot(t.execute(), s.real.execute(), 'b-', t.execute(), s.imag.execute(), 'r--') ... >>> plt.legend(('real', 'imaginary')) ... >>> plt.show() """ a = astensor(a) validate_fft(a, axis, norm) op = TensorIFFT(n=n, axis=axis, norm=norm, dtype=np.dtype(np.complex_)) return op(a)
35.890756
91
0.657926
237
0.055491
0
0
0
0
0
0
3,647
0.853898
bc92d9002e07294919b14cfdd4a1703514d8c845
53
py
Python
server/api/src/db/migrate/versions/v_2.py
mminamina/311-data
9a3e4dc6e14c7500fc3f75f583c7fc4b01108b29
[ "MIT" ]
null
null
null
server/api/src/db/migrate/versions/v_2.py
mminamina/311-data
9a3e4dc6e14c7500fc3f75f583c7fc4b01108b29
[ "MIT" ]
null
null
null
server/api/src/db/migrate/versions/v_2.py
mminamina/311-data
9a3e4dc6e14c7500fc3f75f583c7fc4b01108b29
[ "MIT" ]
null
null
null
def migrate(): print('migrating to version 2')
10.6
35
0.641509
0
0
0
0
0
0
0
0
24
0.45283