content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# 'Uppercase letter (Lu)', 'Lowercase letter (Ll)',
# 'Titlecase letter(Lt)', 'Modifier letter (Lm)', 'Other letter (Lo)'
LETTER = (
u'[A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6'
u'\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376'
u'\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5'
u'\u03f7-\u0481\u048a-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea'
u'\u05f0-\u05f2\u0621-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6'
u'\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1'
u'\u07ca-\u07ea\u07f4\u07f5\u07fa\u0904-\u0939\u093d\u0950\u0958-\u0961'
u'\u0971\u0972\u097b-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8'
u'\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1'
u'\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32'
u'\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74'
u'\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3'
u'\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10'
u'\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d'
u'\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99'
u'\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0'
u'\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d'
u'\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8'
u'\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0d05-\u0d0c'
u'\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d3d\u0d60\u0d61\u0d7a-\u0d7f'
u'\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30'
u'\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d'
u'\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab'
u'\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc\u0edd\u0f00'
u'\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8b\u1000-\u102a\u103f\u1050-\u1055'
u'\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e'
u'\u10a0-\u10c5\u10d0-\u10fa\u10fc\u1100-\u1159\u115f-\u11a2\u11a8-\u11f9'
u'\u1200-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288'
u'\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5'
u'\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f'
u'\u13a0-\u13f4\u1401-\u166c\u166f-\u1676\u1681-\u169a\u16a0-\u16ea'
u'\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c'
u'\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa'
u'\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19a9\u19c1-\u19c7'
u'\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf'
u'\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1d00-\u1dbf\u1e00-\u1f15'
u'\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d'
u'\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc'
u'\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071'
u'\u207f\u2090-\u2094\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124'
u'\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e'
u'\u2183\u2184\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2c6f\u2c71-\u2c7d'
u'\u2c80-\u2ce4\u2d00-\u2d25\u2d30-\u2d65\u2d6f\u2d80-\u2d96\u2da0-\u2da6'
u'\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce'
u'\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005\u3006\u3031-\u3035\u303b\u303c'
u'\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d'
u'\u3131-\u318e\u31a0-\u31b7\u31f0-\u31ff\u3400\u4db5\u4e00\u9fc3'
u'\ua000-\ua48c\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua65f'
u'\ua662-\ua66e\ua67f-\ua697\ua717-\ua71f\ua722-\ua788\ua78b\ua78c'
u'\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873'
u'\ua882-\ua8b3\ua90a-\ua925\ua930-\ua946\uaa00-\uaa28\uaa40-\uaa42'
u'\uaa44-\uaa4b\uac00\ud7a3\uf900-\ufa2d\ufa30-\ufa6a\ufa70-\ufad9'
u'\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c'
u'\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f'
u'\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a'
u'\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7'
u'\uffda-\uffdc]'
)
NON_SPACING_MARK = (
u'[\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5'
u'\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7'
u'\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3'
u'\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c'
u'\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09c1-\u09c4'
u'\u09cd\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48'
u'\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5'
u'\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3f\u0b41-\u0b44\u0b4d'
u'\u0b56\u0b62\u0b63\u0b82\u0bc0\u0bcd\u0c3e-\u0c40\u0c46-\u0c48'
u'\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc6\u0ccc\u0ccd'
u'\u0ce2\u0ce3\u0d41-\u0d44\u0d4d\u0d62\u0d63\u0dca\u0dd2-\u0dd4\u0dd6'
u'\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc'
u'\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84'
u'\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037'
u'\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082'
u'\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753'
u'\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9'
u'\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56'
u'\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03'
u'\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5'
u'\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0'
u'\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u20d0-\u20dc\u20e1'
u'\u20e5-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f'
u'\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4'
u'\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9'
u'\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0'
u'\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\ufb1e'
u'\ufe00-\ufe0f\ufe20-\ufe26]'
)
COMBINING_SPACING_MARK = (
u'[\u0903\u093e-\u0940\u0949-\u094c\u094e\u0982\u0983\u09be-\u09c0\u09c7'
u'\u09c8\u09cb\u09cc\u09d7\u0a03\u0a3e-\u0a40\u0a83\u0abe-\u0ac0\u0ac9'
u'\u0acb\u0acc\u0b02\u0b03\u0b3e\u0b40\u0b47\u0b48\u0b4b\u0b4c\u0b57'
u'\u0bbe\u0bbf\u0bc1\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcc\u0bd7\u0c01-\u0c03'
u'\u0c41-\u0c44\u0c82\u0c83\u0cbe\u0cc0-\u0cc4\u0cc7\u0cc8\u0cca\u0ccb'
u'\u0cd5\u0cd6\u0d02\u0d03\u0d3e-\u0d40\u0d46-\u0d48\u0d4a-\u0d4c\u0d57'
u'\u0d82\u0d83\u0dcf-\u0dd1\u0dd8-\u0ddf\u0df2\u0df3\u0f3e\u0f3f\u0f7f'
u'\u102b\u102c\u1031\u1038\u103b\u103c\u1056\u1057\u1062-\u1064'
u'\u1067-\u106d\u1083\u1084\u1087-\u108c\u108f\u109a-\u109c\u17b6'
u'\u17be-\u17c5\u17c7\u17c8\u1923-\u1926\u1929-\u192b\u1930\u1931'
u'\u1933-\u1938\u19b0-\u19c0\u19c8\u19c9\u1a19-\u1a1b\u1a55\u1a57\u1a61'
u'\u1a63\u1a64\u1a6d-\u1a72\u1b04\u1b35\u1b3b\u1b3d-\u1b41\u1b43\u1b44'
u'\u1b82\u1ba1\u1ba6\u1ba7\u1baa\u1c24-\u1c2b\u1c34\u1c35\u1ce1\u1cf2'
u'\ua823\ua824\ua827\ua880\ua881\ua8b4-\ua8c3\ua952\ua953\ua983\ua9b4'
u'\ua9b5\ua9ba\ua9bb\ua9bd-\ua9c0\uaa2f\uaa30\uaa33\uaa34\uaa4d\uaa7b'
u'\uabe3\uabe4\uabe6\uabe7\uabe9\uabea\uabec]'
)
COMBINING_MARK = u'%s|%s' % (NON_SPACING_MARK, COMBINING_SPACING_MARK)
CONNECTOR_PUNCTUATION = u'[_\u203f\u2040\u2054\ufe33\ufe34\ufe4d-\ufe4f\uff3f]'
DIGIT = (
u'[0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f'
u'\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef' # noqa: E501,W293
u'\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9'
u'\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819'
u'\u1946-\u194f\u19d0-\u19da\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59'
u'\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9'
u'\ua900-\ua909\ua9d0-\ua9d9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19]'
)
| letter = u'[A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԣԱ-Ֆՙա-ևא-תװ-ײء-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺऄ-हऽॐक़-ॡॱॲॻ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡഅ-ഌഎ-ഐഒ-നപ-ഹഽൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜໝༀཀ-ཇཉ-ཬྈ-ྋက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-Ⴥა-ჺჼᄀ-ᅙᅟ-ᆢᆨ-ᇹሀ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙶᚁ-ᚚᚠ-ᛪᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦩᧁ-ᧇᨀ-ᨖᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᰀ-ᰣᱍ-ᱏᱚ-ᱽᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₔℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-Ⱞⰰ-ⱞⱠ-Ɐⱱ-ⱽⲀ-ⳤⴀ-ⴥⴰ-ⵥⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々〆〱-〵〻〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆷㇰ-ㇿ㐀䶵一鿃ꀀ-ꒌꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙟꙢ-ꙮꙿ-ꚗꜗ-ꜟꜢ-ꞈꞋꞌꟻ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꤊ-ꤥꤰ-ꥆꨀ-ꨨꩀ-ꩂꩄ-ꩋ가힣豈-鶴侮-頻並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]'
non_spacing_mark = u'[̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٞۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࠭ऀ-ं़ु-ै्॑-ॕॢॣঁ়ু-ৄ্ৢৣਁਂ਼ੁੂੇੈੋ-੍ੑੰੱੵઁં઼ુ-ૅેૈ્ૢૣଁ଼ିୁ-ୄ୍ୖୢୣஂீ்ా-ీె-ైొ-్ౕౖౢౣ಼ಿೆೌ್ೢೣു-ൄ്ൢൣ්ි-ුූัิ-ฺ็-๎ັິ-ູົຼ່-ໍཱ༹༘༙༵༷-ཾྀ-྄྆྇ྐ-ྗྙ-ྼ࿆ိ-ူဲ-့္်ွှၘၙၞ-ၠၱ-ၴႂႅႆႍႝ፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳិ-ួំ៉-៓៝᠋-᠍ᢩᤠ-ᤢᤧᤨᤲ᤹-᤻ᨘᨗᩖᩘ-ᩞ᩠ᩢᩥ-ᩬᩳ-᩿᩼ᬀ-ᬃ᬴ᬶ-ᬺᬼᭂ᭫-᭳ᮀᮁᮢ-ᮥᮨᮩᰬ-ᰳᰶ᰷᳐-᳔᳒-᳢᳠-᳨᳭᷀-᷽ᷦ-᷿⃐-⃥⃜⃡-⃰⳯-⳱ⷠ-〪ⷿ-゙゚〯꙯꙼꙽꛰꛱ꠂ꠆ꠋꠥꠦ꣄꣠-꣱ꤦ-꤭ꥇ-ꥑꦀ-ꦂ꦳ꦶ-ꦹꦼꨩ-ꨮꨱꨲꨵꨶꩃꩌꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꯥꯨ꯭ﬞ︀-️︠-︦]'
combining_spacing_mark = u'[ःा-ीॉ-ौॎংঃা-ীেৈোৌৗਃਾ-ੀઃા-ીૉોૌଂଃାୀେୈୋୌୗாிுூெ-ைொ-ௌௗఁ-ఃు-ౄಂಃಾೀ-ೄೇೈೊೋೕೖംഃാ-ീെ-ൈൊ-ൌൗංඃා-ෑෘ-ෟෲෳ༾༿ཿါာေးျြၖၗၢ-ၤၧ-ၭႃႄႇ-ႌႏႚ-ႜាើ-ៅះៈᤣ-ᤦᤩ-ᤫᤰᤱᤳ-ᤸᦰ-ᧀᧈᧉᨙ-ᨛᩕᩗᩡᩣᩤᩭ-ᩲᬄᬵᬻᬽ-ᭁᭃ᭄ᮂᮡᮦᮧ᮪ᰤ-ᰫᰴᰵ᳡ᳲꠣꠤꠧꢀꢁꢴ-ꣃꥒ꥓ꦃꦴꦵꦺꦻꦽ-꧀ꨯꨰꨳꨴꩍꩻꯣꯤꯦꯧꯩꯪ꯬]'
combining_mark = u'%s|%s' % (NON_SPACING_MARK, COMBINING_SPACING_MARK)
connector_punctuation = u'[_‿⁀⁔︳︴﹍-﹏_]'
digit = u'[0-9٠-٩۰-۹߀-߉०-९০-৯੦-੯૦-૯୦-୯௦-௯౦-౯೦-೯൦-൯๐-๙໐-໙༠-༩၀-၉႐-႙០-៩᠐-᠙᥆-᥏᧐-᧚᪀-᪉᪐-᪙᭐-᭙᮰-᮹᱀-᱉᱐-᱙꘠-꘩꣐-꣙꤀-꤉꧐-꧙꩐-꩙꯰-꯹0-9]' |
# MOST FREQUENT
n,mx,mn=int(input()),0,10**4
A=[int(a) for a in input().split()]
a=set(A)
for i in a:
q=A.count(i)
if q>mx:
mx = q
mn = i
elif q==mx and i<mn:
mn = i
print(mn)
| (n, mx, mn) = (int(input()), 0, 10 ** 4)
a = [int(a) for a in input().split()]
a = set(A)
for i in a:
q = A.count(i)
if q > mx:
mx = q
mn = i
elif q == mx and i < mn:
mn = i
print(mn) |
class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
# map x to y
xx = collections.defaultdict(set)
# map y to x
yy = collections.defaultdict(set)
for x, y in points:
xx[x].add(y)
yy[y].add(x)
area = sys.maxsize
for x0, y0 in points:
if len(xx[x0]) < 2 or len(yy[y0]) < 2:
continue
for y1 in xx[x0]:
if y1 == y0:
continue
xs = yy[y1]
for x1 in xs:
if x1 != x0 and x1 in yy[y0]:
area = min(area, abs(x0 - x1) * abs(y0 - y1))
if area != sys.maxsize:
return area
return 0
| class Solution:
def min_area_rect(self, points: List[List[int]]) -> int:
xx = collections.defaultdict(set)
yy = collections.defaultdict(set)
for (x, y) in points:
xx[x].add(y)
yy[y].add(x)
area = sys.maxsize
for (x0, y0) in points:
if len(xx[x0]) < 2 or len(yy[y0]) < 2:
continue
for y1 in xx[x0]:
if y1 == y0:
continue
xs = yy[y1]
for x1 in xs:
if x1 != x0 and x1 in yy[y0]:
area = min(area, abs(x0 - x1) * abs(y0 - y1))
if area != sys.maxsize:
return area
return 0 |
with open('census.csv', encoding='utf8') as f:
i = 0
dictio = dict([
('Preschool', 0),
('1st-4th', 0),
('5th-6th', 0),
('7th-8th', 0),
('9th', 0),
('10th', 0),
('11th', 0),
('12th', 0),
('HS-grad', 0),
('Some-college', 0),
('Assoc-voc', 0),
('Assoc-acdm', 0),
('Bachelors', 0),
('Prof-school', 0),
('Masters', 0),
('Doctorate', 0)
])
for line in f:
entry = line.split(', ')
edu_level = entry[3]
if edu_level in dictio:
dictio[edu_level] += 1
if edu_level not in dictio:
dictio[edu_level] = 1
i += 1
for item in dictio:
print('{} -- {}'.format(dictio[item], item))
'''
Expected results:
(16 lines)
5355 -- Bachelors
10501 -- HS-grad
1175 -- 11th
1723 -- Masters
514 -- 9th
7291 -- Some-college
1067 -- Assoc-acdm
1382 -- Assoc-voc
646 -- 7th-8th
413 -- Doctorate
576 -- Prof-school
333 -- 5th-6th
933 -- 10th
168 -- 1st-4th
51 -- Preschool
433 -- 12th
'''
'''
Suggestions from the class:
- setdefault(item, 0) makes if not in dict not needed
- Since every entry in file has at least one, you can also make dictionary empty
- The syntax for dictionary is as follows:
a_dict ={
'key': value,
'another key': another_value
}
'''
| with open('census.csv', encoding='utf8') as f:
i = 0
dictio = dict([('Preschool', 0), ('1st-4th', 0), ('5th-6th', 0), ('7th-8th', 0), ('9th', 0), ('10th', 0), ('11th', 0), ('12th', 0), ('HS-grad', 0), ('Some-college', 0), ('Assoc-voc', 0), ('Assoc-acdm', 0), ('Bachelors', 0), ('Prof-school', 0), ('Masters', 0), ('Doctorate', 0)])
for line in f:
entry = line.split(', ')
edu_level = entry[3]
if edu_level in dictio:
dictio[edu_level] += 1
if edu_level not in dictio:
dictio[edu_level] = 1
i += 1
for item in dictio:
print('{} -- {}'.format(dictio[item], item))
'\nExpected results:\n(16 lines)\n 5355 -- Bachelors\n10501 -- HS-grad\n 1175 -- 11th\n 1723 -- Masters\n 514 -- 9th\n 7291 -- Some-college\n 1067 -- Assoc-acdm\n 1382 -- Assoc-voc\n 646 -- 7th-8th\n 413 -- Doctorate\n 576 -- Prof-school\n 333 -- 5th-6th\n 933 -- 10th\n 168 -- 1st-4th\n 51 -- Preschool\n 433 -- 12th\n'
"\nSuggestions from the class:\n - setdefault(item, 0) makes if not in dict not needed\n - Since every entry in file has at least one, you can also make dictionary empty\n - The syntax for dictionary is as follows:\n a_dict ={\n 'key': value,\n 'another key': another_value\n }\n" |
_base_ = "./wheat_detection_mstrain.py"
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
albu_train_transforms = [
dict(type="RandomRotate90", p=1.0),
dict(
type="OneOf",
transforms=[
dict(type="HueSaturationValue", hue_shift_limit=10, sat_shift_limit=35, val_shift_limit=25),
dict(type="RandomGamma"),
dict(type="CLAHE"),
],
p=0.5,
),
dict(
type="OneOf",
transforms=[
dict(type="RandomBrightnessContrast", brightness_limit=0.25, contrast_limit=0.25),
dict(type="RGBShift", r_shift_limit=15, g_shift_limit=15, b_shift_limit=15),
],
p=0.5,
),
dict(
type="OneOf",
transforms=[
dict(type="Blur"),
dict(type="MotionBlur"),
dict(type="GaussNoise"),
dict(type="ImageCompression", quality_lower=75),
],
p=0.4,
),
dict(
type="CoarseDropout",
max_holes=30,
max_height=30,
max_width=30,
min_holes=5,
min_height=10,
min_width=10,
fill_value=img_norm_cfg["mean"][::-1],
p=0.4,
),
dict(
type="ModifiedShiftScaleRotate",
shift_limit=0.3,
rotate_limit=5,
scale_limit=(-0.3, 0.75),
border_mode=0,
value=img_norm_cfg["mean"][::-1],
),
dict(type="RandomBBoxesSafeCrop", num_rate=(0.5, 1.0), erosion_rate=0.2),
]
train_pipeline = [
dict(type="MultipleLoadImageFromFile"),
dict(type="LoadAnnotations", with_bbox=True),
dict(type="Mosaic", p=0.25, min_buffer_size=4, pad_val=img_norm_cfg["mean"][::-1]),
dict(
type="Albumentations",
transforms=albu_train_transforms,
keymap=dict(img="image", gt_masks="masks", gt_bboxes="bboxes"),
update_pad_shape=False,
skip_img_without_anno=True,
bbox_params=dict(type="BboxParams", format="pascal_voc", label_fields=["labels"]),
min_visibility=0.3,
min_size=4,
max_aspect_ratio=15,
),
dict(type="Mixup", p=0.25, min_buffer_size=2, pad_val=img_norm_cfg["mean"][::-1]),
dict(type="RandomFlip", flip_ratio=0.5),
dict(
type="Resize",
img_scale=[(768 + 32 * i, 768 + 32 * i) for i in range(25)],
multiscale_mode="value",
keep_ratio=True,
),
dict(type="Normalize", **img_norm_cfg),
dict(type="Pad", size_divisor=32),
dict(type="DefaultFormatBundle"),
dict(type="Collect", keys=["img", "gt_bboxes", "gt_labels"]),
]
data_root = "/data/"
data = dict(
train=dict(
pipeline=train_pipeline,
ann_file=[
data_root + "folds_v2/{fold}/coco_tile_train.json",
data_root + "folds_v2/{fold}/coco_pseudo_train.json",
],
img_prefix=[
dict(
roots=[
data_root + "train/",
data_root + "colored_train/",
data_root + "stylized_train/",
data_root + "stylized_by_test_v1/",
data_root + "stylized_by_test_v2/",
data_root + "stylized_by_test_v3/",
data_root + "stylized_by_test_v4/",
],
probabilities=[0.75, 0.15, 0.1 / 5, 0.1 / 5, 0.1 / 5, 0.1 / 5, 0.1 / 5],
),
dict(
roots=[
data_root + "crops_fold0/",
data_root + "colored_crops_fold0/",
data_root + "stylized_pseudo_by_test_v1/",
data_root + "stylized_pseudo_by_test_v2/",
data_root + "stylized_pseudo_by_test_v3/",
data_root + "stylized_pseudo_by_test_v4/",
],
probabilities=[0.75, 0.15, 0.1 / 4, 0.1 / 4, 0.1 / 4, 0.1 / 4],
),
],
)
)
| _base_ = './wheat_detection_mstrain.py'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
albu_train_transforms = [dict(type='RandomRotate90', p=1.0), dict(type='OneOf', transforms=[dict(type='HueSaturationValue', hue_shift_limit=10, sat_shift_limit=35, val_shift_limit=25), dict(type='RandomGamma'), dict(type='CLAHE')], p=0.5), dict(type='OneOf', transforms=[dict(type='RandomBrightnessContrast', brightness_limit=0.25, contrast_limit=0.25), dict(type='RGBShift', r_shift_limit=15, g_shift_limit=15, b_shift_limit=15)], p=0.5), dict(type='OneOf', transforms=[dict(type='Blur'), dict(type='MotionBlur'), dict(type='GaussNoise'), dict(type='ImageCompression', quality_lower=75)], p=0.4), dict(type='CoarseDropout', max_holes=30, max_height=30, max_width=30, min_holes=5, min_height=10, min_width=10, fill_value=img_norm_cfg['mean'][::-1], p=0.4), dict(type='ModifiedShiftScaleRotate', shift_limit=0.3, rotate_limit=5, scale_limit=(-0.3, 0.75), border_mode=0, value=img_norm_cfg['mean'][::-1]), dict(type='RandomBBoxesSafeCrop', num_rate=(0.5, 1.0), erosion_rate=0.2)]
train_pipeline = [dict(type='MultipleLoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Mosaic', p=0.25, min_buffer_size=4, pad_val=img_norm_cfg['mean'][::-1]), dict(type='Albumentations', transforms=albu_train_transforms, keymap=dict(img='image', gt_masks='masks', gt_bboxes='bboxes'), update_pad_shape=False, skip_img_without_anno=True, bbox_params=dict(type='BboxParams', format='pascal_voc', label_fields=['labels']), min_visibility=0.3, min_size=4, max_aspect_ratio=15), dict(type='Mixup', p=0.25, min_buffer_size=2, pad_val=img_norm_cfg['mean'][::-1]), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Resize', img_scale=[(768 + 32 * i, 768 + 32 * i) for i in range(25)], multiscale_mode='value', keep_ratio=True), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])]
data_root = '/data/'
data = dict(train=dict(pipeline=train_pipeline, ann_file=[data_root + 'folds_v2/{fold}/coco_tile_train.json', data_root + 'folds_v2/{fold}/coco_pseudo_train.json'], img_prefix=[dict(roots=[data_root + 'train/', data_root + 'colored_train/', data_root + 'stylized_train/', data_root + 'stylized_by_test_v1/', data_root + 'stylized_by_test_v2/', data_root + 'stylized_by_test_v3/', data_root + 'stylized_by_test_v4/'], probabilities=[0.75, 0.15, 0.1 / 5, 0.1 / 5, 0.1 / 5, 0.1 / 5, 0.1 / 5]), dict(roots=[data_root + 'crops_fold0/', data_root + 'colored_crops_fold0/', data_root + 'stylized_pseudo_by_test_v1/', data_root + 'stylized_pseudo_by_test_v2/', data_root + 'stylized_pseudo_by_test_v3/', data_root + 'stylized_pseudo_by_test_v4/'], probabilities=[0.75, 0.15, 0.1 / 4, 0.1 / 4, 0.1 / 4, 0.1 / 4])])) |
# Creating a bubble sort function
def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [4,5,6,2,1,8,3]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))
| def bubble_sort(list1):
for i in range(0, len(list1) - 1):
for j in range(len(list1) - 1):
if list1[j] > list1[j + 1]:
temp = list1[j]
list1[j] = list1[j + 1]
list1[j + 1] = temp
return list1
list1 = [4, 5, 6, 2, 1, 8, 3]
print('The unsorted list is: ', list1)
print('The sorted list is: ', bubble_sort(list1)) |
def age_calc():
seconds_or_years = input(
"Type 's' if you want to enter your age in seconds. Type 'y' if you want to enter it as years. \n")
if seconds_or_years.lower() == 's':
user_age = input("Enter your age in seconds:")
age_as_years = (int(user_age) / 365 / 24 / 60 / 60)
print("You have lived for {} years.".format(age_as_years))
elif seconds_or_years.lower() == 'y':
user_age = input("Enter your age in years:")
age_as_seconds = (int(user_age) * 365 * 24 * 60 * 60)
print("You have lived for {} seconds.".format(age_as_seconds))
return;
age_calc()
| def age_calc():
seconds_or_years = input("Type 's' if you want to enter your age in seconds. Type 'y' if you want to enter it as years. \n")
if seconds_or_years.lower() == 's':
user_age = input('Enter your age in seconds:')
age_as_years = int(user_age) / 365 / 24 / 60 / 60
print('You have lived for {} years.'.format(age_as_years))
elif seconds_or_years.lower() == 'y':
user_age = input('Enter your age in years:')
age_as_seconds = int(user_age) * 365 * 24 * 60 * 60
print('You have lived for {} seconds.'.format(age_as_seconds))
return
age_calc() |
class Musteri:
def __init__(self, ad, merkez, bakiye, tel):
self.ad = ad
self.merkez = merkez
self.tel = tel
self.bakiye = bakiye
def musteri_adini_yazdir(self):
return self.ad
def musteri_bankasi(self):
return self.merkez
def musteri_tel(self):
return self.tel
def musteri_bakiye(self):
return self.bakiye
def para_yatir(self, eklenecek_para_miktari):
self.bakiye += eklenecek_para_miktari
def para_cek(self, cikarilacak_para_miktari):
self.bakiye -= cikarilacak_para_miktari
| class Musteri:
def __init__(self, ad, merkez, bakiye, tel):
self.ad = ad
self.merkez = merkez
self.tel = tel
self.bakiye = bakiye
def musteri_adini_yazdir(self):
return self.ad
def musteri_bankasi(self):
return self.merkez
def musteri_tel(self):
return self.tel
def musteri_bakiye(self):
return self.bakiye
def para_yatir(self, eklenecek_para_miktari):
self.bakiye += eklenecek_para_miktari
def para_cek(self, cikarilacak_para_miktari):
self.bakiye -= cikarilacak_para_miktari |
def divide(x, y):
return x / y
def multiply(x, y):
return x * y
def subtract(x, y):
return x - y
def add(x, y):
return x + y
def power(x, y):
return x ^ y
| def divide(x, y):
return x / y
def multiply(x, y):
return x * y
def subtract(x, y):
return x - y
def add(x, y):
return x + y
def power(x, y):
return x ^ y |
class Fruit:
def __init__(self, key, weight):
self.key = key
self.weight = weight
| class Fruit:
def __init__(self, key, weight):
self.key = key
self.weight = weight |
# Populate with your own database details
db_password = ''
db_name = ''
table_name = ''
| db_password = ''
db_name = ''
table_name = '' |
# for fetching transcription factor sequences
GENE_IDENTIFIER_MAP = {
'RXR': 'RXRA'
}
NAMES_WITH_HYPHENS = {
'NKX3-1',
'NKX2-1',
'NKX2-5',
'SS18-SSX'
}
def parse_gene_name(name):
if '-' not in name or name in NAMES_WITH_HYPHENS:
name = GENE_IDENTIFIER_MAP.get(name, name)
if '_' in name:
# for now, if target with modification
# just search for the target factor name to the left of the underscore
name, *_ = name.split('_')
return (name,)
first, *rest = name.split('-')
parsed_rest = []
for name in rest:
if len(name) == 1:
name = f'{first[:-1]}{name}'
parsed_rest.append(name)
return tuple([first, *parsed_rest])
| gene_identifier_map = {'RXR': 'RXRA'}
names_with_hyphens = {'NKX3-1', 'NKX2-1', 'NKX2-5', 'SS18-SSX'}
def parse_gene_name(name):
if '-' not in name or name in NAMES_WITH_HYPHENS:
name = GENE_IDENTIFIER_MAP.get(name, name)
if '_' in name:
(name, *_) = name.split('_')
return (name,)
(first, *rest) = name.split('-')
parsed_rest = []
for name in rest:
if len(name) == 1:
name = f'{first[:-1]}{name}'
parsed_rest.append(name)
return tuple([first, *parsed_rest]) |
# Copyright (c) 2016, Samantha Marshall (http://pewpewthespells.com)
# All rights reserved.
#
# https://github.com/samdmarshall/pyconfig
#
# 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.
#
# 3. Neither the name of Samantha Marshall nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# 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 HOLDER 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.
# this is the base class defintion for all of the pyconfig DSL keywords.
## The majority of the functionality in this class is to say that we need
## to subclass and over-ride the methods.
class BaseKeyword(object):
def __init__(self):
self.__parsed_item = None
def __eq__(self, other): # pylint: disable=no-self-use ; # pragma: no cover
raise Exception('Please subclass this class and implement this method')
def serialize(self): # pylint: disable=no-self-use ; # pragma: no cover
raise Exception('Please subclass this class and implement this method')
def consumePath(self, constant, parsed_item=None): # pylint: disable=no-self-use ; # pragma: no cover
parsed_item = list() if parsed_item is None else parsed_item
result = None
if parsed_item[0].endswith(constant):
result = parsed_item[1][1:-1]
return result
def consume(self, parsed_item=None): # pragma: no cover
parsed_item = list() if parsed_item is None else parsed_item
self.__parsed_item = parsed_item
def deserialize(self, xcconfig_line=''): # pylint: disable=no-self-use ; # pragma: no cover
_unused = xcconfig_line
raise Exception('Please subclass this class and implement this method')
| class Basekeyword(object):
def __init__(self):
self.__parsed_item = None
def __eq__(self, other):
raise exception('Please subclass this class and implement this method')
def serialize(self):
raise exception('Please subclass this class and implement this method')
def consume_path(self, constant, parsed_item=None):
parsed_item = list() if parsed_item is None else parsed_item
result = None
if parsed_item[0].endswith(constant):
result = parsed_item[1][1:-1]
return result
def consume(self, parsed_item=None):
parsed_item = list() if parsed_item is None else parsed_item
self.__parsed_item = parsed_item
def deserialize(self, xcconfig_line=''):
_unused = xcconfig_line
raise exception('Please subclass this class and implement this method') |
#coding:utf-8
class Configurer(object):
def __init__(self,config):
self._config = config
self._key = 'variables'
self._results = {}
def parse(self):
config_body = self._config.get('config_body')
self._results = self._parse(config_body)
return [(self._key,self._results)]
def _parse(self,body):
_result = {}
if isinstance(body, dict):
_result = body
elif isinstance(body, list):
for _item in body:
_result.update(self._parse(_item))
return _result
def close(self):
pass
| class Configurer(object):
def __init__(self, config):
self._config = config
self._key = 'variables'
self._results = {}
def parse(self):
config_body = self._config.get('config_body')
self._results = self._parse(config_body)
return [(self._key, self._results)]
def _parse(self, body):
_result = {}
if isinstance(body, dict):
_result = body
elif isinstance(body, list):
for _item in body:
_result.update(self._parse(_item))
return _result
def close(self):
pass |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
nums1.extend(nums2)
nums1.sort()
result = 0
length = len(nums1)
if length % 2 == 0:
result = (nums1[int(length / 2 - 1)] +
nums1[int(length / 2)]) / 2.0
else:
result = nums1[int(length / 2)]
return result
if __name__ == "__main__":
input1 = [1, 4, 2, 3]
input2 = [9, 8, 4, 1]
solution = Solution()
print("Input:", input1, input2)
print("Output:", solution.findMedianSortedArrays(input1, input2))
| class Solution(object):
def find_median_sorted_arrays(self, nums1, nums2):
nums1.extend(nums2)
nums1.sort()
result = 0
length = len(nums1)
if length % 2 == 0:
result = (nums1[int(length / 2 - 1)] + nums1[int(length / 2)]) / 2.0
else:
result = nums1[int(length / 2)]
return result
if __name__ == '__main__':
input1 = [1, 4, 2, 3]
input2 = [9, 8, 4, 1]
solution = solution()
print('Input:', input1, input2)
print('Output:', solution.findMedianSortedArrays(input1, input2)) |
# O(n) in time
def my_func(arr):
length = len(arr)
start = 0
end = length - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
ls = [1, 2, 3]
print(my_func(ls))
| def my_func(arr):
length = len(arr)
start = 0
end = length - 1
while start < end:
(arr[start], arr[end]) = (arr[end], arr[start])
start += 1
end -= 1
return arr
ls = [1, 2, 3]
print(my_func(ls)) |
# Create list of departments
departments = ['trash', 'streets', 'water']
# Create multiple sns topics using the following for loop
for dept in departments:
# For every department, create a general topic
sns.create_topic(Name="{}_general".format(dept))
# For every department, create a critical topic
sns.create_topic(Name="{}_critical".format(dept))
# Print all the topics in SNS
response = sns.list_topics()
print(response['Topics'])
# Removing the topics that are not critical from the messaging service
# Get the current list of topics
topics = sns.list_topics()['Topics']
for topic in topics:
# For each topic, if it is not marked critical, delete it
if "critical" not in topic['TopicArn']:
sns.delete_topic(TopicArn=topic['TopicArn'])
# Print the list of remaining critical topics
print(sns.list_topics()['Topics'])
| departments = ['trash', 'streets', 'water']
for dept in departments:
sns.create_topic(Name='{}_general'.format(dept))
sns.create_topic(Name='{}_critical'.format(dept))
response = sns.list_topics()
print(response['Topics'])
topics = sns.list_topics()['Topics']
for topic in topics:
if 'critical' not in topic['TopicArn']:
sns.delete_topic(TopicArn=topic['TopicArn'])
print(sns.list_topics()['Topics']) |
def beans(age1,age2):
print(age1, age2) # pre-swap
age1, age2 = age2, age1
# print(age1, age2) # post-swap
return age1, age2
def swap():
age1 = int(input("select a number for age1:"))
age2 = int(input("select a number for age2:"))
x,y=beans(age1,age2)
print(x,y)
| def beans(age1, age2):
print(age1, age2)
(age1, age2) = (age2, age1)
return (age1, age2)
def swap():
age1 = int(input('select a number for age1:'))
age2 = int(input('select a number for age2:'))
(x, y) = beans(age1, age2)
print(x, y) |
announcements = {'code': '000000', 'message': None, 'messageDetail': None, 'data': {'articles': [{'id': 72913, 'code': 'b9fbcf46da3a4d7f8f2d1bf1bd874665', 'title': 'Binance Adds BETA & BNX on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72876, 'code': '14e4354e11444c7092934e618f5eac64', 'title': 'Introducing the FC Porto Fan Token (PORTO) Token Sale on Binance Launchpad!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72806, 'code': '5c649babec204c27b7d7b734dba937ee', 'title': 'Binance Adds ALGO/RUB, AUD/USDC, LAZIO/BUSD, LUNA/BIDR, MANA/TRY, OXT/BUSD & SHIB/UAH Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72789, 'code': 'f9e1123ffc12458795716a0e027ff07a', 'title': 'Binance Will List Rari Governance Token (RGT)', 'body': None, 'type': None, 'catalogId': None,
'catalogName': None, 'publishDate': None}, {'id': 72774, 'code': '1f01516fe1f64bd08ed5a9f4207a9e5b', 'title': 'Binance Adds DOGE/BUSD Cross Margin & SHIB/DOGE Isolated Margin Pairs, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72633, 'code': '0337a0095c5b47f09a4882b6af624bdd', 'title': 'Binance Will List BinaryX (BNX) in the Innovation Zone', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72275, 'code': '8f89686731e04da3b9a98e20a0897413', 'title': 'Binance Futures Will Launch Coin-Margined FTM Perpetual Contracts with Up to 20X Leverage', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72200, 'code': 'e75ededcc356463a94786de743009a31', 'title': 'Binance Adds SHIB/DOGE Trading Pair', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71995, 'code': 'eabde816eb1043f6b1cb04215902b7c1', 'title': 'Binance Adds ADX/USDT, AUCTION/USDT, CELO/BUSD, FTM/RUB, NU/AUD, NU/RUB, REEF/BIDR & REEF/TRY Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71918, 'code': '28c68286fe9340cd97740774b4e13af9', 'title': 'Introducing Mines of Dalarnia (DAR) on Binance Launchpool! Farm DAR By Staking BNB and BUSD', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71904, 'code': '6ccecf57e6b24276a23ce49b77496efd', 'title': 'Binance Adds CHESS on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71467, 'code': 'aa4a4f5e4f1344ae921ad13c90d7a21f', 'title': 'Binance Futures Will Launch USDT-Margined CTSI Perpetual Contracts with Up to 25X Leverage', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71321, 'code': '8d0eaa46e96e490999a7e1a5cd6bebcd', 'title': 'Binance Adds FTM/AUD, FTM/BRL & SCRT/BUSD Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71304, 'code': '75ee0166b3ec43aba2266ef98893dd56', 'title': 'Binance Will List Tranchess (CHESS) in the Innovation Zone', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71268, 'code': 'c94a767e99244553b7a976ee8957a2c7', 'title': 'Binance Completes the Lazio Fan Token Subscription Launchpad and Will Open Trading for LAZIO', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}], 'total': 842}, 'success': True}
articles = [
{
"id":72913,
"code":"b9fbcf46da3a4d7f8f2d1bf1bd874665",
"title":"Binance Adds BETA & BNX on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72876,
"code":"14e4354e11444c7092934e618f5eac64",
"title":"Introducing the FC Porto Fan Token (PORTO) Token Sale on Binance Launchpad!",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72806,
"code":"5c649babec204c27b7d7b734dba937ee",
"title":"Binance Adds ALGO/RUB, AUD/USDC, LAZIO/BUSD, LUNA/BIDR, MANA/TRY, OXT/BUSD & SHIB/UAH Trading Pairs",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72789,
"code":"f9e1123ffc12458795716a0e027ff07a",
"title":"Binance Will List Rari Governance Token (RGT)",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72774,
"code":"1f01516fe1f64bd08ed5a9f4207a9e5b",
"title":"Binance Adds DOGE/BUSD Cross Margin & SHIB/DOGE Isolated Margin Pairs, Stablecoins Annual Interest Rate Starts at 6.20%!",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72633,
"code":"0337a0095c5b47f09a4882b6af624bdd",
"title":"Binance Will List BinaryX (BNX) in the Innovation Zone",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72275,
"code":"8f89686731e04da3b9a98e20a0897413",
"title":"Binance Futures Will Launch Coin-Margined FTM Perpetual Contracts with Up to 20X Leverage",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":72200,
"code":"e75ededcc356463a94786de743009a31",
"title":"Binance Adds SHIB/DOGE Trading Pair",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71995,
"code":"eabde816eb1043f6b1cb04215902b7c1",
"title":"Binance Adds ADX/USDT, AUCTION/USDT, CELO/BUSD, FTM/RUB, NU/AUD, NU/RUB, REEF/BIDR & REEF/TRY Trading Pairs",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71918,
"code":"28c68286fe9340cd97740774b4e13af9",
"title":"Introducing Mines of Dalarnia (DAR) on Binance Launchpool! Farm DAR By Staking BNB and BUSD",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71904,
"code":"6ccecf57e6b24276a23ce49b77496efd",
"title":"Binance Adds CHESS on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71467,
"code":"aa4a4f5e4f1344ae921ad13c90d7a21f",
"title":"Binance Futures Will Launch USDT-Margined CTSI Perpetual Contracts with Up to 25X Leverage",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71321,
"code":"8d0eaa46e96e490999a7e1a5cd6bebcd",
"title":"Binance Adds FTM/AUD, FTM/BRL & SCRT/BUSD Trading Pairs",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71304,
"code":"75ee0166b3ec43aba2266ef98893dd56",
"title":"Binance Will List Tranchess (CHESS) in the Innovation Zone",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
},
{
"id":71268,
"code":"c94a767e99244553b7a976ee8957a2c7",
"title":"Binance Completes the Lazio Fan Token Subscription Launchpad and Will Open Trading for LAZIO",
"body":"None",
"type":"None",
"catalogId":"None",
"catalogName":"None",
"publishDate":"None"
}
] | announcements = {'code': '000000', 'message': None, 'messageDetail': None, 'data': {'articles': [{'id': 72913, 'code': 'b9fbcf46da3a4d7f8f2d1bf1bd874665', 'title': 'Binance Adds BETA & BNX on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72876, 'code': '14e4354e11444c7092934e618f5eac64', 'title': 'Introducing the FC Porto Fan Token (PORTO) Token Sale on Binance Launchpad!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72806, 'code': '5c649babec204c27b7d7b734dba937ee', 'title': 'Binance Adds ALGO/RUB, AUD/USDC, LAZIO/BUSD, LUNA/BIDR, MANA/TRY, OXT/BUSD & SHIB/UAH Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72789, 'code': 'f9e1123ffc12458795716a0e027ff07a', 'title': 'Binance Will List Rari Governance Token (RGT)', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72774, 'code': '1f01516fe1f64bd08ed5a9f4207a9e5b', 'title': 'Binance Adds DOGE/BUSD Cross Margin & SHIB/DOGE Isolated Margin Pairs, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72633, 'code': '0337a0095c5b47f09a4882b6af624bdd', 'title': 'Binance Will List BinaryX (BNX) in the Innovation Zone', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72275, 'code': '8f89686731e04da3b9a98e20a0897413', 'title': 'Binance Futures Will Launch Coin-Margined FTM Perpetual Contracts with Up to 20X Leverage', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 72200, 'code': 'e75ededcc356463a94786de743009a31', 'title': 'Binance Adds SHIB/DOGE Trading Pair', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71995, 'code': 'eabde816eb1043f6b1cb04215902b7c1', 'title': 'Binance Adds ADX/USDT, AUCTION/USDT, CELO/BUSD, FTM/RUB, NU/AUD, NU/RUB, REEF/BIDR & REEF/TRY Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71918, 'code': '28c68286fe9340cd97740774b4e13af9', 'title': 'Introducing Mines of Dalarnia (DAR) on Binance Launchpool! Farm DAR By Staking BNB and BUSD', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71904, 'code': '6ccecf57e6b24276a23ce49b77496efd', 'title': 'Binance Adds CHESS on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71467, 'code': 'aa4a4f5e4f1344ae921ad13c90d7a21f', 'title': 'Binance Futures Will Launch USDT-Margined CTSI Perpetual Contracts with Up to 25X Leverage', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71321, 'code': '8d0eaa46e96e490999a7e1a5cd6bebcd', 'title': 'Binance Adds FTM/AUD, FTM/BRL & SCRT/BUSD Trading Pairs', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71304, 'code': '75ee0166b3ec43aba2266ef98893dd56', 'title': 'Binance Will List Tranchess (CHESS) in the Innovation Zone', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}, {'id': 71268, 'code': 'c94a767e99244553b7a976ee8957a2c7', 'title': 'Binance Completes the Lazio Fan Token Subscription Launchpad and Will Open Trading for LAZIO', 'body': None, 'type': None, 'catalogId': None, 'catalogName': None, 'publishDate': None}], 'total': 842}, 'success': True}
articles = [{'id': 72913, 'code': 'b9fbcf46da3a4d7f8f2d1bf1bd874665', 'title': 'Binance Adds BETA & BNX on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72876, 'code': '14e4354e11444c7092934e618f5eac64', 'title': 'Introducing the FC Porto Fan Token (PORTO) Token Sale on Binance Launchpad!', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72806, 'code': '5c649babec204c27b7d7b734dba937ee', 'title': 'Binance Adds ALGO/RUB, AUD/USDC, LAZIO/BUSD, LUNA/BIDR, MANA/TRY, OXT/BUSD & SHIB/UAH Trading Pairs', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72789, 'code': 'f9e1123ffc12458795716a0e027ff07a', 'title': 'Binance Will List Rari Governance Token (RGT)', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72774, 'code': '1f01516fe1f64bd08ed5a9f4207a9e5b', 'title': 'Binance Adds DOGE/BUSD Cross Margin & SHIB/DOGE Isolated Margin Pairs, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72633, 'code': '0337a0095c5b47f09a4882b6af624bdd', 'title': 'Binance Will List BinaryX (BNX) in the Innovation Zone', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72275, 'code': '8f89686731e04da3b9a98e20a0897413', 'title': 'Binance Futures Will Launch Coin-Margined FTM Perpetual Contracts with Up to 20X Leverage', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 72200, 'code': 'e75ededcc356463a94786de743009a31', 'title': 'Binance Adds SHIB/DOGE Trading Pair', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71995, 'code': 'eabde816eb1043f6b1cb04215902b7c1', 'title': 'Binance Adds ADX/USDT, AUCTION/USDT, CELO/BUSD, FTM/RUB, NU/AUD, NU/RUB, REEF/BIDR & REEF/TRY Trading Pairs', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71918, 'code': '28c68286fe9340cd97740774b4e13af9', 'title': 'Introducing Mines of Dalarnia (DAR) on Binance Launchpool! Farm DAR By Staking BNB and BUSD', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71904, 'code': '6ccecf57e6b24276a23ce49b77496efd', 'title': 'Binance Adds CHESS on Isolated Margin, Stablecoins Annual Interest Rate Starts at 6.20%!', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71467, 'code': 'aa4a4f5e4f1344ae921ad13c90d7a21f', 'title': 'Binance Futures Will Launch USDT-Margined CTSI Perpetual Contracts with Up to 25X Leverage', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71321, 'code': '8d0eaa46e96e490999a7e1a5cd6bebcd', 'title': 'Binance Adds FTM/AUD, FTM/BRL & SCRT/BUSD Trading Pairs', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71304, 'code': '75ee0166b3ec43aba2266ef98893dd56', 'title': 'Binance Will List Tranchess (CHESS) in the Innovation Zone', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}, {'id': 71268, 'code': 'c94a767e99244553b7a976ee8957a2c7', 'title': 'Binance Completes the Lazio Fan Token Subscription Launchpad and Will Open Trading for LAZIO', 'body': 'None', 'type': 'None', 'catalogId': 'None', 'catalogName': 'None', 'publishDate': 'None'}] |
data = (
'Pan ', # 0x00
'Yang ', # 0x01
'Lei ', # 0x02
'Sa ', # 0x03
'Shu ', # 0x04
'Zan ', # 0x05
'Nian ', # 0x06
'Xian ', # 0x07
'Jun ', # 0x08
'Huo ', # 0x09
'Li ', # 0x0a
'La ', # 0x0b
'Han ', # 0x0c
'Ying ', # 0x0d
'Lu ', # 0x0e
'Long ', # 0x0f
'Qian ', # 0x10
'Qian ', # 0x11
'Zan ', # 0x12
'Qian ', # 0x13
'Lan ', # 0x14
'San ', # 0x15
'Ying ', # 0x16
'Mei ', # 0x17
'Rang ', # 0x18
'Chan ', # 0x19
None, # 0x1a
'Cuan ', # 0x1b
'Xi ', # 0x1c
'She ', # 0x1d
'Luo ', # 0x1e
'Jun ', # 0x1f
'Mi ', # 0x20
'Li ', # 0x21
'Zan ', # 0x22
'Luan ', # 0x23
'Tan ', # 0x24
'Zuan ', # 0x25
'Li ', # 0x26
'Dian ', # 0x27
'Wa ', # 0x28
'Dang ', # 0x29
'Jiao ', # 0x2a
'Jue ', # 0x2b
'Lan ', # 0x2c
'Li ', # 0x2d
'Nang ', # 0x2e
'Zhi ', # 0x2f
'Gui ', # 0x30
'Gui ', # 0x31
'Qi ', # 0x32
'Xin ', # 0x33
'Pu ', # 0x34
'Sui ', # 0x35
'Shou ', # 0x36
'Kao ', # 0x37
'You ', # 0x38
'Gai ', # 0x39
'Yi ', # 0x3a
'Gong ', # 0x3b
'Gan ', # 0x3c
'Ban ', # 0x3d
'Fang ', # 0x3e
'Zheng ', # 0x3f
'Bo ', # 0x40
'Dian ', # 0x41
'Kou ', # 0x42
'Min ', # 0x43
'Wu ', # 0x44
'Gu ', # 0x45
'He ', # 0x46
'Ce ', # 0x47
'Xiao ', # 0x48
'Mi ', # 0x49
'Chu ', # 0x4a
'Ge ', # 0x4b
'Di ', # 0x4c
'Xu ', # 0x4d
'Jiao ', # 0x4e
'Min ', # 0x4f
'Chen ', # 0x50
'Jiu ', # 0x51
'Zhen ', # 0x52
'Duo ', # 0x53
'Yu ', # 0x54
'Chi ', # 0x55
'Ao ', # 0x56
'Bai ', # 0x57
'Xu ', # 0x58
'Jiao ', # 0x59
'Duo ', # 0x5a
'Lian ', # 0x5b
'Nie ', # 0x5c
'Bi ', # 0x5d
'Chang ', # 0x5e
'Dian ', # 0x5f
'Duo ', # 0x60
'Yi ', # 0x61
'Gan ', # 0x62
'San ', # 0x63
'Ke ', # 0x64
'Yan ', # 0x65
'Dun ', # 0x66
'Qi ', # 0x67
'Dou ', # 0x68
'Xiao ', # 0x69
'Duo ', # 0x6a
'Jiao ', # 0x6b
'Jing ', # 0x6c
'Yang ', # 0x6d
'Xia ', # 0x6e
'Min ', # 0x6f
'Shu ', # 0x70
'Ai ', # 0x71
'Qiao ', # 0x72
'Ai ', # 0x73
'Zheng ', # 0x74
'Di ', # 0x75
'Zhen ', # 0x76
'Fu ', # 0x77
'Shu ', # 0x78
'Liao ', # 0x79
'Qu ', # 0x7a
'Xiong ', # 0x7b
'Xi ', # 0x7c
'Jiao ', # 0x7d
'Sen ', # 0x7e
'Jiao ', # 0x7f
'Zhuo ', # 0x80
'Yi ', # 0x81
'Lian ', # 0x82
'Bi ', # 0x83
'Li ', # 0x84
'Xiao ', # 0x85
'Xiao ', # 0x86
'Wen ', # 0x87
'Xue ', # 0x88
'Qi ', # 0x89
'Qi ', # 0x8a
'Zhai ', # 0x8b
'Bin ', # 0x8c
'Jue ', # 0x8d
'Zhai ', # 0x8e
None, # 0x8f
'Fei ', # 0x90
'Ban ', # 0x91
'Ban ', # 0x92
'Lan ', # 0x93
'Yu ', # 0x94
'Lan ', # 0x95
'Wei ', # 0x96
'Dou ', # 0x97
'Sheng ', # 0x98
'Liao ', # 0x99
'Jia ', # 0x9a
'Hu ', # 0x9b
'Xie ', # 0x9c
'Jia ', # 0x9d
'Yu ', # 0x9e
'Zhen ', # 0x9f
'Jiao ', # 0xa0
'Wo ', # 0xa1
'Tou ', # 0xa2
'Chu ', # 0xa3
'Jin ', # 0xa4
'Chi ', # 0xa5
'Yin ', # 0xa6
'Fu ', # 0xa7
'Qiang ', # 0xa8
'Zhan ', # 0xa9
'Qu ', # 0xaa
'Zhuo ', # 0xab
'Zhan ', # 0xac
'Duan ', # 0xad
'Zhuo ', # 0xae
'Si ', # 0xaf
'Xin ', # 0xb0
'Zhuo ', # 0xb1
'Zhuo ', # 0xb2
'Qin ', # 0xb3
'Lin ', # 0xb4
'Zhuo ', # 0xb5
'Chu ', # 0xb6
'Duan ', # 0xb7
'Zhu ', # 0xb8
'Fang ', # 0xb9
'Xie ', # 0xba
'Hang ', # 0xbb
'Yu ', # 0xbc
'Shi ', # 0xbd
'Pei ', # 0xbe
'You ', # 0xbf
'Mye ', # 0xc0
'Pang ', # 0xc1
'Qi ', # 0xc2
'Zhan ', # 0xc3
'Mao ', # 0xc4
'Lu ', # 0xc5
'Pei ', # 0xc6
'Pi ', # 0xc7
'Liu ', # 0xc8
'Fu ', # 0xc9
'Fang ', # 0xca
'Xuan ', # 0xcb
'Jing ', # 0xcc
'Jing ', # 0xcd
'Ni ', # 0xce
'Zu ', # 0xcf
'Zhao ', # 0xd0
'Yi ', # 0xd1
'Liu ', # 0xd2
'Shao ', # 0xd3
'Jian ', # 0xd4
'Es ', # 0xd5
'Yi ', # 0xd6
'Qi ', # 0xd7
'Zhi ', # 0xd8
'Fan ', # 0xd9
'Piao ', # 0xda
'Fan ', # 0xdb
'Zhan ', # 0xdc
'Guai ', # 0xdd
'Sui ', # 0xde
'Yu ', # 0xdf
'Wu ', # 0xe0
'Ji ', # 0xe1
'Ji ', # 0xe2
'Ji ', # 0xe3
'Huo ', # 0xe4
'Ri ', # 0xe5
'Dan ', # 0xe6
'Jiu ', # 0xe7
'Zhi ', # 0xe8
'Zao ', # 0xe9
'Xie ', # 0xea
'Tiao ', # 0xeb
'Xun ', # 0xec
'Xu ', # 0xed
'Xu ', # 0xee
'Xu ', # 0xef
'Gan ', # 0xf0
'Han ', # 0xf1
'Tai ', # 0xf2
'Di ', # 0xf3
'Xu ', # 0xf4
'Chan ', # 0xf5
'Shi ', # 0xf6
'Kuang ', # 0xf7
'Yang ', # 0xf8
'Shi ', # 0xf9
'Wang ', # 0xfa
'Min ', # 0xfb
'Min ', # 0xfc
'Tun ', # 0xfd
'Chun ', # 0xfe
'Wu ', # 0xff
)
| data = ('Pan ', 'Yang ', 'Lei ', 'Sa ', 'Shu ', 'Zan ', 'Nian ', 'Xian ', 'Jun ', 'Huo ', 'Li ', 'La ', 'Han ', 'Ying ', 'Lu ', 'Long ', 'Qian ', 'Qian ', 'Zan ', 'Qian ', 'Lan ', 'San ', 'Ying ', 'Mei ', 'Rang ', 'Chan ', None, 'Cuan ', 'Xi ', 'She ', 'Luo ', 'Jun ', 'Mi ', 'Li ', 'Zan ', 'Luan ', 'Tan ', 'Zuan ', 'Li ', 'Dian ', 'Wa ', 'Dang ', 'Jiao ', 'Jue ', 'Lan ', 'Li ', 'Nang ', 'Zhi ', 'Gui ', 'Gui ', 'Qi ', 'Xin ', 'Pu ', 'Sui ', 'Shou ', 'Kao ', 'You ', 'Gai ', 'Yi ', 'Gong ', 'Gan ', 'Ban ', 'Fang ', 'Zheng ', 'Bo ', 'Dian ', 'Kou ', 'Min ', 'Wu ', 'Gu ', 'He ', 'Ce ', 'Xiao ', 'Mi ', 'Chu ', 'Ge ', 'Di ', 'Xu ', 'Jiao ', 'Min ', 'Chen ', 'Jiu ', 'Zhen ', 'Duo ', 'Yu ', 'Chi ', 'Ao ', 'Bai ', 'Xu ', 'Jiao ', 'Duo ', 'Lian ', 'Nie ', 'Bi ', 'Chang ', 'Dian ', 'Duo ', 'Yi ', 'Gan ', 'San ', 'Ke ', 'Yan ', 'Dun ', 'Qi ', 'Dou ', 'Xiao ', 'Duo ', 'Jiao ', 'Jing ', 'Yang ', 'Xia ', 'Min ', 'Shu ', 'Ai ', 'Qiao ', 'Ai ', 'Zheng ', 'Di ', 'Zhen ', 'Fu ', 'Shu ', 'Liao ', 'Qu ', 'Xiong ', 'Xi ', 'Jiao ', 'Sen ', 'Jiao ', 'Zhuo ', 'Yi ', 'Lian ', 'Bi ', 'Li ', 'Xiao ', 'Xiao ', 'Wen ', 'Xue ', 'Qi ', 'Qi ', 'Zhai ', 'Bin ', 'Jue ', 'Zhai ', None, 'Fei ', 'Ban ', 'Ban ', 'Lan ', 'Yu ', 'Lan ', 'Wei ', 'Dou ', 'Sheng ', 'Liao ', 'Jia ', 'Hu ', 'Xie ', 'Jia ', 'Yu ', 'Zhen ', 'Jiao ', 'Wo ', 'Tou ', 'Chu ', 'Jin ', 'Chi ', 'Yin ', 'Fu ', 'Qiang ', 'Zhan ', 'Qu ', 'Zhuo ', 'Zhan ', 'Duan ', 'Zhuo ', 'Si ', 'Xin ', 'Zhuo ', 'Zhuo ', 'Qin ', 'Lin ', 'Zhuo ', 'Chu ', 'Duan ', 'Zhu ', 'Fang ', 'Xie ', 'Hang ', 'Yu ', 'Shi ', 'Pei ', 'You ', 'Mye ', 'Pang ', 'Qi ', 'Zhan ', 'Mao ', 'Lu ', 'Pei ', 'Pi ', 'Liu ', 'Fu ', 'Fang ', 'Xuan ', 'Jing ', 'Jing ', 'Ni ', 'Zu ', 'Zhao ', 'Yi ', 'Liu ', 'Shao ', 'Jian ', 'Es ', 'Yi ', 'Qi ', 'Zhi ', 'Fan ', 'Piao ', 'Fan ', 'Zhan ', 'Guai ', 'Sui ', 'Yu ', 'Wu ', 'Ji ', 'Ji ', 'Ji ', 'Huo ', 'Ri ', 'Dan ', 'Jiu ', 'Zhi ', 'Zao ', 'Xie ', 'Tiao ', 'Xun ', 'Xu ', 'Xu ', 'Xu ', 'Gan ', 'Han ', 'Tai ', 'Di ', 'Xu ', 'Chan ', 'Shi ', 'Kuang ', 'Yang ', 'Shi ', 'Wang ', 'Min ', 'Min ', 'Tun ', 'Chun ', 'Wu ') |
# This file was automatically generated on 2020-04-30T19:04:34.713080
# by script /code/nc/extract_nc/ansi_escape_code.py
# from ANSI escape codes
COLORS = {
'Black': (0, 0, 0),
'Red': (255, 0, 0),
'Green': (0, 255, 0),
'Yellow': (255, 255, 0),
'Blue': (0, 0, 255),
'Magenta': (255, 0, 255),
'Cyan': (0, 255, 255),
'White': (255, 255, 255),
'Bright Black': None,
'Bright Red': None,
'Bright Green': (144, 238, 144),
'Bright Yellow': (255, 255, 224),
'Bright Blue': (173, 216, 230),
'Bright Magenta': None,
'Bright Cyan': (224, 255, 255),
'Bright White': None,
}
| colors = {'Black': (0, 0, 0), 'Red': (255, 0, 0), 'Green': (0, 255, 0), 'Yellow': (255, 255, 0), 'Blue': (0, 0, 255), 'Magenta': (255, 0, 255), 'Cyan': (0, 255, 255), 'White': (255, 255, 255), 'Bright Black': None, 'Bright Red': None, 'Bright Green': (144, 238, 144), 'Bright Yellow': (255, 255, 224), 'Bright Blue': (173, 216, 230), 'Bright Magenta': None, 'Bright Cyan': (224, 255, 255), 'Bright White': None} |
MIME_TYPES = dict(png='image/png',
svg='image/svg+xml',
xlsx='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
sdf='chemical/x-mdl-sdfile', zip='application/zip',
csv='text/csv', mol='chemical/x-mdl-molfile', smi='chemical/x-daylight-smiles',
cif='chemical/x-cif', pdf='application/pdf')
def get_content_type(path):
lwr = path.lower()
if lwr.endswith('.mol'):
return MIME_TYPES['mol']
if lwr.endswith('.sdf'):
return MIME_TYPES['sdf']
if lwr.endswith('.smi'):
return MIME_TYPES['smi']
if lwr.endswith('.cif'):
return MIME_TYPES['cif']
if lwr.endswith('.pdf'):
return MIME_TYPES['pdf']
if lwr.endswith('.csv'):
return MIME_TYPES['csv']
if lwr.endswith('.xlsx'):
return MIME_TYPES['xlsx']
| mime_types = dict(png='image/png', svg='image/svg+xml', xlsx='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', sdf='chemical/x-mdl-sdfile', zip='application/zip', csv='text/csv', mol='chemical/x-mdl-molfile', smi='chemical/x-daylight-smiles', cif='chemical/x-cif', pdf='application/pdf')
def get_content_type(path):
lwr = path.lower()
if lwr.endswith('.mol'):
return MIME_TYPES['mol']
if lwr.endswith('.sdf'):
return MIME_TYPES['sdf']
if lwr.endswith('.smi'):
return MIME_TYPES['smi']
if lwr.endswith('.cif'):
return MIME_TYPES['cif']
if lwr.endswith('.pdf'):
return MIME_TYPES['pdf']
if lwr.endswith('.csv'):
return MIME_TYPES['csv']
if lwr.endswith('.xlsx'):
return MIME_TYPES['xlsx'] |
class PARA:
CNS_ip = '192.168.0.55'
CNS_port = 7001
Remote_ip = '192.168.0.29'
Remote_port = 7001
| class Para:
cns_ip = '192.168.0.55'
cns_port = 7001
remote_ip = '192.168.0.29'
remote_port = 7001 |
RED='\033[01;31m'
GREEN='\033[01;32m'
YELLOW='\033[01;33m'
BLUE='\033[01;34m'
VIOLET='\033[01;35m'
LIGHT_BLUE='\033[01;36m'
WHITE='\033[01;37m'
VOID='\033[0m'
#color print
def print_c(msg, end='\n'):
print(msg+VOID, end=end)
| red = '\x1b[01;31m'
green = '\x1b[01;32m'
yellow = '\x1b[01;33m'
blue = '\x1b[01;34m'
violet = '\x1b[01;35m'
light_blue = '\x1b[01;36m'
white = '\x1b[01;37m'
void = '\x1b[0m'
def print_c(msg, end='\n'):
print(msg + VOID, end=end) |
#BINARY TO NUMBER
b=str(input("ENTER THE BINARY :"))
l=len(b)
c=0
for a in b:
x=int(a)
l=l-1
if (x==1):
power=pow(2,(l))
print("2^",(l),"=",power)
c=c+power
print("SUM =",c) | b = str(input('ENTER THE BINARY :'))
l = len(b)
c = 0
for a in b:
x = int(a)
l = l - 1
if x == 1:
power = pow(2, l)
print('2^', l, '=', power)
c = c + power
print('SUM =', c) |
#!/usr/bin/python
# Copyright (c) 2021 Samsung Electronics Co., Ltd. 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.
UNIT_SYMBOLS = ['B', 'K', 'M', 'G', 'T']
CHAR_SYMBOLS = {'operator': '#', 'tensor': '%', 'buffer': '&'}
def ConvertBytesToHuman(n):
n = int(n)
if n < 0:
return 0
format_str = "%(val)3.1f%(symb)s"
prefix = {}
for i, s in enumerate(UNIT_SYMBOLS[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(UNIT_SYMBOLS[1:]):
if n >= prefix[symbol]:
v = float(n) / prefix[symbol]
return format_str % dict(symb=symbol, val=v)
return format_str % dict(symb=UNIT_SYMBOLS[0], val=n)
def GetStringTensorIndex(tensors):
return_string = []
return_string.append("[")
for idx in range(len(tensors)):
if idx != 0:
return_string.append(", ")
return_string.append(CHAR_SYMBOLS['tensor'] + str(tensors[idx].tensor_idx))
return_string.append("]")
return "".join(return_string)
def GetStringShape(tensor):
if tensor.tf_tensor.ShapeLength() == 0:
return "Scalar"
return_string = []
return_string.append("[")
for shape_idx in range(tensor.tf_tensor.ShapeLength()):
if (shape_idx != 0):
return_string.append(", ")
# when shape signature is -1, that means unknown dim
if tensor.tf_tensor.ShapeSignature(shape_idx) != -1:
return_string.append(str(tensor.tf_tensor.Shape(shape_idx)))
else:
return_string.append("-1")
return_string.append("]")
return "".join(return_string)
def GetStringTensor(tensor):
info = ""
if tensor.tensor_idx < 0:
info = "{0:5}".format(CHAR_SYMBOLS['tensor'] + str(tensor.tensor_idx))
else:
buffer_idx = tensor.tf_tensor.Buffer()
buffer_str = "Empty" if buffer_idx == 0 else str(buffer_idx)
isEmpty = "Filled"
if (tensor.tf_buffer.DataLength() == 0):
isEmpty = " Empty"
shape_str = GetStringShape(tensor)
type_name = tensor.type_name
shape_name = ""
if tensor.tf_tensor.Name() != 0:
shape_name = tensor.tf_tensor.Name()
memory_size = ConvertBytesToHuman(tensor.memory_size)
info = "{:5} : buffer {:5} | {} | {:7} | Memory {:6} | Shape {} ({})".format(
CHAR_SYMBOLS['tensor'] + str(tensor.tensor_idx),
CHAR_SYMBOLS['buffer'] + buffer_str, isEmpty, type_name, memory_size,
shape_str, shape_name)
return info
def GetStringPadding(options):
if options.Padding() == 0:
return "SAME"
elif options.Padding() == 1:
return "VALID"
else:
return "** wrong padding value **"
def GetStringOption(op_name, options):
if (op_name == "AVERAGE_POOL_2D" or op_name == "MAX_POOL_2D"):
return "{}, {}, {}".format(
"Filter W:H = {}:{}".format(options.FilterWidth(), options.FilterHeight()),
"Stride W:H = {}:{}".format(options.StrideW(),
options.StrideH()), "Padding = {}".format(
GetStringPadding(options)))
elif (op_name == "CONV_2D"):
return "{}, {}, {}".format(
"Stride W:H = {}:{}".format(options.StrideW(), options.StrideH()),
"Dilation W:H = {}:{}".format(options.DilationWFactor(),
options.DilationHFactor()),
"Padding = {}".format(GetStringPadding(options)))
elif (op_name == "DEPTHWISE_CONV_2D"):
# yapf: disable
return "{}, {}, {}, {}".format(
"Stride W:H = {}:{}".format(options.StrideW(),
options.StrideH()),
"Dilation W:H = {}:{}".format(options.DilationWFactor(),
options.DilationHFactor()),
"Padding = {}".format(GetStringPadding(options)),
"DepthMultiplier = {}".format(options.DepthMultiplier()))
# yapf: enable
elif (op_name == "STRIDED_SLICE"):
# yapf: disable
return "{}, {}, {}, {}, {}".format(
"begin_mask({})".format(options.BeginMask()),
"end_mask({})".format(options.EndMask()),
"ellipsis_mask({})".format(options.EllipsisMask()),
"new_axis_mask({})".format(options.NewAxisMask()),
"shrink_axis_mask({})".format(options.ShrinkAxisMask()))
# yapf: enable
else:
return None
class StringBuilder(object):
def __init__(self):
pass
def GraphStats(self, stats):
results = []
results.append("Number of all operator types: {}".format(len(stats.op_counts)))
# op type stats
for op_name in sorted(stats.op_counts.keys()):
occur = stats.op_counts[op_name]
optype_info_str = " {:38}: {:4}".format(op_name, occur)
results.append(optype_info_str)
summary_str = "{0:40}: {1:4}".format("Number of all operators",
sum(stats.op_counts.values()))
results.append(summary_str)
results.append('\n')
# memory stats
results.append("Expected TOTAL memory: {}".format(
ConvertBytesToHuman(stats.total_memory)))
results.append("Expected FILLED memory: {}".format(
ConvertBytesToHuman(stats.filled_memory)))
results.append('\n')
return "\n".join(results)
def Operator(self, operator, depth_str=""):
results = []
results.append("{}{} {}".format(
depth_str, CHAR_SYMBOLS['operator'] + str(operator.operator_idx),
operator.opcode_str))
results.append("{} Fused Activation: {}".format(depth_str,
operator.fused_activation))
results.append("{} Input Tensors{}".format(depth_str,
GetStringTensorIndex(
operator.inputs)))
for tensor in operator.inputs:
results.append(self.Tensor(tensor, depth_str + " "))
results.append("{} Output Tensors{}".format(
depth_str, GetStringTensorIndex(operator.outputs)))
for tensor in operator.outputs:
results.append(self.Tensor(tensor, depth_str + " "))
# operator option
# Some operations does not have option. In such case no option is printed
if operator.options != None:
option_str = GetStringOption(operator.opcode_str, operator.options)
if option_str != None:
results.append("{} Options".format(depth_str))
results.append("{} {}".format(depth_str, option_str))
return "\n".join(results)
def Tensor(self, tensor, depth_str=""):
results = []
if depth_str != "":
results.append(depth_str)
results.append(GetStringTensor(tensor))
return "".join(results)
| unit_symbols = ['B', 'K', 'M', 'G', 'T']
char_symbols = {'operator': '#', 'tensor': '%', 'buffer': '&'}
def convert_bytes_to_human(n):
n = int(n)
if n < 0:
return 0
format_str = '%(val)3.1f%(symb)s'
prefix = {}
for (i, s) in enumerate(UNIT_SYMBOLS[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(UNIT_SYMBOLS[1:]):
if n >= prefix[symbol]:
v = float(n) / prefix[symbol]
return format_str % dict(symb=symbol, val=v)
return format_str % dict(symb=UNIT_SYMBOLS[0], val=n)
def get_string_tensor_index(tensors):
return_string = []
return_string.append('[')
for idx in range(len(tensors)):
if idx != 0:
return_string.append(', ')
return_string.append(CHAR_SYMBOLS['tensor'] + str(tensors[idx].tensor_idx))
return_string.append(']')
return ''.join(return_string)
def get_string_shape(tensor):
if tensor.tf_tensor.ShapeLength() == 0:
return 'Scalar'
return_string = []
return_string.append('[')
for shape_idx in range(tensor.tf_tensor.ShapeLength()):
if shape_idx != 0:
return_string.append(', ')
if tensor.tf_tensor.ShapeSignature(shape_idx) != -1:
return_string.append(str(tensor.tf_tensor.Shape(shape_idx)))
else:
return_string.append('-1')
return_string.append(']')
return ''.join(return_string)
def get_string_tensor(tensor):
info = ''
if tensor.tensor_idx < 0:
info = '{0:5}'.format(CHAR_SYMBOLS['tensor'] + str(tensor.tensor_idx))
else:
buffer_idx = tensor.tf_tensor.Buffer()
buffer_str = 'Empty' if buffer_idx == 0 else str(buffer_idx)
is_empty = 'Filled'
if tensor.tf_buffer.DataLength() == 0:
is_empty = ' Empty'
shape_str = get_string_shape(tensor)
type_name = tensor.type_name
shape_name = ''
if tensor.tf_tensor.Name() != 0:
shape_name = tensor.tf_tensor.Name()
memory_size = convert_bytes_to_human(tensor.memory_size)
info = '{:5} : buffer {:5} | {} | {:7} | Memory {:6} | Shape {} ({})'.format(CHAR_SYMBOLS['tensor'] + str(tensor.tensor_idx), CHAR_SYMBOLS['buffer'] + buffer_str, isEmpty, type_name, memory_size, shape_str, shape_name)
return info
def get_string_padding(options):
if options.Padding() == 0:
return 'SAME'
elif options.Padding() == 1:
return 'VALID'
else:
return '** wrong padding value **'
def get_string_option(op_name, options):
if op_name == 'AVERAGE_POOL_2D' or op_name == 'MAX_POOL_2D':
return '{}, {}, {}'.format('Filter W:H = {}:{}'.format(options.FilterWidth(), options.FilterHeight()), 'Stride W:H = {}:{}'.format(options.StrideW(), options.StrideH()), 'Padding = {}'.format(get_string_padding(options)))
elif op_name == 'CONV_2D':
return '{}, {}, {}'.format('Stride W:H = {}:{}'.format(options.StrideW(), options.StrideH()), 'Dilation W:H = {}:{}'.format(options.DilationWFactor(), options.DilationHFactor()), 'Padding = {}'.format(get_string_padding(options)))
elif op_name == 'DEPTHWISE_CONV_2D':
return '{}, {}, {}, {}'.format('Stride W:H = {}:{}'.format(options.StrideW(), options.StrideH()), 'Dilation W:H = {}:{}'.format(options.DilationWFactor(), options.DilationHFactor()), 'Padding = {}'.format(get_string_padding(options)), 'DepthMultiplier = {}'.format(options.DepthMultiplier()))
elif op_name == 'STRIDED_SLICE':
return '{}, {}, {}, {}, {}'.format('begin_mask({})'.format(options.BeginMask()), 'end_mask({})'.format(options.EndMask()), 'ellipsis_mask({})'.format(options.EllipsisMask()), 'new_axis_mask({})'.format(options.NewAxisMask()), 'shrink_axis_mask({})'.format(options.ShrinkAxisMask()))
else:
return None
class Stringbuilder(object):
def __init__(self):
pass
def graph_stats(self, stats):
results = []
results.append('Number of all operator types: {}'.format(len(stats.op_counts)))
for op_name in sorted(stats.op_counts.keys()):
occur = stats.op_counts[op_name]
optype_info_str = ' {:38}: {:4}'.format(op_name, occur)
results.append(optype_info_str)
summary_str = '{0:40}: {1:4}'.format('Number of all operators', sum(stats.op_counts.values()))
results.append(summary_str)
results.append('\n')
results.append('Expected TOTAL memory: {}'.format(convert_bytes_to_human(stats.total_memory)))
results.append('Expected FILLED memory: {}'.format(convert_bytes_to_human(stats.filled_memory)))
results.append('\n')
return '\n'.join(results)
def operator(self, operator, depth_str=''):
results = []
results.append('{}{} {}'.format(depth_str, CHAR_SYMBOLS['operator'] + str(operator.operator_idx), operator.opcode_str))
results.append('{} Fused Activation: {}'.format(depth_str, operator.fused_activation))
results.append('{} Input Tensors{}'.format(depth_str, get_string_tensor_index(operator.inputs)))
for tensor in operator.inputs:
results.append(self.Tensor(tensor, depth_str + ' '))
results.append('{} Output Tensors{}'.format(depth_str, get_string_tensor_index(operator.outputs)))
for tensor in operator.outputs:
results.append(self.Tensor(tensor, depth_str + ' '))
if operator.options != None:
option_str = get_string_option(operator.opcode_str, operator.options)
if option_str != None:
results.append('{} Options'.format(depth_str))
results.append('{} {}'.format(depth_str, option_str))
return '\n'.join(results)
def tensor(self, tensor, depth_str=''):
results = []
if depth_str != '':
results.append(depth_str)
results.append(get_string_tensor(tensor))
return ''.join(results) |
class Solution:
def minDeletionSize(self, A):
res = 0
cur = [""] * len(A)
for col in zip(*A):
cur2 = list(zip(cur, col))
if cur2 == sorted(cur2):
cur = cur2
else:
res += 1
return res | class Solution:
def min_deletion_size(self, A):
res = 0
cur = [''] * len(A)
for col in zip(*A):
cur2 = list(zip(cur, col))
if cur2 == sorted(cur2):
cur = cur2
else:
res += 1
return res |
class Solution:
def numDecodings(self, s: str) -> int:
preDecode, curDecode, preDig = 0, s[0] > "0", ""
for l in s:
preDecode, curDecode, preDig = (
curDecode,
(l > "0") * curDecode + (9 < int(preDig + l) < 27) * preDecode,
l,
)
return curDecode
| class Solution:
def num_decodings(self, s: str) -> int:
(pre_decode, cur_decode, pre_dig) = (0, s[0] > '0', '')
for l in s:
(pre_decode, cur_decode, pre_dig) = (curDecode, (l > '0') * curDecode + (9 < int(preDig + l) < 27) * preDecode, l)
return curDecode |
def dice_credits():
print("Credits:")
print("")
print("This code was initially put together by DNEAVES.")
print('Documentation can be found at: http://github.com/DNEAVES/CLIDice')
print("")
print("This software is licensed under an MIT License.")
print('You can read the whole thing by typing "license".')
print("")
print("You are free to fork, distribute, whatever, as long as you abide to the terms of that license.")
print("Thanks for checking out this program, and this page :)")
print("")
| def dice_credits():
print('Credits:')
print('')
print('This code was initially put together by DNEAVES.')
print('Documentation can be found at: http://github.com/DNEAVES/CLIDice')
print('')
print('This software is licensed under an MIT License.')
print('You can read the whole thing by typing "license".')
print('')
print('You are free to fork, distribute, whatever, as long as you abide to the terms of that license.')
print('Thanks for checking out this program, and this page :)')
print('') |
'''
02 - Loading and exploring a JSON
Now that you know what a JSON is, you'll load one into your Python environment
and explore it yourself. Here, you'll load the JSON 'a_movie.json' into the
variable json_data, which will be a dictionary. You'll then explore the JSON
contents by printing the key-value pairs of json_data to the shell.
Instructions:
- Load the JSON 'a_movie.json' into the variable json_data within the context
provided by the with statement. To do so, use the function json.load() within
the context manager.
- Use a for loop to print all key-value pairs in the dictionary json_data. Recall
that you can access a value in a dictionary using the syntax: dictionary[key]
'''
# Load JSON: json_data
with open("a_movie.json") as json_file:
json_data = json.load(json_file)
# Print each key-value pair in json_data
for k in json_data.keys():
print(k + ': ', json_data[k])
| """
02 - Loading and exploring a JSON
Now that you know what a JSON is, you'll load one into your Python environment
and explore it yourself. Here, you'll load the JSON 'a_movie.json' into the
variable json_data, which will be a dictionary. You'll then explore the JSON
contents by printing the key-value pairs of json_data to the shell.
Instructions:
- Load the JSON 'a_movie.json' into the variable json_data within the context
provided by the with statement. To do so, use the function json.load() within
the context manager.
- Use a for loop to print all key-value pairs in the dictionary json_data. Recall
that you can access a value in a dictionary using the syntax: dictionary[key]
"""
with open('a_movie.json') as json_file:
json_data = json.load(json_file)
for k in json_data.keys():
print(k + ': ', json_data[k]) |
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
n = floor(log2(N)) + 1
bitmask = (1 << n) - 1
return bitmask ^ N | class Solution:
def bitwise_complement(self, N: int) -> int:
if N == 0:
return 1
n = floor(log2(N)) + 1
bitmask = (1 << n) - 1
return bitmask ^ N |
# A theater seating chart is implemented as a table of ticket prices, like this:
# 10 10 10 10 10 10 10 10 10 10
# 10 10 10 10 10 10 10 10 10 10
# 10 10 10 10 10 10 10 10 10 10
# 10 10 20 20 20 20 20 20 10 10
# 10 10 20 20 20 20 20 20 10 10
# 10 10 20 20 20 20 20 20 10 10
# 20 20 30 30 40 40 30 30 20 20
# 20 30 30 40 50 50 40 30 30 20
# 30 40 50 50 50 50 50 50 40 30
#
# Write a program that prompts users to
# pick either a seat or a price. Mark sold
# seats by changing the price to 0. When
# a user specifies a seat, make sure it is
# available. When a user specifies a price,
# find any seat with that price.
# FUNCTIONS
def printSeats(seats):
for i in range(len(seats[0]) - 1):
print(seats[i])
def findSeat(seats, pickChoice):
if pickChoice.lower() == "p":
price = int(input("\nEnter the price(10, 20, 30, 40 or 50): "))
seatFound = False
for i in range(len(seats)):
for j in range(len(seats[0])):
if seats[i][j] == price and not seatFound:
seatFound = True
seats[i][j] = 0
print("\nYour seat is in row %d and seat %d" % (i + 1, j + 1))
else:
totalRows = int(len(seats)) - 1
row = int(input("\nEnter the row (1 through %d): " % totalRows))
totalCols = int(len(seats[0])) - 1
col = int(input(("\nEnter the seat(column) (1 through %d): " % totalCols)))
if seats[row-1][col-1] == 0:
print("\nSorry the seat is unavailable")
else:
seats[row-1][col-1] = 0
print("\nYour seat is in row %d and seat %d" % (row, col))
# main
def main():
seats = [ [ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ], [ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ],
[ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ], [ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 ],
[ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 ], [ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 ],
[ 20, 20, 30, 30, 40, 40, 30, 30, 20, 20 ], [ 20, 30, 30, 40, 50, 50, 40, 30, 30, 20 ],
[ 30, 40, 50, 50, 50, 50, 50, 50, 40, 30 ] ]
pickChoice = str(input("Pick seat by price or location(Enter P or L): "))
printSeats(seats)
findSeat(seats, pickChoice)
printSeats(seats)
# PROGRAM RUN
main() | def print_seats(seats):
for i in range(len(seats[0]) - 1):
print(seats[i])
def find_seat(seats, pickChoice):
if pickChoice.lower() == 'p':
price = int(input('\nEnter the price(10, 20, 30, 40 or 50): '))
seat_found = False
for i in range(len(seats)):
for j in range(len(seats[0])):
if seats[i][j] == price and (not seatFound):
seat_found = True
seats[i][j] = 0
print('\nYour seat is in row %d and seat %d' % (i + 1, j + 1))
else:
total_rows = int(len(seats)) - 1
row = int(input('\nEnter the row (1 through %d): ' % totalRows))
total_cols = int(len(seats[0])) - 1
col = int(input('\nEnter the seat(column) (1 through %d): ' % totalCols))
if seats[row - 1][col - 1] == 0:
print('\nSorry the seat is unavailable')
else:
seats[row - 1][col - 1] = 0
print('\nYour seat is in row %d and seat %d' % (row, col))
def main():
seats = [[10, 10, 10, 10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10], [10, 10, 20, 20, 20, 20, 20, 20, 10, 10], [10, 10, 20, 20, 20, 20, 20, 20, 10, 10], [10, 10, 20, 20, 20, 20, 20, 20, 10, 10], [20, 20, 30, 30, 40, 40, 30, 30, 20, 20], [20, 30, 30, 40, 50, 50, 40, 30, 30, 20], [30, 40, 50, 50, 50, 50, 50, 50, 40, 30]]
pick_choice = str(input('Pick seat by price or location(Enter P or L): '))
print_seats(seats)
find_seat(seats, pickChoice)
print_seats(seats)
main() |
def grep(pattern):
while True:
line = (yield)
if pattern in line:
print(line)
g = grep("python")
g.send(None)
g.send("java is cool")
g.send("python is cool")
| def grep(pattern):
while True:
line = (yield)
if pattern in line:
print(line)
g = grep('python')
g.send(None)
g.send('java is cool')
g.send('python is cool') |
print('Enter a name.')
name = input()
if name:
print('Thank You')
else:
print('You didn"t enter a name')
| print('Enter a name.')
name = input()
if name:
print('Thank You')
else:
print('You didn"t enter a name') |
# Football player simulator and adventure game
# this is a choose your own path game
#beginning of the game/ enter a name
print("This is a choose your own path game. You will be a football player, and you will have to make decisions that will influence your career: ")
x = input(str("to begin the game enter your football player's name: "))
print("Alright you are ready to begin, " + x)
#functions
def catch():
for x in range (random.randint(4,8)):
print("you caught a ball!")
def catch2():
for x in range (random.randint(1,5)):
print("you caught a ball!")
#NFL or college
y = input("YOUR FIRST BIG DECISION! Do you want to go straight to the NFL or finish college and risk an injury? for NFL type football, for college type college: ")
while y != "football" and y != "college":
y = input("please type football or college! ")
if y == "football":
print("your talents have been recognized by the NFL and you have been recruited!")
else:
print("your academic commitment is recognized for being special! After your year in college you have been recruited")
#draft or undrafted
z = input("BIG DECISION! Do you want to participate in the draft or be undrafted? For draft type draft, for undrafted type undrafted: ")
if z == "draft":
print("You have been drafted by the Miami Dolphins! Don't worry they are in rebuild")
elif z == "undrafted":
print("You have been picked up off the waver wire by the GREEN BAY PACKERS! You have a shot at getting a ring in your first season!")
else:
print("please enter a valid name, You have been drafted the ATLANTA FALCONS! Solid middle of the pack team")
#leader or follower
a = input("BIG DECISION! Do you want to become a leader or take a secondary role on your new team? Type leader for leader or follower for secondary role: ")
while a != "leader" and a != "follower":
a = input("please type leader or follower! ")
if a == "leader":
print("your coach and teamates have noticed your leadership, but they blame you for their most recent loss. Try and get back on their good side")
else:
print("your talent goes unoticed by your coaches and teammates, try putting yourself out there for more playing time")
#money or better team
b = input("BIG DECISION! After a few years in the league your contract is up, do you want a bigger contract or play for a better team for less money? Type money or team: ")
while b != "money" and b != "team":
b = input("please type money or team! ")
if b == "money":
print("you have been picked up in free agency by the ARIZONA CARDINALS, but you got your big money")
else:
print("you have taken less money, but secured a spot on a really good San Fransisco 49ers team")
#stats or wins
c = input("BIG DECISION! Would you rather chase stats and become a legendary player or get wins by being a team player? Type stats or wins: ")
while c != "stats" and c != "wins":
c = input("please type stats or wins! ")
if c == "stats":
print("you have broken the yards record for a single season, but your team didn't make the playoffs")
else:
print("you have had an average year, but your team won their division and you might be on your way to a ring")
print("PLEASE GO TO NEXT BLOCK")
| print('This is a choose your own path game. You will be a football player, and you will have to make decisions that will influence your career: ')
x = input(str("to begin the game enter your football player's name: "))
print('Alright you are ready to begin, ' + x)
def catch():
for x in range(random.randint(4, 8)):
print('you caught a ball!')
def catch2():
for x in range(random.randint(1, 5)):
print('you caught a ball!')
y = input('YOUR FIRST BIG DECISION! Do you want to go straight to the NFL or finish college and risk an injury? for NFL type football, for college type college: ')
while y != 'football' and y != 'college':
y = input('please type football or college! ')
if y == 'football':
print('your talents have been recognized by the NFL and you have been recruited!')
else:
print('your academic commitment is recognized for being special! After your year in college you have been recruited')
z = input('BIG DECISION! Do you want to participate in the draft or be undrafted? For draft type draft, for undrafted type undrafted: ')
if z == 'draft':
print("You have been drafted by the Miami Dolphins! Don't worry they are in rebuild")
elif z == 'undrafted':
print('You have been picked up off the waver wire by the GREEN BAY PACKERS! You have a shot at getting a ring in your first season!')
else:
print('please enter a valid name, You have been drafted the ATLANTA FALCONS! Solid middle of the pack team')
a = input('BIG DECISION! Do you want to become a leader or take a secondary role on your new team? Type leader for leader or follower for secondary role: ')
while a != 'leader' and a != 'follower':
a = input('please type leader or follower! ')
if a == 'leader':
print('your coach and teamates have noticed your leadership, but they blame you for their most recent loss. Try and get back on their good side')
else:
print('your talent goes unoticed by your coaches and teammates, try putting yourself out there for more playing time')
b = input('BIG DECISION! After a few years in the league your contract is up, do you want a bigger contract or play for a better team for less money? Type money or team: ')
while b != 'money' and b != 'team':
b = input('please type money or team! ')
if b == 'money':
print('you have been picked up in free agency by the ARIZONA CARDINALS, but you got your big money')
else:
print('you have taken less money, but secured a spot on a really good San Fransisco 49ers team')
c = input('BIG DECISION! Would you rather chase stats and become a legendary player or get wins by being a team player? Type stats or wins: ')
while c != 'stats' and c != 'wins':
c = input('please type stats or wins! ')
if c == 'stats':
print("you have broken the yards record for a single season, but your team didn't make the playoffs")
else:
print('you have had an average year, but your team won their division and you might be on your way to a ring')
print('PLEASE GO TO NEXT BLOCK') |
#
# PySNMP MIB module GDCDATX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GDCDATX-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:05:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
SCinstance, = mibBuilder.importSymbols("GDCMACRO-MIB", "SCinstance")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, enterprises, TimeTicks, Counter64, Gauge32, MibIdentifier, Integer32, NotificationType, IpAddress, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "enterprises", "TimeTicks", "Counter64", "Gauge32", "MibIdentifier", "Integer32", "NotificationType", "IpAddress", "ObjectIdentity", "ModuleIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
gdc = MibIdentifier((1, 3, 6, 1, 4, 1, 498))
datx = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7))
datxSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1))
dtx2011 = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2))
datxVersion = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 1))
datxMaintenance = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 2))
datxConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 3))
datxDiagnostics = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 4))
datxStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 5))
datxMIBversion = MibScalar((1, 3, 6, 1, 4, 1, 498, 7, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxMIBversion.setStatus('mandatory')
datxMaintTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1), )
if mibBuilder.loadTexts: datxMaintTable.setStatus('mandatory')
datxMaintEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxMaintIndex"))
if mibBuilder.loadTexts: datxMaintEntry.setStatus('mandatory')
datxMaintIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxMaintIndex.setStatus('mandatory')
datxFirmwareRev = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxFirmwareRev.setStatus('mandatory')
datxDefaultInit = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("factoryDefault", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxDefaultInit.setStatus('mandatory')
datxFrontPanel = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inhibit", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxFrontPanel.setStatus('mandatory')
datxLedStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxLedStatus.setStatus('mandatory')
datxTransConfigTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1), )
if mibBuilder.loadTexts: datxTransConfigTable.setStatus('mandatory')
datxTransConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxTransConfigIndex"))
if mibBuilder.loadTexts: datxTransConfigEntry.setStatus('mandatory')
datxTransConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxTransConfigIndex.setStatus('mandatory')
datxBaudRate = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("asynchronous", 1), ("synchronous1200", 2), ("synchronous2400", 3), ("synchronous4800", 4), ("synchronous7200", 5), ("synchronous9600", 6), ("synchronous14400", 7), ("synchronous19200", 8)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxBaudRate.setStatus('mandatory')
datxSyncTxClockSource = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("internal", 1), ("slave", 2), ("external", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxSyncTxClockSource.setStatus('mandatory')
datxEiaSyncClock = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxEiaSyncClock.setStatus('mandatory')
datxEiaConfigTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2), )
if mibBuilder.loadTexts: datxEiaConfigTable.setStatus('mandatory')
datxEiaConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxEIAIndex"))
if mibBuilder.loadTexts: datxEiaConfigEntry.setStatus('mandatory')
datxEIAIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxEIAIndex.setStatus('mandatory')
datxCarrierControl = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("dtr", 1), ("rts", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxCarrierControl.setStatus('mandatory')
datxRtsMode = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("real", 1), ("forced", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxRtsMode.setStatus('mandatory')
datxRtsCtsDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("t8mSec", 1), ("t75mSec", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxRtsCtsDelay.setStatus('mandatory')
datxEiaRdlControl = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxEiaRdlControl.setStatus('mandatory')
datxDsrInAl = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxDsrInAl.setStatus('mandatory')
datxEiaAlControl = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxEiaAlControl.setStatus('mandatory')
datxMiscConfigTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3), )
if mibBuilder.loadTexts: datxMiscConfigTable.setStatus('mandatory')
datxMiscConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxMiscIndex"))
if mibBuilder.loadTexts: datxMiscConfigEntry.setStatus('mandatory')
datxMiscIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxMiscIndex.setStatus('mandatory')
datxSystemStatusOption = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxSystemStatusOption.setStatus('mandatory')
datxDualSignalingTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("disable", 1), ("time3Sec", 2), ("time1Sec", 3), ("immediate", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxDualSignalingTimer.setStatus('mandatory')
datxRegenCharLength = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("bits8", 1), ("bits9", 2), ("bits10", 3), ("bits11", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxRegenCharLength.setStatus('mandatory')
datxRegenMode = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxRegenMode.setStatus('mandatory')
datxAsyncRate = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("async4800", 1), ("async7200", 2), ("async9600", 3), ("async14400", 4), ("async19200", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxAsyncRate.setStatus('mandatory')
datxDiagnosticsTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1), )
if mibBuilder.loadTexts: datxDiagnosticsTable.setStatus('mandatory')
datxDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxDiagnosticsIndex"))
if mibBuilder.loadTexts: datxDiagEntry.setStatus('mandatory')
datxDiagnosticsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxDiagnosticsIndex.setStatus('mandatory')
datxDiagTest = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("noTest", 1), ("selfTest", 2), ("analoop", 3), ("analoopSelfTest", 4), ("remoteDL", 5), ("remoteDLselfTest", 6)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: datxDiagTest.setStatus('mandatory')
datxTestError = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noError", 1), ("testError", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxTestError.setStatus('mandatory')
datxTestDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxTestDuration.setStatus('mandatory')
datxStatusTable = MibTable((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1), )
if mibBuilder.loadTexts: datxStatusTable.setStatus('mandatory')
datxStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1), ).setIndexNames((0, "GDCDATX-MIB", "datxStatusIndex"))
if mibBuilder.loadTexts: datxStatusEntry.setStatus('mandatory')
datxStatusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxStatusIndex.setStatus('mandatory')
datxDTRstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxDTRstatus.setStatus('mandatory')
datxRDLstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxRDLstatus.setStatus('mandatory')
datxCOstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxCOstatus.setStatus('mandatory')
datxCTSstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxCTSstatus.setStatus('mandatory')
datxRTSstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxRTSstatus.setStatus('mandatory')
datxTMstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxTMstatus.setStatus('mandatory')
datxALstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxALstatus.setStatus('mandatory')
datxDSRstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxDSRstatus.setStatus('mandatory')
datxRXclock = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inactive", 1), ("active", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxRXclock.setStatus('mandatory')
datxTXclock = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inactive", 1), ("active", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxTXclock.setStatus('mandatory')
datxEXTclock = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inactive", 1), ("active", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxEXTclock.setStatus('mandatory')
datxAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: datxAlarmStatus.setStatus('mandatory')
dtx2011AlarmData = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1))
dtx2011NoResponseAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 1))
dtx2011DiagRxErrAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 2))
dtx2011PowerUpAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 3))
dtx2011DCDLossAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 4))
dtx2011NoExtClockAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 5))
mibBuilder.exportSymbols("GDCDATX-MIB", datxCOstatus=datxCOstatus, datxEiaConfigTable=datxEiaConfigTable, datxRegenMode=datxRegenMode, datxBaudRate=datxBaudRate, gdc=gdc, datxRXclock=datxRXclock, datxStatusIndex=datxStatusIndex, datxDiagnostics=datxDiagnostics, datxDefaultInit=datxDefaultInit, datxMIBversion=datxMIBversion, datxDiagEntry=datxDiagEntry, datxAsyncRate=datxAsyncRate, datxRtsCtsDelay=datxRtsCtsDelay, datx=datx, datxStatus=datxStatus, datxStatusEntry=datxStatusEntry, datxLedStatus=datxLedStatus, datxEiaRdlControl=datxEiaRdlControl, dtx2011DiagRxErrAlm=dtx2011DiagRxErrAlm, datxMiscIndex=datxMiscIndex, datxTXclock=datxTXclock, datxMaintEntry=datxMaintEntry, dtx2011PowerUpAlm=dtx2011PowerUpAlm, dtx2011DCDLossAlm=dtx2011DCDLossAlm, datxDiagnosticsTable=datxDiagnosticsTable, datxFirmwareRev=datxFirmwareRev, datxSyncTxClockSource=datxSyncTxClockSource, datxCarrierControl=datxCarrierControl, datxFrontPanel=datxFrontPanel, dtx2011=dtx2011, datxDiagTest=datxDiagTest, datxALstatus=datxALstatus, datxEiaSyncClock=datxEiaSyncClock, datxTMstatus=datxTMstatus, datxRtsMode=datxRtsMode, datxMaintIndex=datxMaintIndex, datxDsrInAl=datxDsrInAl, datxEiaAlControl=datxEiaAlControl, datxMaintTable=datxMaintTable, datxTransConfigTable=datxTransConfigTable, datxEiaConfigEntry=datxEiaConfigEntry, datxTestError=datxTestError, dtx2011NoExtClockAlm=dtx2011NoExtClockAlm, datxMiscConfigTable=datxMiscConfigTable, datxAlarmStatus=datxAlarmStatus, datxDualSignalingTimer=datxDualSignalingTimer, datxTransConfigEntry=datxTransConfigEntry, datxConfiguration=datxConfiguration, datxRDLstatus=datxRDLstatus, datxTransConfigIndex=datxTransConfigIndex, datxSystem=datxSystem, datxSystemStatusOption=datxSystemStatusOption, datxDTRstatus=datxDTRstatus, dtx2011AlarmData=dtx2011AlarmData, dtx2011NoResponseAlm=dtx2011NoResponseAlm, datxStatusTable=datxStatusTable, datxRTSstatus=datxRTSstatus, datxTestDuration=datxTestDuration, datxDSRstatus=datxDSRstatus, datxMaintenance=datxMaintenance, datxCTSstatus=datxCTSstatus, datxVersion=datxVersion, datxDiagnosticsIndex=datxDiagnosticsIndex, datxMiscConfigEntry=datxMiscConfigEntry, datxRegenCharLength=datxRegenCharLength, datxEXTclock=datxEXTclock, datxEIAIndex=datxEIAIndex)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(s_cinstance,) = mibBuilder.importSymbols('GDCMACRO-MIB', 'SCinstance')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, counter32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, enterprises, time_ticks, counter64, gauge32, mib_identifier, integer32, notification_type, ip_address, object_identity, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Counter32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'enterprises', 'TimeTicks', 'Counter64', 'Gauge32', 'MibIdentifier', 'Integer32', 'NotificationType', 'IpAddress', 'ObjectIdentity', 'ModuleIdentity')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
gdc = mib_identifier((1, 3, 6, 1, 4, 1, 498))
datx = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7))
datx_system = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1))
dtx2011 = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2))
datx_version = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 1))
datx_maintenance = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 2))
datx_configuration = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 3))
datx_diagnostics = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 4))
datx_status = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 1, 5))
datx_mi_bversion = mib_scalar((1, 3, 6, 1, 4, 1, 498, 7, 1, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(5, 5)).setFixedLength(5)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxMIBversion.setStatus('mandatory')
datx_maint_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1))
if mibBuilder.loadTexts:
datxMaintTable.setStatus('mandatory')
datx_maint_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxMaintIndex'))
if mibBuilder.loadTexts:
datxMaintEntry.setStatus('mandatory')
datx_maint_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxMaintIndex.setStatus('mandatory')
datx_firmware_rev = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(2, 2)).setFixedLength(2)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxFirmwareRev.setStatus('mandatory')
datx_default_init = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('normal', 1), ('factoryDefault', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxDefaultInit.setStatus('mandatory')
datx_front_panel = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('inhibit', 1), ('enable', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxFrontPanel.setStatus('mandatory')
datx_led_status = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 2, 1, 1, 5), octet_string().subtype(subtypeSpec=value_size_constraint(2, 2)).setFixedLength(2)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxLedStatus.setStatus('mandatory')
datx_trans_config_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1))
if mibBuilder.loadTexts:
datxTransConfigTable.setStatus('mandatory')
datx_trans_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxTransConfigIndex'))
if mibBuilder.loadTexts:
datxTransConfigEntry.setStatus('mandatory')
datx_trans_config_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxTransConfigIndex.setStatus('mandatory')
datx_baud_rate = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=named_values(('asynchronous', 1), ('synchronous1200', 2), ('synchronous2400', 3), ('synchronous4800', 4), ('synchronous7200', 5), ('synchronous9600', 6), ('synchronous14400', 7), ('synchronous19200', 8)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxBaudRate.setStatus('mandatory')
datx_sync_tx_clock_source = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('internal', 1), ('slave', 2), ('external', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxSyncTxClockSource.setStatus('mandatory')
datx_eia_sync_clock = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxEiaSyncClock.setStatus('mandatory')
datx_eia_config_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2))
if mibBuilder.loadTexts:
datxEiaConfigTable.setStatus('mandatory')
datx_eia_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxEIAIndex'))
if mibBuilder.loadTexts:
datxEiaConfigEntry.setStatus('mandatory')
datx_eia_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxEIAIndex.setStatus('mandatory')
datx_carrier_control = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('dtr', 1), ('rts', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxCarrierControl.setStatus('mandatory')
datx_rts_mode = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('real', 1), ('forced', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxRtsMode.setStatus('mandatory')
datx_rts_cts_delay = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('t8mSec', 1), ('t75mSec', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxRtsCtsDelay.setStatus('mandatory')
datx_eia_rdl_control = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxEiaRdlControl.setStatus('mandatory')
datx_dsr_in_al = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxDsrInAl.setStatus('mandatory')
datx_eia_al_control = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxEiaAlControl.setStatus('mandatory')
datx_misc_config_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3))
if mibBuilder.loadTexts:
datxMiscConfigTable.setStatus('mandatory')
datx_misc_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxMiscIndex'))
if mibBuilder.loadTexts:
datxMiscConfigEntry.setStatus('mandatory')
datx_misc_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxMiscIndex.setStatus('mandatory')
datx_system_status_option = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxSystemStatusOption.setStatus('mandatory')
datx_dual_signaling_timer = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('disable', 1), ('time3Sec', 2), ('time1Sec', 3), ('immediate', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxDualSignalingTimer.setStatus('mandatory')
datx_regen_char_length = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('bits8', 1), ('bits9', 2), ('bits10', 3), ('bits11', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxRegenCharLength.setStatus('mandatory')
datx_regen_mode = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxRegenMode.setStatus('mandatory')
datx_async_rate = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 3, 3, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('async4800', 1), ('async7200', 2), ('async9600', 3), ('async14400', 4), ('async19200', 5)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxAsyncRate.setStatus('mandatory')
datx_diagnostics_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1))
if mibBuilder.loadTexts:
datxDiagnosticsTable.setStatus('mandatory')
datx_diag_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxDiagnosticsIndex'))
if mibBuilder.loadTexts:
datxDiagEntry.setStatus('mandatory')
datx_diagnostics_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxDiagnosticsIndex.setStatus('mandatory')
datx_diag_test = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('noTest', 1), ('selfTest', 2), ('analoop', 3), ('analoopSelfTest', 4), ('remoteDL', 5), ('remoteDLselfTest', 6)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
datxDiagTest.setStatus('mandatory')
datx_test_error = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('noError', 1), ('testError', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxTestError.setStatus('mandatory')
datx_test_duration = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 4, 1, 1, 4), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxTestDuration.setStatus('mandatory')
datx_status_table = mib_table((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1))
if mibBuilder.loadTexts:
datxStatusTable.setStatus('mandatory')
datx_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1)).setIndexNames((0, 'GDCDATX-MIB', 'datxStatusIndex'))
if mibBuilder.loadTexts:
datxStatusEntry.setStatus('mandatory')
datx_status_index = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 1), s_cinstance()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxStatusIndex.setStatus('mandatory')
datx_dt_rstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxDTRstatus.setStatus('mandatory')
datx_rd_lstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxRDLstatus.setStatus('mandatory')
datx_c_ostatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxCOstatus.setStatus('mandatory')
datx_ct_sstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxCTSstatus.setStatus('mandatory')
datx_rt_sstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxRTSstatus.setStatus('mandatory')
datx_t_mstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxTMstatus.setStatus('mandatory')
datx_a_lstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxALstatus.setStatus('mandatory')
datx_ds_rstatus = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('off', 1), ('on', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxDSRstatus.setStatus('mandatory')
datx_r_xclock = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('inactive', 1), ('active', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxRXclock.setStatus('mandatory')
datx_t_xclock = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('inactive', 1), ('active', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxTXclock.setStatus('mandatory')
datx_ex_tclock = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('inactive', 1), ('active', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxEXTclock.setStatus('mandatory')
datx_alarm_status = mib_table_column((1, 3, 6, 1, 4, 1, 498, 7, 1, 5, 1, 1, 13), octet_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
datxAlarmStatus.setStatus('mandatory')
dtx2011_alarm_data = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1))
dtx2011_no_response_alm = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 1))
dtx2011_diag_rx_err_alm = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 2))
dtx2011_power_up_alm = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 3))
dtx2011_dcd_loss_alm = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 4))
dtx2011_no_ext_clock_alm = mib_identifier((1, 3, 6, 1, 4, 1, 498, 7, 2, 1, 5))
mibBuilder.exportSymbols('GDCDATX-MIB', datxCOstatus=datxCOstatus, datxEiaConfigTable=datxEiaConfigTable, datxRegenMode=datxRegenMode, datxBaudRate=datxBaudRate, gdc=gdc, datxRXclock=datxRXclock, datxStatusIndex=datxStatusIndex, datxDiagnostics=datxDiagnostics, datxDefaultInit=datxDefaultInit, datxMIBversion=datxMIBversion, datxDiagEntry=datxDiagEntry, datxAsyncRate=datxAsyncRate, datxRtsCtsDelay=datxRtsCtsDelay, datx=datx, datxStatus=datxStatus, datxStatusEntry=datxStatusEntry, datxLedStatus=datxLedStatus, datxEiaRdlControl=datxEiaRdlControl, dtx2011DiagRxErrAlm=dtx2011DiagRxErrAlm, datxMiscIndex=datxMiscIndex, datxTXclock=datxTXclock, datxMaintEntry=datxMaintEntry, dtx2011PowerUpAlm=dtx2011PowerUpAlm, dtx2011DCDLossAlm=dtx2011DCDLossAlm, datxDiagnosticsTable=datxDiagnosticsTable, datxFirmwareRev=datxFirmwareRev, datxSyncTxClockSource=datxSyncTxClockSource, datxCarrierControl=datxCarrierControl, datxFrontPanel=datxFrontPanel, dtx2011=dtx2011, datxDiagTest=datxDiagTest, datxALstatus=datxALstatus, datxEiaSyncClock=datxEiaSyncClock, datxTMstatus=datxTMstatus, datxRtsMode=datxRtsMode, datxMaintIndex=datxMaintIndex, datxDsrInAl=datxDsrInAl, datxEiaAlControl=datxEiaAlControl, datxMaintTable=datxMaintTable, datxTransConfigTable=datxTransConfigTable, datxEiaConfigEntry=datxEiaConfigEntry, datxTestError=datxTestError, dtx2011NoExtClockAlm=dtx2011NoExtClockAlm, datxMiscConfigTable=datxMiscConfigTable, datxAlarmStatus=datxAlarmStatus, datxDualSignalingTimer=datxDualSignalingTimer, datxTransConfigEntry=datxTransConfigEntry, datxConfiguration=datxConfiguration, datxRDLstatus=datxRDLstatus, datxTransConfigIndex=datxTransConfigIndex, datxSystem=datxSystem, datxSystemStatusOption=datxSystemStatusOption, datxDTRstatus=datxDTRstatus, dtx2011AlarmData=dtx2011AlarmData, dtx2011NoResponseAlm=dtx2011NoResponseAlm, datxStatusTable=datxStatusTable, datxRTSstatus=datxRTSstatus, datxTestDuration=datxTestDuration, datxDSRstatus=datxDSRstatus, datxMaintenance=datxMaintenance, datxCTSstatus=datxCTSstatus, datxVersion=datxVersion, datxDiagnosticsIndex=datxDiagnosticsIndex, datxMiscConfigEntry=datxMiscConfigEntry, datxRegenCharLength=datxRegenCharLength, datxEXTclock=datxEXTclock, datxEIAIndex=datxEIAIndex) |
def _Weinreb2020_color_palette():
palette = {
"Neutrophil": "#023047",
"Eos": "#005f73",
"Baso": "#0a9396",
"Mast": "#94d2bd",
"Erythroid": "#e9d8a6",
"Lymphoid": "#ee9b00",
"Monocyte": "#F08700",
"pDC": "#bb3e03",
"Ccr7_DC": "#ae2012",
"Meg": "#9b2226",
"undiff": "#f0efeb",
}
return palette | def __weinreb2020_color_palette():
palette = {'Neutrophil': '#023047', 'Eos': '#005f73', 'Baso': '#0a9396', 'Mast': '#94d2bd', 'Erythroid': '#e9d8a6', 'Lymphoid': '#ee9b00', 'Monocyte': '#F08700', 'pDC': '#bb3e03', 'Ccr7_DC': '#ae2012', 'Meg': '#9b2226', 'undiff': '#f0efeb'}
return palette |
def p01():
with open("data_day01.txt") as data_file:
data = data_file.read().splitlines()
increase_count = 0
previous_value = 1e10
for value_str in data:
value = int(value_str)
if value > previous_value:
increase_count += 1
previous_value = value
return increase_count
if __name__ == "__main__":
print(p01()) | def p01():
with open('data_day01.txt') as data_file:
data = data_file.read().splitlines()
increase_count = 0
previous_value = 10000000000.0
for value_str in data:
value = int(value_str)
if value > previous_value:
increase_count += 1
previous_value = value
return increase_count
if __name__ == '__main__':
print(p01()) |
def backspaceCompare(s, t):
def StringBuild(x, stack):
for i in x:
if i != "#":
stack.append(i)
elif stack:
stack.pop()
return "".join(stack)
return StringBuild(s, []) == StringBuild(t, [])
| def backspace_compare(s, t):
def string_build(x, stack):
for i in x:
if i != '#':
stack.append(i)
elif stack:
stack.pop()
return ''.join(stack)
return string_build(s, []) == string_build(t, []) |
expected_output = {
"line": {
"0 con 0": {"host": "idle", "active": False},
"2 vty 0": {"user": "user1", "host": "idle", "idle": "0", "location": "SERVICE1.CISCO.COM", "active": True},
}
}
| expected_output = {'line': {'0 con 0': {'host': 'idle', 'active': False}, '2 vty 0': {'user': 'user1', 'host': 'idle', 'idle': '0', 'location': 'SERVICE1.CISCO.COM', 'active': True}}} |
INSTALLED_APPS = [
'graphiql_debug_toolbar',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
SECRET_KEY = 'test'
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'loaders': [
'django.template.loaders.app_directories.Loader',
],
},
},
]
| installed_apps = ['graphiql_debug_toolbar']
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
secret_key = 'test'
root_urlconf = 'tests.urls'
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'loaders': ['django.template.loaders.app_directories.Loader']}}] |
#########################################################################################
# #
# Program purpose: Remove spaces from a given string. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : October 25, 2019 #
# #
#########################################################################################
def obtain_user_input(input_mess: str):
is_valid, user_data = False, ''
while is_valid is False:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise ValueError('Please enter a string or sentence to work with')
is_valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
def remove_string_spaces(main_str: str):
main_str = main_str.replace(' ', '')
return main_str
if __name__ == "__main__":
main_data = obtain_user_input(input_mess='Enter a sentence: ')
print(f'Removed spaces: {remove_string_spaces(main_str=main_data)}') | def obtain_user_input(input_mess: str):
(is_valid, user_data) = (False, '')
while is_valid is False:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise value_error('Please enter a string or sentence to work with')
is_valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
def remove_string_spaces(main_str: str):
main_str = main_str.replace(' ', '')
return main_str
if __name__ == '__main__':
main_data = obtain_user_input(input_mess='Enter a sentence: ')
print(f'Removed spaces: {remove_string_spaces(main_str=main_data)}') |
def test_configuration_exclusive(iosxr_conn):
iosxr_conn.acquire_priv("configuration_exclusive")
result = iosxr_conn.send_configs(["do show configuration sessions"])
iosxr_conn.close()
# last character should be an asterisk indicating configuration is locked
assert result[0].result[-1:] == "*"
| def test_configuration_exclusive(iosxr_conn):
iosxr_conn.acquire_priv('configuration_exclusive')
result = iosxr_conn.send_configs(['do show configuration sessions'])
iosxr_conn.close()
assert result[0].result[-1:] == '*' |
# https://www.hackerrank.com/challenges/jim-and-the-orders/problem?isFullScreen=true
def jimOrders(orders):
# Write your code here
dict = {}
for i in range(len(orders)):
sum = orders[i][0] + orders[i][1]
dict[i+1] = sum
# returns an array
dict = sorted(dict.items(), key = lambda kv:(kv[1], kv[0]))
return [item[0] for item in dict]
| def jim_orders(orders):
dict = {}
for i in range(len(orders)):
sum = orders[i][0] + orders[i][1]
dict[i + 1] = sum
dict = sorted(dict.items(), key=lambda kv: (kv[1], kv[0]))
return [item[0] for item in dict] |
def decode(bytestring):
chars = []
for byte in bytestring:
if byte in decode.dictionary:
chars.append(decode.dictionary[byte])
elif 0xBB <= byte <= 0xD4:
chars.append(chr(byte - 0xBB + ord("A")))
elif 0xD5 <= byte <= 0xEE:
chars.append(chr(byte - 0xD5 + ord("a")))
elif 0xA1 <= byte <= 0xAA:
chars.append(chr(byte - 0xA1 + ord("0")))
elif byte == 0xFF:
break
else:
raise ValueError(f"0x{byte :02X}")
return "".join(chars)
decode.dictionary = {
0x00: " ",
0xAD: ".",
0xB4: "'"
}
| def decode(bytestring):
chars = []
for byte in bytestring:
if byte in decode.dictionary:
chars.append(decode.dictionary[byte])
elif 187 <= byte <= 212:
chars.append(chr(byte - 187 + ord('A')))
elif 213 <= byte <= 238:
chars.append(chr(byte - 213 + ord('a')))
elif 161 <= byte <= 170:
chars.append(chr(byte - 161 + ord('0')))
elif byte == 255:
break
else:
raise value_error(f'0x{byte:02X}')
return ''.join(chars)
decode.dictionary = {0: ' ', 173: '.', 180: "'"} |
CLI_ACTION_LOGIN = 'login'
CLI_ACTION_UPLOAD = 'upload'
CLI_ACTION_CONFIG = 'config'
CLI_DEFAULT_API_ADDRESS = 'http://localhost:8080/api'
CLI_DEFAULT_API_USERNAME = 'admin'
CLI_DEFAULT_API_PASSWORD = 'admin'
CLI_DEFAULT_CONFIG_ROOT_DIR = '.crawlab'
CLI_DEFAULT_CONFIG_CLI_DIR = 'cli'
CLI_DEFAULT_CONFIG_FILE_NAME = 'config.json'
CLI_DEFAULT_CONFIG_KEY_USERNAME = 'username'
CLI_DEFAULT_CONFIG_KEY_PASSWORD = 'password'
CLI_DEFAULT_CONFIG_KEY_API_ADDRESS = 'api_address'
CLI_DEFAULT_CONFIG_KEY_TOKEN = 'token'
CLI_DEFAULT_UPLOAD_IGNORE_PATTERNS = [
r'^.git/',
r'\.pyc$',
r'__pycache__/',
r'.DS_Store',
r'\.idea/'
]
CLI_DEFAULT_UPLOAD_SPIDER_MODE = 'random'
| cli_action_login = 'login'
cli_action_upload = 'upload'
cli_action_config = 'config'
cli_default_api_address = 'http://localhost:8080/api'
cli_default_api_username = 'admin'
cli_default_api_password = 'admin'
cli_default_config_root_dir = '.crawlab'
cli_default_config_cli_dir = 'cli'
cli_default_config_file_name = 'config.json'
cli_default_config_key_username = 'username'
cli_default_config_key_password = 'password'
cli_default_config_key_api_address = 'api_address'
cli_default_config_key_token = 'token'
cli_default_upload_ignore_patterns = ['^.git/', '\\.pyc$', '__pycache__/', '.DS_Store', '\\.idea/']
cli_default_upload_spider_mode = 'random' |
# This file is part of datacube-ows, part of the Open Data Cube project.
# See https://opendatacube.org for more information.
#
# Copyright (c) 2017-2021 OWS Contributors
# SPDX-License-Identifier: Apache-2.0
mixed_3 = {
"test": 2634,
"subtest": {
"include": "tests.cfg.simple.doesnt_exist",
"type": "python"
}
}
| mixed_3 = {'test': 2634, 'subtest': {'include': 'tests.cfg.simple.doesnt_exist', 'type': 'python'}} |
numerator,denominator = input().split()
first_defect = int(input())
#probability of machine produces a defective product
p = int(numerator) / int(denominator)
q = 1- p
n = first_defect
#Applying to equation ( qn-1 . p)
ans = pow(q,n-1) * p
print(round(ans,3))
| (numerator, denominator) = input().split()
first_defect = int(input())
p = int(numerator) / int(denominator)
q = 1 - p
n = first_defect
ans = pow(q, n - 1) * p
print(round(ans, 3)) |
def link_content(url, rel, content_type):
return f"<{url}>; rel=\"{rel}\"; type=\"{content_type}\""
def get_string_or_evaluate(string_or_func, *args, **kwargs):
if not string_or_func:
return None
if isinstance(string_or_func, str):
return string_or_func
return string_or_func(*args, **kwargs)
| def link_content(url, rel, content_type):
return f'<{url}>; rel="{rel}"; type="{content_type}"'
def get_string_or_evaluate(string_or_func, *args, **kwargs):
if not string_or_func:
return None
if isinstance(string_or_func, str):
return string_or_func
return string_or_func(*args, **kwargs) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t1==None:
return t2
if t2==None:
return t1
t1.val+=t2.val
t1.left=self.mergeTrees(t1.left,t2.left)
t1.right=self.mergeTrees(t1.right,t2.right)
return t1
| class Solution:
def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t1 == None:
return t2
if t2 == None:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1 |
def is_end(history, pieces_per_player):
heads = []
player_pieces = {}
first_move = True
for e, *d in history:
if e.name == 'MOVE':
player, piece, head = d
if first_move:
heads = list(piece)
first_move = False
else:
heads[head] = piece[piece[0] == heads[head]]
player_pieces[player] = player_pieces.get(player, 0) + 1
return any([pieces_per_player - x <= 2 for x in player_pieces.values()])
def parse_bool(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.lower() in ("yes", "true", "t", "1")
raise TypeError("`value` should be bool or str")
| def is_end(history, pieces_per_player):
heads = []
player_pieces = {}
first_move = True
for (e, *d) in history:
if e.name == 'MOVE':
(player, piece, head) = d
if first_move:
heads = list(piece)
first_move = False
else:
heads[head] = piece[piece[0] == heads[head]]
player_pieces[player] = player_pieces.get(player, 0) + 1
return any([pieces_per_player - x <= 2 for x in player_pieces.values()])
def parse_bool(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.lower() in ('yes', 'true', 't', '1')
raise type_error('`value` should be bool or str') |
# --- Depois de refatorar ---
def is_decreasing(i, j, k):
return i > j and j > k
def is_increasing(i, j, k):
return i < j and j < k
def main(soldiers):
count = 0
for i in range(len(soldiers)):
for j in range(i+1,len(soldiers)):
for k in range(j+1,len(soldiers)):
if is_decreasing(soldiers[i],soldiers[j],soldiers[k]) or is_increasing(soldiers[i],soldiers[j],soldiers[k]):
count += 1
return count
# if soldiers[1] == 1:
# return 0
# if soldiers[0] == 2:
# return 3
# return 4
#for i in range(len(soldiers)) | def is_decreasing(i, j, k):
return i > j and j > k
def is_increasing(i, j, k):
return i < j and j < k
def main(soldiers):
count = 0
for i in range(len(soldiers)):
for j in range(i + 1, len(soldiers)):
for k in range(j + 1, len(soldiers)):
if is_decreasing(soldiers[i], soldiers[j], soldiers[k]) or is_increasing(soldiers[i], soldiers[j], soldiers[k]):
count += 1
return count |
SERVERSIDE_TABLE_COLUMNS = [
{
"data_name": "tweetID",
"column_name": "Tweet ID",
"default": 0,
"order": 1,
"searchable": True
},
{
"data_name": "tweetCreator",
"column_name": "Profile Name",
"default": 0,
"order": 2,
"searchable": True
},
{
"data_name": "tweetTextCount",
"column_name": "Word Count",
"default": 0,
"order": 3,
"searchable": False
},
{
"data_name": "creatorFollowers",
"column_name": "Follower Count",
"default": 0,
"order": 4,
"searchable": False
},
{
"data_name": "location",
"column_name": "Location",
"default": 0,
"order": 5,
"searchable": True
},
{
"data_name": "dateCreated",
"column_name": "Time",
"default": 0,
"order": 6,
"searchable": True
},
{
"data_name": "tweetLikes",
"column_name": "Likes",
"default": 0,
"order": 7,
"searchable": False
},
{
"data_name": "tweetRe",
"column_name": "Retweets",
"default": 0,
"order": 8,
"searchable": False
}
]
| serverside_table_columns = [{'data_name': 'tweetID', 'column_name': 'Tweet ID', 'default': 0, 'order': 1, 'searchable': True}, {'data_name': 'tweetCreator', 'column_name': 'Profile Name', 'default': 0, 'order': 2, 'searchable': True}, {'data_name': 'tweetTextCount', 'column_name': 'Word Count', 'default': 0, 'order': 3, 'searchable': False}, {'data_name': 'creatorFollowers', 'column_name': 'Follower Count', 'default': 0, 'order': 4, 'searchable': False}, {'data_name': 'location', 'column_name': 'Location', 'default': 0, 'order': 5, 'searchable': True}, {'data_name': 'dateCreated', 'column_name': 'Time', 'default': 0, 'order': 6, 'searchable': True}, {'data_name': 'tweetLikes', 'column_name': 'Likes', 'default': 0, 'order': 7, 'searchable': False}, {'data_name': 'tweetRe', 'column_name': 'Retweets', 'default': 0, 'order': 8, 'searchable': False}] |
patches = [
{
"op": "move",
"from": "/PropertyTypes/AWS::GroundStation::Config.FrequencyBandwidth",
"path": "/PropertyTypes/AWS::GroundStation::Config.Bandwidth",
},
{
"op": "replace",
"path": "/PropertyTypes/AWS::GroundStation::Config.SpectrumConfig/Properties/Bandwidth/Type",
"value": "Bandwidth",
},
{
"op": "replace",
"path": "/PropertyTypes/AWS::GroundStation::Config.AntennaUplinkConfig/Properties/SpectrumConfig/Type",
"value": "SpectrumConfig",
},
{
"op": "remove",
"path": "/PropertyTypes/AWS::GroundStation::Config.UplinkSpectrumConfig",
},
]
| patches = [{'op': 'move', 'from': '/PropertyTypes/AWS::GroundStation::Config.FrequencyBandwidth', 'path': '/PropertyTypes/AWS::GroundStation::Config.Bandwidth'}, {'op': 'replace', 'path': '/PropertyTypes/AWS::GroundStation::Config.SpectrumConfig/Properties/Bandwidth/Type', 'value': 'Bandwidth'}, {'op': 'replace', 'path': '/PropertyTypes/AWS::GroundStation::Config.AntennaUplinkConfig/Properties/SpectrumConfig/Type', 'value': 'SpectrumConfig'}, {'op': 'remove', 'path': '/PropertyTypes/AWS::GroundStation::Config.UplinkSpectrumConfig'}] |
height = int(input())
x = 1
for i in range(1,height+1):
for j in range(1,height+1):
if((j <= x or j > height-x) and j <= height//2):
print(i,end=" ")
elif((j <= x or j > height-x) and j > height//2):
print(i,end=" ")
else:
print(end=" ")
if(i <= height//2):
x += 1
else :
x -= 1
print()
# Sample Input :- 7
# Output :-
# 1 1
# 2 2 2 2
# 3 3 3 3 3 3
# 4 4 4 4 4 4 4
# 5 5 5 5 5 5
# 6 6 6 6
# 7 7
| height = int(input())
x = 1
for i in range(1, height + 1):
for j in range(1, height + 1):
if (j <= x or j > height - x) and j <= height // 2:
print(i, end=' ')
elif (j <= x or j > height - x) and j > height // 2:
print(i, end=' ')
else:
print(end=' ')
if i <= height // 2:
x += 1
else:
x -= 1
print() |
IN = 'ga.txt'
OUT = 'ga.dat'
with open(IN, 'r') as f, open(OUT, 'w') as g:
f.readline()
for line in f.readlines():
sol = int(line.split(',')[1])
if sol >= 13:
g.write(line.split(',')[2])
else:
print(line) | in = 'ga.txt'
out = 'ga.dat'
with open(IN, 'r') as f, open(OUT, 'w') as g:
f.readline()
for line in f.readlines():
sol = int(line.split(',')[1])
if sol >= 13:
g.write(line.split(',')[2])
else:
print(line) |
class Skills_Placement(object):
def __init__(self, skills_placement):
self.skills_placement = skills_placement | class Skills_Placement(object):
def __init__(self, skills_placement):
self.skills_placement = skills_placement |
L = -np.ones(T) * (min_error_controlgain-0.3)
s_closed_loop, a_closed_loop = lds.dynamics_closedloop(D, B, L)
with plt.xkcd():
fig = plt.figure(figsize=(8, 6))
plot_vs_time(s_closed_loop,'Closed Loop','b',goal)
plt.title('Closed Loop State Evolution with Under-Ambitious Control Gain')
plt.show()
| l = -np.ones(T) * (min_error_controlgain - 0.3)
(s_closed_loop, a_closed_loop) = lds.dynamics_closedloop(D, B, L)
with plt.xkcd():
fig = plt.figure(figsize=(8, 6))
plot_vs_time(s_closed_loop, 'Closed Loop', 'b', goal)
plt.title('Closed Loop State Evolution with Under-Ambitious Control Gain')
plt.show() |
class BaseEventRule(object):
rules = dict()
functions = []
name = ''
@property
def expression(self):
raise NotImplementedError
class RateEventRule(BaseEventRule):
UNIT_MINIUTES = 'minutes'
UNIT_HOURS = 'hours'
UNIT_DAYS = 'days'
def __init__(self, name, value, unit='minutes'):
if not isinstance(value, int):
raise TypeError('Parameter "value" must be type of "int", not "%s"' % str(type(value)))
units = [getattr(self, key) for key in dir(self) if key.startswith('UNIT_')]
if unit not in units:
raise ValueError('Parameter "unit" must be one of %s' % ','.join(units))
self.name = name
self.value = value
self.unit = unit
@property
def expression(self):
return 'rate(%d %s)' % (self.value, self.unit)
class TimeEventRule(BaseEventRule):
def __init__(self, name, pattern):
if not isinstance(pattern, basestring):
raise TypeError('Parameter "expression" must be type of "string", not "%s"' % str(type(pattern)))
self.name = name
self.pattern = pattern
@property
def expression(self):
return 'cron(%s)' % self.pattern
| class Baseeventrule(object):
rules = dict()
functions = []
name = ''
@property
def expression(self):
raise NotImplementedError
class Rateeventrule(BaseEventRule):
unit_miniutes = 'minutes'
unit_hours = 'hours'
unit_days = 'days'
def __init__(self, name, value, unit='minutes'):
if not isinstance(value, int):
raise type_error('Parameter "value" must be type of "int", not "%s"' % str(type(value)))
units = [getattr(self, key) for key in dir(self) if key.startswith('UNIT_')]
if unit not in units:
raise value_error('Parameter "unit" must be one of %s' % ','.join(units))
self.name = name
self.value = value
self.unit = unit
@property
def expression(self):
return 'rate(%d %s)' % (self.value, self.unit)
class Timeeventrule(BaseEventRule):
def __init__(self, name, pattern):
if not isinstance(pattern, basestring):
raise type_error('Parameter "expression" must be type of "string", not "%s"' % str(type(pattern)))
self.name = name
self.pattern = pattern
@property
def expression(self):
return 'cron(%s)' % self.pattern |
# Adding two number provided by user input
num1 = input("First Number: ")
num2 = input("\nSecond Number: ")
#adding two number
sum = float(num1) + float(num2)
#display the sum
print("The sum of {0} and {1} is {2}".format(num1, num2, sum)) | num1 = input('First Number: ')
num2 = input('\nSecond Number: ')
sum = float(num1) + float(num2)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
meatPrice = 4.00
meatTax = 0.03 * meatPrice
milkPrice = 2.00
milkTax = 0.03 * milkPrice
print(meatTax + meatPrice + milkTax + milkPrice)
| meat_price = 4.0
meat_tax = 0.03 * meatPrice
milk_price = 2.0
milk_tax = 0.03 * milkPrice
print(meatTax + meatPrice + milkTax + milkPrice) |
'''
Arrival of the General
'''
n = int(input())
soldiers = list(map(int, input().split(' ')))
maxs = max(soldiers)
mins = min(soldiers)
posi_max = soldiers.index(maxs)
soldiers.reverse()
posi_min = n-1 - soldiers.index(mins)
if posi_max > posi_min:
swap = (posi_max - 0) + (n - 1 - (posi_min + 1))
else:
swap = (posi_max - 0) + (n - 1 - posi_min)
print(swap) | """
Arrival of the General
"""
n = int(input())
soldiers = list(map(int, input().split(' ')))
maxs = max(soldiers)
mins = min(soldiers)
posi_max = soldiers.index(maxs)
soldiers.reverse()
posi_min = n - 1 - soldiers.index(mins)
if posi_max > posi_min:
swap = posi_max - 0 + (n - 1 - (posi_min + 1))
else:
swap = posi_max - 0 + (n - 1 - posi_min)
print(swap) |
languages = ['en', 'de', 'fr']
vocab_dirs = ['data/Multi30K_DE/', 'data/Multi30K_DE/', 'data/Multi30K_FR/']
for language, vocab_dir in zip(languages, vocab_dirs):
with open('data/AmbiguousCOCO/test_2017_mscoco.lc.norm.tok.'+language, 'r') as f:
coco = [line.strip() for line in f.readlines()]
with open(vocab_dir + 'vocab.'+language, 'r') as f:
en_vocab = [(line.strip(), len(line)) for i, line in enumerate(f.readlines())]
unk = '[unk]'
en_vocab += [(unk, -1)]
en_vocab = dict(en_vocab)
def get_bpe_segment(token):
for l in range(len(token)-2 if token.endswith('@@') else len(token)):
word2id = en_vocab.get(token[l:], -1)
if word2id != -1:
bpe = []
bpe.append(token[l:])
if l != 0:
bpe.extend(get_bpe_segment(token[:l]+'@@'))
return bpe
return [token]
with open('data/AmbiguousCOCO/test.norm.tok.lc.10000bpe.'+language, 'w') as f:
for line in coco:
tokens = line.split()
bpe_tokens = []
for token in tokens:
if token in en_vocab.keys():
bpe = token
else:
bpe = get_bpe_segment(token)
bpe.reverse()
bpe = ' '.join(bpe)
bpe_tokens.append(bpe)
f.write(' '.join(bpe_tokens)+'\n')
| languages = ['en', 'de', 'fr']
vocab_dirs = ['data/Multi30K_DE/', 'data/Multi30K_DE/', 'data/Multi30K_FR/']
for (language, vocab_dir) in zip(languages, vocab_dirs):
with open('data/AmbiguousCOCO/test_2017_mscoco.lc.norm.tok.' + language, 'r') as f:
coco = [line.strip() for line in f.readlines()]
with open(vocab_dir + 'vocab.' + language, 'r') as f:
en_vocab = [(line.strip(), len(line)) for (i, line) in enumerate(f.readlines())]
unk = '[unk]'
en_vocab += [(unk, -1)]
en_vocab = dict(en_vocab)
def get_bpe_segment(token):
for l in range(len(token) - 2 if token.endswith('@@') else len(token)):
word2id = en_vocab.get(token[l:], -1)
if word2id != -1:
bpe = []
bpe.append(token[l:])
if l != 0:
bpe.extend(get_bpe_segment(token[:l] + '@@'))
return bpe
return [token]
with open('data/AmbiguousCOCO/test.norm.tok.lc.10000bpe.' + language, 'w') as f:
for line in coco:
tokens = line.split()
bpe_tokens = []
for token in tokens:
if token in en_vocab.keys():
bpe = token
else:
bpe = get_bpe_segment(token)
bpe.reverse()
bpe = ' '.join(bpe)
bpe_tokens.append(bpe)
f.write(' '.join(bpe_tokens) + '\n') |
expected_output = {
"tag": {
"1": {
"level": {
1: {
"hosts": {
"R1-asr1k-43": {
"metric": 33554428,
"interface": {
"Gi0/1/4": {
"next_hop": "R3-asr1k-53",
"snpa": "c014.fe84.b306"
}
}
},
"R3-asr1k-53": {
"metric": 16777214,
"interface": {
"Gi0/1/4": {
"next_hop": "R3-asr1k-53",
"snpa": "c014.fe84.b306"
}
}
},
"R5-asr1k-11": {},
"R6-asr1k-20": {
"metric": 16777214,
"interface": {
"Gi0/0/2": {
"next_hop": "R6-asr1k-20",
"snpa": "3c57.31c1.fb32"
},
"Gi0/0/3": {
"next_hop": "R6-asr1k-20",
"snpa": "3c57.31c1.fb33"
}
}
}
},
"flex_algo": 129
},
2: {
"hosts": {
"R1-asr1k-43": {
"metric": 33554428,
"interface": {
"Gi0/1/4": {
"next_hop": "R3-asr1k-53",
"snpa": "c014.fe84.b306"
}
}
},
"R3-asr1k-53": {
"metric": 16777214,
"interface": {
"Gi0/1/4": {
"next_hop": "R3-asr1k-53",
"snpa": "c014.fe84.b306"
}
}
},
"R5-asr1k-11": {},
"R6-asr1k-20": {
"metric": 16777214,
"interface": {
"Gi0/0/2": {
"next_hop": "R6-asr1k-20",
"snpa": "3c57.31c1.fb32"
},
"Gi0/0/3": {
"next_hop": "R6-asr1k-20",
"snpa": "3c57.31c1.fb33"
}
}
}
},
"flex_algo": 129
}
}
}
}
} | expected_output = {'tag': {'1': {'level': {1: {'hosts': {'R1-asr1k-43': {'metric': 33554428, 'interface': {'Gi0/1/4': {'next_hop': 'R3-asr1k-53', 'snpa': 'c014.fe84.b306'}}}, 'R3-asr1k-53': {'metric': 16777214, 'interface': {'Gi0/1/4': {'next_hop': 'R3-asr1k-53', 'snpa': 'c014.fe84.b306'}}}, 'R5-asr1k-11': {}, 'R6-asr1k-20': {'metric': 16777214, 'interface': {'Gi0/0/2': {'next_hop': 'R6-asr1k-20', 'snpa': '3c57.31c1.fb32'}, 'Gi0/0/3': {'next_hop': 'R6-asr1k-20', 'snpa': '3c57.31c1.fb33'}}}}, 'flex_algo': 129}, 2: {'hosts': {'R1-asr1k-43': {'metric': 33554428, 'interface': {'Gi0/1/4': {'next_hop': 'R3-asr1k-53', 'snpa': 'c014.fe84.b306'}}}, 'R3-asr1k-53': {'metric': 16777214, 'interface': {'Gi0/1/4': {'next_hop': 'R3-asr1k-53', 'snpa': 'c014.fe84.b306'}}}, 'R5-asr1k-11': {}, 'R6-asr1k-20': {'metric': 16777214, 'interface': {'Gi0/0/2': {'next_hop': 'R6-asr1k-20', 'snpa': '3c57.31c1.fb32'}, 'Gi0/0/3': {'next_hop': 'R6-asr1k-20', 'snpa': '3c57.31c1.fb33'}}}}, 'flex_algo': 129}}}}} |
type_of_fire = input().split("#")
water_amount = int(input())
effort = 0
total_fire = 0
print(f"Cells:")
for i in type_of_fire:
cell = i.split(" ")
if water_amount <= 0:
break
if 0 < int(cell[2]) <= 50 and cell[0] == "Low":
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += (int(cell[2]) / 4)
total_fire += int(cell[2])
print(f" - {cell[2]}")
elif 50 < int(cell[2]) <= 80 and cell[0] == "Medium":
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += (int(cell[2]) / 4)
total_fire += int(cell[2])
print(f" - {cell[2]}")
elif 80 < int(cell[2]) <= 125 and cell[0] == "High":
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += (int(cell[2]) / 4)
total_fire += int(cell[2])
print(f" - {cell[2]}")
print(f"Effort: {effort:.2f}\nTotal Fire: {total_fire}") | type_of_fire = input().split('#')
water_amount = int(input())
effort = 0
total_fire = 0
print(f'Cells:')
for i in type_of_fire:
cell = i.split(' ')
if water_amount <= 0:
break
if 0 < int(cell[2]) <= 50 and cell[0] == 'Low':
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += int(cell[2]) / 4
total_fire += int(cell[2])
print(f' - {cell[2]}')
elif 50 < int(cell[2]) <= 80 and cell[0] == 'Medium':
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += int(cell[2]) / 4
total_fire += int(cell[2])
print(f' - {cell[2]}')
elif 80 < int(cell[2]) <= 125 and cell[0] == 'High':
if int(cell[2]) > water_amount:
continue
else:
water_amount -= int(cell[2])
effort += int(cell[2]) / 4
total_fire += int(cell[2])
print(f' - {cell[2]}')
print(f'Effort: {effort:.2f}\nTotal Fire: {total_fire}') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def person(name, age, **kwargs):
print(name, age, kwargs)
def product(*args):
r = 1
for v in args:
r *= v
return r
if __name__ == '__main__':
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
print('product(1, 2, 3):', product(1, 2, 3))
| def person(name, age, **kwargs):
print(name, age, kwargs)
def product(*args):
r = 1
for v in args:
r *= v
return r
if __name__ == '__main__':
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
print('product(1, 2, 3):', product(1, 2, 3)) |
#!/usr/bin/python
# Filename: ex_celsisu_to_fahrenheit_v1.py
celsius = 20
fahrenheit = (celsius * 9 / 5) + 32
print(fahrenheit)
| celsius = 20
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit) |
TRANSACTION_LEARN = 'learn'
TRANSACTION_PREDICT = 'predict'
TRANSACTION_NORMAL_SELECT = 'normal_select'
TRANSACTION_NORMAL_MODIFY = 'normal_modify'
TRANSACTION_BAD_QUERY = 'bad_query'
TRANSACTION_DROP_MODEL ='drop_model'
STOP_TRAINING = 'stop_training'
KILL_TRAINING = 'kill_training'
KEY_NO_GROUP_BY = 'ALL_ROWS_NO_GROUP_BY'
class DATA_SUBTYPES:
# Numeric
INT = 'Int'
FLOAT = 'Float'
BINARY = 'Binary' # Should we have this ?
# DATETIME
DATE = 'Date' # YYYY-MM-DD
TIMESTAMP = 'Timestamp' # YYYY-MM-DD hh:mm:ss or 1852362464
# CATEGORICAL
SINGLE = 'Binary Category'
MULTIPLE = 'Category'
# FILE_PATH
IMAGE = 'Image'
VIDEO = 'Video'
AUDIO = 'Audio'
# URL
# How do we detect the tpye here... maybe setup async download for random sample an stats ?
# SEQUENTIAL
TEXT = 'Text'
ARRAY = 'Array' # Do we even want to support arrays / structs / nested ... etc ?
class DATA_TYPES:
NUMERIC = 'Numeric'
DATE = 'Date'
CATEGORICAL = 'Categorical'
FILE_PATH = 'File Path'
URL = 'Url'
SEQUENTIAL = 'Sequential'
class DATA_TYPES_SUBTYPES:
subtypes = {
DATA_TYPES.NUMERIC: (DATA_SUBTYPES.INT, DATA_SUBTYPES.FLOAT, DATA_SUBTYPES.BINARY)
,DATA_TYPES.DATE:(DATA_SUBTYPES.DATE, DATA_SUBTYPES.TIMESTAMP)
,DATA_TYPES.CATEGORICAL:(DATA_SUBTYPES.SINGLE, DATA_SUBTYPES.MULTIPLE)
,DATA_TYPES.FILE_PATH:(DATA_SUBTYPES.IMAGE, DATA_SUBTYPES.VIDEO, DATA_SUBTYPES.AUDIO)
,DATA_TYPES.URL:()
,DATA_TYPES.SEQUENTIAL:(DATA_SUBTYPES.TEXT, DATA_SUBTYPES.ARRAY)
}
class ORDER_BY_KEYS:
COLUMN = 0
ASCENDING_VALUE = 1
PHASE_DATA_EXTRACTOR = 1
PHASE_STATS_GENERATOR = 2
PHASE_MODEL_INTERFACE = 3
PHASE_MODEL_ANALYZER = 4
MODEL_STATUS_TRAINED = "Trained"
MODEL_STATUS_PREPARING = "Preparing"
MODEL_STATUS_DATA_ANALYSIS = "Data Analysis"
MODEL_STATUS_TRAINING= "Training"
MODEL_STATUS_ANALYZING = "Analyzing"
MODEL_STATUS_ERROR = "Error"
WORD_SEPARATORS = [',', "\t", ' ']
DEBUG_LOG_LEVEL = 10
INFO_LOG_LEVEL = 20
WARNING_LOG_LEVEL = 30
ERROR_LOG_LEVEL = 40
NO_LOGS_LOG_LEVEL = 50
| transaction_learn = 'learn'
transaction_predict = 'predict'
transaction_normal_select = 'normal_select'
transaction_normal_modify = 'normal_modify'
transaction_bad_query = 'bad_query'
transaction_drop_model = 'drop_model'
stop_training = 'stop_training'
kill_training = 'kill_training'
key_no_group_by = 'ALL_ROWS_NO_GROUP_BY'
class Data_Subtypes:
int = 'Int'
float = 'Float'
binary = 'Binary'
date = 'Date'
timestamp = 'Timestamp'
single = 'Binary Category'
multiple = 'Category'
image = 'Image'
video = 'Video'
audio = 'Audio'
text = 'Text'
array = 'Array'
class Data_Types:
numeric = 'Numeric'
date = 'Date'
categorical = 'Categorical'
file_path = 'File Path'
url = 'Url'
sequential = 'Sequential'
class Data_Types_Subtypes:
subtypes = {DATA_TYPES.NUMERIC: (DATA_SUBTYPES.INT, DATA_SUBTYPES.FLOAT, DATA_SUBTYPES.BINARY), DATA_TYPES.DATE: (DATA_SUBTYPES.DATE, DATA_SUBTYPES.TIMESTAMP), DATA_TYPES.CATEGORICAL: (DATA_SUBTYPES.SINGLE, DATA_SUBTYPES.MULTIPLE), DATA_TYPES.FILE_PATH: (DATA_SUBTYPES.IMAGE, DATA_SUBTYPES.VIDEO, DATA_SUBTYPES.AUDIO), DATA_TYPES.URL: (), DATA_TYPES.SEQUENTIAL: (DATA_SUBTYPES.TEXT, DATA_SUBTYPES.ARRAY)}
class Order_By_Keys:
column = 0
ascending_value = 1
phase_data_extractor = 1
phase_stats_generator = 2
phase_model_interface = 3
phase_model_analyzer = 4
model_status_trained = 'Trained'
model_status_preparing = 'Preparing'
model_status_data_analysis = 'Data Analysis'
model_status_training = 'Training'
model_status_analyzing = 'Analyzing'
model_status_error = 'Error'
word_separators = [',', '\t', ' ']
debug_log_level = 10
info_log_level = 20
warning_log_level = 30
error_log_level = 40
no_logs_log_level = 50 |
choices = ["rock", "paper", "scissors"]
player_lives = 3
computer_lives = 3
total_lives = 3
player = False; | choices = ['rock', 'paper', 'scissors']
player_lives = 3
computer_lives = 3
total_lives = 3
player = False |
path = os.getcwd()
csv_files = []
for i in csv_folders:
csv_files.append(glob.glob(os.path.join(f'{i}', "*.csv")))
#speed (max, min, avg, median), distance travelled (max, min, avg, median), time travelled per trip (max, min, avg, median)
def data(file):
for i in range(len(file)):
d = [dist(i)[0] for i in drive(file[i])]
sp = [dist(i)[1] for i in drive(file[i])]
t = [dist(i)[2] for i in drive(file[i])]
details = [str(i), max(sp), min(sp), mean(sp), median(sp), max(d), min(d), mean(d), median(d), sum(d), max(t), min(t), mean(t), median(t), sum(t)]
df.loc[len(df)] = details
return df
def data_per_driver(file):
distance = []
for i in range(1, len(file)):
distance.append(((file.x[i]-file.x[i-1])**2 + (file.y[i]-file.y[i-1])**2)**0.5)
return [sum(distance)/1000, sum(distance)*18/(len(file)*5), len(file)/3600]
#df = data(csv_files)
#new_csv = csv_files
portion1 = new_csv[0:50]
new_csv = new_csv[50:]
print(len(new_csv), len(csv_files))
res = pd.DataFrame(columns = ['turno', 'tripDuration', 'tripDistance', 'activeDriving', 'stopDuration', 'stopNo', 'speed', 'jerkCount', 'maxAngVel', 'maxAcc',
'maxJerk', 'medianSpeed', 'medianAcc', 'avgAngleChange', 'meanSpeed', 'meanAcc', 'urban', 'highway', 'speedingUrban',
'speedingHighway'])
res = pd.read_csv('final.csv')
del res['Unnamed: 0']
p1 = join(portion4, 50)
p2 = join(portion5, 36)
#p3 = join(portion3, 50)
res = pd.concat([res, p1, p2], axis=0)
| path = os.getcwd()
csv_files = []
for i in csv_folders:
csv_files.append(glob.glob(os.path.join(f'{i}', '*.csv')))
def data(file):
for i in range(len(file)):
d = [dist(i)[0] for i in drive(file[i])]
sp = [dist(i)[1] for i in drive(file[i])]
t = [dist(i)[2] for i in drive(file[i])]
details = [str(i), max(sp), min(sp), mean(sp), median(sp), max(d), min(d), mean(d), median(d), sum(d), max(t), min(t), mean(t), median(t), sum(t)]
df.loc[len(df)] = details
return df
def data_per_driver(file):
distance = []
for i in range(1, len(file)):
distance.append(((file.x[i] - file.x[i - 1]) ** 2 + (file.y[i] - file.y[i - 1]) ** 2) ** 0.5)
return [sum(distance) / 1000, sum(distance) * 18 / (len(file) * 5), len(file) / 3600]
portion1 = new_csv[0:50]
new_csv = new_csv[50:]
print(len(new_csv), len(csv_files))
res = pd.DataFrame(columns=['turno', 'tripDuration', 'tripDistance', 'activeDriving', 'stopDuration', 'stopNo', 'speed', 'jerkCount', 'maxAngVel', 'maxAcc', 'maxJerk', 'medianSpeed', 'medianAcc', 'avgAngleChange', 'meanSpeed', 'meanAcc', 'urban', 'highway', 'speedingUrban', 'speedingHighway'])
res = pd.read_csv('final.csv')
del res['Unnamed: 0']
p1 = join(portion4, 50)
p2 = join(portion5, 36)
res = pd.concat([res, p1, p2], axis=0) |
__name__ = "__main__"
def bar():
print("bar")
print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard") | __name__ = '__main__'
def bar():
print('bar')
print('before __name__ guard')
if __name__ == '__main__':
bar()
print('after __name__ guard') |
__all__ = ["user"]
for _import in __all__:
__import__(__package__ + "." + _import)
| __all__ = ['user']
for _import in __all__:
__import__(__package__ + '.' + _import) |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
count = 1
while count < len(nums):
if nums[count] == nums[count - 1]:
nums.remove(nums[count])
else:
count += 1
return len(nums)
| class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
count = 1
while count < len(nums):
if nums[count] == nums[count - 1]:
nums.remove(nums[count])
else:
count += 1
return len(nums) |
def hello(name='World'):
if not isinstance(name, str):
raise Exception("ValueError: name should be of type str")
return 'Hello, {}!'.format(name) | def hello(name='World'):
if not isinstance(name, str):
raise exception('ValueError: name should be of type str')
return 'Hello, {}!'.format(name) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014, Mingze
# Author: Mingze (mxu@microstrategy.com)
class cmd:
ATT_ErrorRsp = 'ATT_ErrorRsp',
ATT_ExchangeMTUReq = 'ATT_ExchangeMTUReq',
ATT_ExchangeMTURsp = 'ATT_ExchangeMTURsp',
ATT_FindInfoReq = 'ATT_FindInfoReq',
ATT_FindInfoRsp = 'ATT_FindInfoRsp',
ATT_FindByTypeValueReq = 'ATT_FindByTypeValueReq',
ATT_FindByTypeValueRsp = 'ATT_FindByTypeValueRsp',
ATT_FindByTypeReq = 'ATT_FindByTypeReq',
ATT_FindByTypeRsp = 'ATT_FindByTypeRsp',
ATT_ReadReq = 'ATT_ReadReq',
ATT_ReadRsp = 'ATT_ReadRsp',
ATT_ReadBlobReq = 'ATT_ReadBlobReq',
ATT_ReadBlobRsp = 'ATT_ReadBlobRsp',
ATT_ReadByGrpTypeReq = 'ATT_ReadByGrpTypeReq',
ATT_ReadByGrpTypeRsp = 'ATT_ReadByGrpTypeRsp',
ATT_WriteReq = 'ATT_WriteReq',
ATT_WriteRsp = 'ATT_WriteRsp',
ATT_PrepareWriteReq = 'ATT_PrepareWriteReq',
ATT_PrepareWriteRsp = 'ATT_PrepareWriteRsp',
ATT_ExecuteWriteReq = 'ATT_ExecuteWriteReq',
ATT_ExecuteWriteRsp = 'ATT_ExecuteWriteRsp',
ATT_HandleValueNotification = 'ATT_HandleValueNotification',
ATT_HandleValueIndication = 'ATT_HandleValueIndication',
ATT_HandleValueConfirmation = 'ATT_HandleValueConfirmation',
GATT_DiscPrimaryServiceByUUID = 'GATT_DiscPrimaryServiceByUUID',
GATT_DiscCharsByUUID = 'GATT_DiscCharsByUUID',
GATT_ReadCharValue = 'GATT_ReadCharValue',
GATT_WriteCharValue = 'GATT_WriteCharValue',
GATT_ReadMultipleCharValues = 'GATT_ReadMultipleCharValues',
GATT_ReadMultipleCharValues = 'GATT_WriteCharValue',
GATT_WriteLongCharValue = 'GATT_WriteLongCharValue',
GATT_DiscAllChars = 'GATT_DiscAllChars',
GATT_ReadUsingCharUUID = 'GATT_ReadUsingCharUUID',
GATT_AddService = 'GATT_AddService',
GATT_DelService = 'GATT_DelService',
GATT_AddAttribute = 'GATT_AddAttribute',
GAP_DeviceInit = 'GAP_DeviceInit',
GAP_ConfigureDeviceAddr = 'GAP_ConfigureDeviceAddr',
GATT_DeviceDiscoveryRequest = 'GATT_DeviceDiscoveryRequest',
GATT_DeviceDiscoveryCancel = 'GATT_DeviceDiscoveryCancel',
GAP_MakeDiscoverable = 'GAP_MakeDiscoverable',
GAP_UpdateAdvertisingData = 'GAP_UpdateAdvertisingData',
GAP_EndDiscoverable = 'GAP_EndDiscoverable',
GAP_EstablishLinkRequest = 'GAP_EstablishLinkRequest',
GAP_TerminateLinkRequest = 'GAP_TerminateLinkRequest',
GAP_UpdateLinkParamReq = 'GAP_UpdateLinkParamReq',
GAP_SetParam = 'GAP_SetParam',
GAP_GetParam = 'GAP_GetParam',
HTIL_Reset = 'HTIL_Reset'
class event:
HCI_LE_ExtEvent = 'HCI_LE_ExtEvent'
ATT_ErrorRsp = 'ATT_ErrorRsp',
ATT_ExchangeMTUReq = 'ATT_ExchangeMTUReq',
ATT_ExchangeMTURsp = 'ATT_ExchangeMTURsp',
ATT_FindInfoReq = 'ATT_FindInfoReq',
ATT_FindInfoRsp = 'ATT_FindInfoRsp',
ATT_FindByTypeValueReq = 'ATT_FindByTypeValueReq',
ATT_FindByTypeValueRsp = 'ATT_FindByTypeValueRsp',
ATT_ReadByTypeReq = 'ATT_ReadByTypeReq',
ATT_ReadByTypeRsp = 'ATT_ReadByTypeRsp',
ATT_ReadReq = 'ATT_ReadReq',
ATT_ReadRsp = 'ATT_ReadRsp',
ATT_ReadBlobReq = 'ATT_ReadBlobReq',
ATT_ReadBlobRsp = 'ATT_ReadBlobRsp',
ATT_ReadMultiReq = 'ATT_ReadMultiReq',
ATT_ReadMultiRsp = 'ATT_ReadMultiRsp',
ATT_ReadByGrpTypeReq = 'ATT_ReadByGrpTypeReq',
ATT_ReadByGrpTypeRsp = 'ATT_ReadByGrpTypeRsp',
ATT_WriteReq = 'ATT_WriteReq',
ATT_WriteRsp = 'ATT_WriteRsp',
ATT_PrepareWriteReq = 'ATT_PrepareWriteReq',
ATT_PrepareWriteRsp = 'ATT_PrepareWriteRsp',
ATT_ExecuteWriteReq = 'ATT_ExecuteWriteReq',
ATT_ExecuteWriteRsp = 'ATT_ExecuteWriteRsp',
ATT_HandleValueNotification = 'ATT_HandleValueNotification',
ATT_HandleValueIndication = 'ATT_HandleValueIndication',
ATT_HandleValueConfirmation = 'ATT_HandleValueConfirmation',
GATT_ClientCharCfgUpdated = 'GATT_ClientCharCfgUpdated',
GATT_DiscCharsByUUID = 'GATT_DiscCharsByUUID',
GAP_DeviceInitDone = 'GAP_DeviceInitDone',
GAP_DeviceDiscoveryDone = 'GAP_DeviceDiscoveryDone',
GAP_AdvertDataUpdateDone = 'GAP_AdvertDataUpdateDone',
GAP_MakeDiscoverableDone = 'GAP_MakeDiscoverableDone',
GAP_EndDiscoverableDone = 'GAP_EndDiscoverableDone',
GAP_LinkEstablished = 'GAP_LinkEstablished',
GAP_LinkTerminated = 'GAP_LinkTerminated',
GAP_LinkParamUpdate = 'GAP_LinkParamUpdate',
GAP_DeviceInformation = 'GAP_DeviceInformation',
GAP_HCI_ExtensionCommandStatus = 'GAP_HCI_ExtensionCommandStatus',
opcodes = {
"fd01":cmd.ATT_ErrorRsp,
"fd02":cmd.ATT_ExchangeMTUReq,
"fd03":cmd.ATT_ExchangeMTURsp,
"fd04":cmd.ATT_FindInfoReq,
"fd05":cmd.ATT_FindInfoRsp,
"fd06":cmd.ATT_FindByTypeValueReq,
"fd07":cmd.ATT_FindByTypeValueRsp,
"fd08":cmd.ATT_FindByTypeReq,
"fd09":cmd.ATT_FindByTypeRsp,
"fd0a":cmd.ATT_ReadReq,
"fd0b":cmd.ATT_ReadRsp,
"fd0c":cmd.ATT_ReadBlobReq,
"fd0d":cmd.ATT_ReadBlobRsp,
"fd10":cmd.ATT_ReadByGrpTypeReq,
"fd11":cmd.ATT_ReadByGrpTypeRsp,
"fd12":cmd.ATT_WriteReq,
"fd13":cmd.ATT_WriteRsp,
"fd16":cmd.ATT_PrepareWriteReq,
"fd17":cmd.ATT_PrepareWriteRsp,
"fd18":cmd.ATT_ExecuteWriteReq,
"fd19":cmd.ATT_ExecuteWriteRsp,
"fd1b":cmd.ATT_HandleValueNotification,
"fd1d":cmd.ATT_HandleValueIndication,
"fd1e":cmd.ATT_HandleValueConfirmation,
"fd86":cmd.GATT_DiscPrimaryServiceByUUID,
"fd88":cmd.GATT_DiscCharsByUUID,
"fd8a":cmd.GATT_ReadCharValue,
"fd8e":cmd.GATT_ReadMultipleCharValues,
"fd92":cmd.GATT_WriteCharValue,
"fd96":cmd.GATT_WriteLongCharValue,
"fdb2":cmd.GATT_DiscAllChars,
"fdb4":cmd.GATT_ReadUsingCharUUID,
"fdfc":cmd.GATT_AddService,
"fdfd":cmd.GATT_DelService,
"fdfe":cmd.GATT_AddAttribute,
"fe00":cmd.GAP_DeviceInit,
"fe03":cmd.GAP_ConfigureDeviceAddr,
"fe04":cmd.GATT_DeviceDiscoveryRequest,
"fe05":cmd.GATT_DeviceDiscoveryCancel,
"fe06":cmd.GAP_MakeDiscoverable,
"fe07":cmd.GAP_UpdateAdvertisingData,
"fe08":cmd.GAP_EndDiscoverable,
"fe09":cmd.GAP_EstablishLinkRequest,
"fe0a":cmd.GAP_TerminateLinkRequest,
"fe11":cmd.GAP_UpdateLinkParamReq,
"fe30":cmd.GAP_SetParam,
"fe31":cmd.GAP_GetParam,
"fe80":cmd.HTIL_Reset,
}
hci_cmds = {
"fd01":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'req_opcode', 'len':1, 'default':'\x00'},
{'name':'handle', 'len':2, 'default':'\x00\x00'},
{'name':'error_code', 'len':1, 'default':'\x00'}],
"fd02":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'client_rx_mtu','len':2, 'default':'\x00\x87'}],
"fd03":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'server_rx_mtu','len':2, 'default':'\x00\x87'}],
"fd04":
[{'name':'conn_handle', 'len':2, 'default':'\xff\xfe'},
{'name':'start_handle','len':2, 'default':'\x00\x01'},
{'name':'end_handle', 'len':2, 'default':'\xff\xff'}],
"fd09":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'data_length', 'len':1, 'default':None},
{'name':'value', 'len':None, 'default':None}],
"fd0c":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'handle', 'len':2, 'default':'\x00\x00'},
{'name':'offset', 'len':2, 'default':'\x00\x00'}],
"fd0d":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'value', 'len':None, 'default':None}],
"fd10":
[{'name':'conn_handle', 'len':2, 'default':'\xff\xfe'},
{'name':'start_handle','len':2, 'default':'\x00\x01'},
{'name':'end_handle', 'len':2, 'default':'\xff\xff'},
{'name':'group_type', 'len':None, 'default':'\x00\x28'}], #by default it's service
"fd11":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'data_length', 'len':1, 'default':None},
{'name':'value', 'len':None, 'default':'\x00\x00'}],
"fd13":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'}],
"fd1b":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'authenticated', 'len':1, 'default':'\x00'},
{'name':'handle', 'len':2, 'default':'\xfe\xff'},
{'name':'value', 'len':None, 'default':None}],
"fd1d":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'authenticated', 'len':1, 'default':'\x00'},
{'name':'handle', 'len':2, 'default':'\xfe\xff'},
{'name':'value', 'len':None, 'default':None}],
"fd1e":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'}],
"fd86":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'value', 'len':None, 'default':None}],
"fd88":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'start_handle','len':2, 'default':'\x01\x00'},
{'name':'end_handle', 'len':2, 'default':'\xfe\xff'},
{'name':'type', 'len':None, 'default':None}],
"fd8a":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'handle', 'len':2, 'default':None}],
"fd8c":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'handle', 'len':2, 'default':'\x00\x00'},
{'name':'offset', 'len':2, 'default':'\x00\x00'},
{'name':'type', 'len':1, 'default':'\x00'}],
"fd8e":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'handles', 'len':None, 'default':None}],
"fd92":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'handle', 'len':2, 'default':None},
{'name':'value', 'len':None, 'default':None}],
"fd96":
[{'name':'handle', 'len':2, 'default':'\x00\x00'},
{'name':'offset', 'len':1, 'default':None},
{'name':'value', 'len':None, 'default':None}],
"fdb2":
[{'name':'start_handle','len':2, 'default':'\x00\x00'},
{'name':'end_handle', 'len':2, 'default':'\xff\xff'}],
"fdb4":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'start_handle','len':2, 'default':'\x01\x00'},
{'name':'end_handle', 'len':2, 'default':'\xff\xff'},
{'name':'read_type', 'len':2, 'default':None}],
"fdfc":
[{'name':'uuid', 'len':2, 'default':'\x28\x00'},
{'name':'numAttrs', 'len':2, 'default':'\x00\x01'}],
"fdfd":
[{'name':'handle', 'len':2, 'default':'\x00\x01'}],
"fdfe":
[{'name':'uuid', 'len':None, 'default':'\x00\0x00'},
{'name':'permissions', 'len':1, 'default':'\x03'}],
"fe00":
[{'name':'profile_role','len':1, 'default':'\x08'},
{'name':'max_scan_rsps','len':1, 'default':'\xa0'},
{'name':'irk', 'len':16, 'default':'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'},
{'name':'csrk', 'len':16, 'default':'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'},
{'name':'sign_counter','len':4, 'default':'\x01\x00\x00\x00'}],
"fe03":
[{'name':'addr_type', 'len':1, 'default':None},
{'name':'addr', 'len':6, 'default':None}],
"fe04":
[{'name':'mode', 'len':1, 'default':None},
{'name':'active_scan', 'len':1, 'default':'\x01'},
{'name':'white_list', 'len':1, 'default':'\x00'}],
"fe05":
[],
"fe06":
[{'name':'event_type', 'len':1, 'default':'\x00'},
{'name':'init_addr_type', 'len':1, 'default':'\x00'},
{'name':'init_addrs', 'len':6, 'default':'\x00\x00\x00\x00\x00\x00'},
{'name':'channel_map', 'len':1, 'default':'\x07'},
{'name':'filter_policy','len':1, 'default':'\x00'}],
"fe07":
[{'name':'ad_type', 'len':1, 'default':'\x01'},
{'name':'data_length', 'len':1, 'default':None},
{'name':'advert_data', 'len':None, 'default':'\x02\x01\x07'}],
"fe08":
[],
"fe09":
[{'name':'high_duty_cycle','len':1, 'default':'\x00'},
{'name':'white_list', 'len':1, 'default':'\x00'},
{'name':'addr_type_peer','len':1, 'default':'\x00'},
{'name':'peer_addr', 'len':6, 'default':None}],
"fe0a":
[{'name':'conn_handle', 'len':2, 'default':'\x00\x00'},
{'name':'disconnect_reason', 'len':1, 'default':'\x13'}],
"fe30":
[{'name':'param_id', 'len':1, 'default':None},
{'name':'param_value', 'len':2, 'default':None}],
"fe31":
[{'name':'param_id', 'len':1, 'default':None}],
"fe80":
[{'name':'reset_type', 'len':1, 'default':'\x01'}],
"0c03":
[],
}
hci_events = {"ff":
{'name':event.HCI_LE_ExtEvent,
'structure':
[{'name':'ext_event', 'len':None}]},
}
ext_events= {"0501":
{'name':event.ATT_ErrorRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'req_op_code', 'len':1},
{'name':'handle', 'len':2},
{'name':'error_code', 'len':1}]},
"0502":
{'name':event.ATT_ExchangeMTUReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'client_rx_mtu','len':2}]},
"0503":
{'name':event.ATT_ExchangeMTURsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'server_rx_mtu','len':2}]},
"0504":
{'name':event.ATT_FindInfoReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'start_handle','len':2},
{'name':'end_handle', 'len':2}]},
"0505":
{'name':event.ATT_FindInfoRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'format', 'len':1},
{'name':'results', 'len':None}],
'parsing':
[('results', lambda ble, original:
ble._parse_find_info_results(original['results'], original['format']))]},
"0506":
{'name':event.ATT_FindByTypeValueReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'start_handle','len':2},
{'name':'end_handle', 'len':2}]},
"0507":
{'name':event.ATT_FindByTypeValueRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'start_handle','len':2},
{'name':'end_handle', 'len':2},
{'name':'value', 'len':None}]},
"0508":
{'name':event.ATT_ReadByTypeReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'start_handle','len':2},
{'name':'end_handle', 'len':2},
{'name':'type', 'len':None}]},
"0509":
{'name':event.ATT_ReadByTypeRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'length', 'len':1},
{'name':'handle', 'len':2},
{'name':'value', 'len':None}]},
"050b":
{'name':event.ATT_ReadRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'value', 'len':None}]},
"050c":
{'name':event.ATT_ReadBlobReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'handle', 'len':2},
{'name':'offset', 'len':2}]},
"050d":
{'name':event.ATT_ReadBlobRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'value', 'len':None}]},
"050f":
{'name':event.ATT_ReadMultiRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'results', 'len':None}]},
"0510":
{'name':event.ATT_ReadByGrpTypeReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'start_handle','len':2},
{'name':'end_handle', 'len':2},
{'name':'group_type', 'len':2}]},
"0511":
{'name':event.ATT_ReadByGrpTypeRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1}]},
"0512":
{'name':event.ATT_WriteReq,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'signature', 'len':1},
{'name':'command', 'len':1},
{'name':'handle', 'len':2},
{'name':'value', 'len':None}]},
"0513":
{'name':event.ATT_WriteRsp,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1}]},
"051b":
{'name':event.ATT_HandleValueNotification,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'handle', 'len':2},
{'name':'values', 'len':None}]},
"051d":
{'name':event.ATT_HandleValueIndication,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'handle', 'len':2},
{'name':'values', 'len':None}]},
"051e":
{'name':event.ATT_HandleValueConfirmation,
'structure':
[{'name':'conn_handle', 'len':2}]},
"0580":
{'name':event.GATT_ClientCharCfgUpdated,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'pdu_len', 'len':1},
{'name':'attr_handle', 'len':2},
{'name':'value', 'len':1}]},
"0600":
{'name':event.GAP_DeviceInitDone,
'structure':
[{'name':'dev_addr', 'len':6},
{'name':'data_pkt_len','len':2},
{'name':'num_data_pkts','len':1},
{'name':'irk', 'len':16},
{'name':'csrk', 'len':16}]},
"0601":
{'name':event.GAP_DeviceDiscoveryDone,
'structure':
[{'name':'num_devs', 'len':1},
{'name':'devices', 'len':None}],
'parsing':
[('devices', lambda ble, original:
ble._parse_devices(original['devices']))]},
"0602":
{'name':event.GAP_AdvertDataUpdateDone,
'structure':
[{'name':'ad_type', 'len':1}]},
"0603":
{'name':event.GAP_MakeDiscoverableDone,
'structure':
[]},
"0604":
{'name':event.GAP_EndDiscoverableDone,
'structure':
[]},
"0605":
{'name':event.GAP_LinkEstablished,
'structure':
[{'name':'dev_addr_type','len':1},
{'name':'dev_addr', 'len':6},
{'name':'conn_handle', 'len':2},
{'name':'conn_interval','len':2},
{'name':'conn_latency','len':2},
{'name':'conn_timeout','len':2},
{'name':'clock_accuracy','len':1}]},
"0606":
{'name':event.GAP_LinkTerminated,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'value', 'len':None}]},
"0607":
{'name':event.GAP_LinkParamUpdate,
'structure':
[{'name':'conn_handle', 'len':2},
{'name':'conn_interval', 'len':2},
{'name':'conn_latency', 'len':2},
{'name':'conn_timeout', 'len':2}]},
"060d":
{'name':event.GAP_DeviceInformation,
'structure':
[{'name':'event_type', 'len':1},
{'name':'addr_type', 'len':1},
{'name':'addr', 'len':6},
{'name':'rssi', 'len':1},
{'name':'data_len', 'len':1},
{'name':'data_field', 'len':None}]},
"067f":
{'name':event.GAP_HCI_ExtensionCommandStatus,
'structure':
[{'name':'op_code', 'len':2},
{'name':'data_len', 'len':1},
{'name':'param_value', 'len':None}],
'parsing':
[('op_code', lambda ble, original:
ble._parse_opcodes(original['op_code']))]},
} | class Cmd:
att__error_rsp = ('ATT_ErrorRsp',)
att__exchange_mtu_req = ('ATT_ExchangeMTUReq',)
att__exchange_mtu_rsp = ('ATT_ExchangeMTURsp',)
att__find_info_req = ('ATT_FindInfoReq',)
att__find_info_rsp = ('ATT_FindInfoRsp',)
att__find_by_type_value_req = ('ATT_FindByTypeValueReq',)
att__find_by_type_value_rsp = ('ATT_FindByTypeValueRsp',)
att__find_by_type_req = ('ATT_FindByTypeReq',)
att__find_by_type_rsp = ('ATT_FindByTypeRsp',)
att__read_req = ('ATT_ReadReq',)
att__read_rsp = ('ATT_ReadRsp',)
att__read_blob_req = ('ATT_ReadBlobReq',)
att__read_blob_rsp = ('ATT_ReadBlobRsp',)
att__read_by_grp_type_req = ('ATT_ReadByGrpTypeReq',)
att__read_by_grp_type_rsp = ('ATT_ReadByGrpTypeRsp',)
att__write_req = ('ATT_WriteReq',)
att__write_rsp = ('ATT_WriteRsp',)
att__prepare_write_req = ('ATT_PrepareWriteReq',)
att__prepare_write_rsp = ('ATT_PrepareWriteRsp',)
att__execute_write_req = ('ATT_ExecuteWriteReq',)
att__execute_write_rsp = ('ATT_ExecuteWriteRsp',)
att__handle_value_notification = ('ATT_HandleValueNotification',)
att__handle_value_indication = ('ATT_HandleValueIndication',)
att__handle_value_confirmation = ('ATT_HandleValueConfirmation',)
gatt__disc_primary_service_by_uuid = ('GATT_DiscPrimaryServiceByUUID',)
gatt__disc_chars_by_uuid = ('GATT_DiscCharsByUUID',)
gatt__read_char_value = ('GATT_ReadCharValue',)
gatt__write_char_value = ('GATT_WriteCharValue',)
gatt__read_multiple_char_values = ('GATT_ReadMultipleCharValues',)
gatt__read_multiple_char_values = ('GATT_WriteCharValue',)
gatt__write_long_char_value = ('GATT_WriteLongCharValue',)
gatt__disc_all_chars = ('GATT_DiscAllChars',)
gatt__read_using_char_uuid = ('GATT_ReadUsingCharUUID',)
gatt__add_service = ('GATT_AddService',)
gatt__del_service = ('GATT_DelService',)
gatt__add_attribute = ('GATT_AddAttribute',)
gap__device_init = ('GAP_DeviceInit',)
gap__configure_device_addr = ('GAP_ConfigureDeviceAddr',)
gatt__device_discovery_request = ('GATT_DeviceDiscoveryRequest',)
gatt__device_discovery_cancel = ('GATT_DeviceDiscoveryCancel',)
gap__make_discoverable = ('GAP_MakeDiscoverable',)
gap__update_advertising_data = ('GAP_UpdateAdvertisingData',)
gap__end_discoverable = ('GAP_EndDiscoverable',)
gap__establish_link_request = ('GAP_EstablishLinkRequest',)
gap__terminate_link_request = ('GAP_TerminateLinkRequest',)
gap__update_link_param_req = ('GAP_UpdateLinkParamReq',)
gap__set_param = ('GAP_SetParam',)
gap__get_param = ('GAP_GetParam',)
htil__reset = 'HTIL_Reset'
class Event:
hci_le__ext_event = 'HCI_LE_ExtEvent'
att__error_rsp = ('ATT_ErrorRsp',)
att__exchange_mtu_req = ('ATT_ExchangeMTUReq',)
att__exchange_mtu_rsp = ('ATT_ExchangeMTURsp',)
att__find_info_req = ('ATT_FindInfoReq',)
att__find_info_rsp = ('ATT_FindInfoRsp',)
att__find_by_type_value_req = ('ATT_FindByTypeValueReq',)
att__find_by_type_value_rsp = ('ATT_FindByTypeValueRsp',)
att__read_by_type_req = ('ATT_ReadByTypeReq',)
att__read_by_type_rsp = ('ATT_ReadByTypeRsp',)
att__read_req = ('ATT_ReadReq',)
att__read_rsp = ('ATT_ReadRsp',)
att__read_blob_req = ('ATT_ReadBlobReq',)
att__read_blob_rsp = ('ATT_ReadBlobRsp',)
att__read_multi_req = ('ATT_ReadMultiReq',)
att__read_multi_rsp = ('ATT_ReadMultiRsp',)
att__read_by_grp_type_req = ('ATT_ReadByGrpTypeReq',)
att__read_by_grp_type_rsp = ('ATT_ReadByGrpTypeRsp',)
att__write_req = ('ATT_WriteReq',)
att__write_rsp = ('ATT_WriteRsp',)
att__prepare_write_req = ('ATT_PrepareWriteReq',)
att__prepare_write_rsp = ('ATT_PrepareWriteRsp',)
att__execute_write_req = ('ATT_ExecuteWriteReq',)
att__execute_write_rsp = ('ATT_ExecuteWriteRsp',)
att__handle_value_notification = ('ATT_HandleValueNotification',)
att__handle_value_indication = ('ATT_HandleValueIndication',)
att__handle_value_confirmation = ('ATT_HandleValueConfirmation',)
gatt__client_char_cfg_updated = ('GATT_ClientCharCfgUpdated',)
gatt__disc_chars_by_uuid = ('GATT_DiscCharsByUUID',)
gap__device_init_done = ('GAP_DeviceInitDone',)
gap__device_discovery_done = ('GAP_DeviceDiscoveryDone',)
gap__advert_data_update_done = ('GAP_AdvertDataUpdateDone',)
gap__make_discoverable_done = ('GAP_MakeDiscoverableDone',)
gap__end_discoverable_done = ('GAP_EndDiscoverableDone',)
gap__link_established = ('GAP_LinkEstablished',)
gap__link_terminated = ('GAP_LinkTerminated',)
gap__link_param_update = ('GAP_LinkParamUpdate',)
gap__device_information = ('GAP_DeviceInformation',)
gap_hci__extension_command_status = ('GAP_HCI_ExtensionCommandStatus',)
opcodes = {'fd01': cmd.ATT_ErrorRsp, 'fd02': cmd.ATT_ExchangeMTUReq, 'fd03': cmd.ATT_ExchangeMTURsp, 'fd04': cmd.ATT_FindInfoReq, 'fd05': cmd.ATT_FindInfoRsp, 'fd06': cmd.ATT_FindByTypeValueReq, 'fd07': cmd.ATT_FindByTypeValueRsp, 'fd08': cmd.ATT_FindByTypeReq, 'fd09': cmd.ATT_FindByTypeRsp, 'fd0a': cmd.ATT_ReadReq, 'fd0b': cmd.ATT_ReadRsp, 'fd0c': cmd.ATT_ReadBlobReq, 'fd0d': cmd.ATT_ReadBlobRsp, 'fd10': cmd.ATT_ReadByGrpTypeReq, 'fd11': cmd.ATT_ReadByGrpTypeRsp, 'fd12': cmd.ATT_WriteReq, 'fd13': cmd.ATT_WriteRsp, 'fd16': cmd.ATT_PrepareWriteReq, 'fd17': cmd.ATT_PrepareWriteRsp, 'fd18': cmd.ATT_ExecuteWriteReq, 'fd19': cmd.ATT_ExecuteWriteRsp, 'fd1b': cmd.ATT_HandleValueNotification, 'fd1d': cmd.ATT_HandleValueIndication, 'fd1e': cmd.ATT_HandleValueConfirmation, 'fd86': cmd.GATT_DiscPrimaryServiceByUUID, 'fd88': cmd.GATT_DiscCharsByUUID, 'fd8a': cmd.GATT_ReadCharValue, 'fd8e': cmd.GATT_ReadMultipleCharValues, 'fd92': cmd.GATT_WriteCharValue, 'fd96': cmd.GATT_WriteLongCharValue, 'fdb2': cmd.GATT_DiscAllChars, 'fdb4': cmd.GATT_ReadUsingCharUUID, 'fdfc': cmd.GATT_AddService, 'fdfd': cmd.GATT_DelService, 'fdfe': cmd.GATT_AddAttribute, 'fe00': cmd.GAP_DeviceInit, 'fe03': cmd.GAP_ConfigureDeviceAddr, 'fe04': cmd.GATT_DeviceDiscoveryRequest, 'fe05': cmd.GATT_DeviceDiscoveryCancel, 'fe06': cmd.GAP_MakeDiscoverable, 'fe07': cmd.GAP_UpdateAdvertisingData, 'fe08': cmd.GAP_EndDiscoverable, 'fe09': cmd.GAP_EstablishLinkRequest, 'fe0a': cmd.GAP_TerminateLinkRequest, 'fe11': cmd.GAP_UpdateLinkParamReq, 'fe30': cmd.GAP_SetParam, 'fe31': cmd.GAP_GetParam, 'fe80': cmd.HTIL_Reset}
hci_cmds = {'fd01': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'req_opcode', 'len': 1, 'default': '\x00'}, {'name': 'handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'error_code', 'len': 1, 'default': '\x00'}], 'fd02': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'client_rx_mtu', 'len': 2, 'default': '\x00\x87'}], 'fd03': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'server_rx_mtu', 'len': 2, 'default': '\x00\x87'}], 'fd04': [{'name': 'conn_handle', 'len': 2, 'default': 'ÿþ'}, {'name': 'start_handle', 'len': 2, 'default': '\x00\x01'}, {'name': 'end_handle', 'len': 2, 'default': 'ÿÿ'}], 'fd09': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'data_length', 'len': 1, 'default': None}, {'name': 'value', 'len': None, 'default': None}], 'fd0c': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'offset', 'len': 2, 'default': '\x00\x00'}], 'fd0d': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'value', 'len': None, 'default': None}], 'fd10': [{'name': 'conn_handle', 'len': 2, 'default': 'ÿþ'}, {'name': 'start_handle', 'len': 2, 'default': '\x00\x01'}, {'name': 'end_handle', 'len': 2, 'default': 'ÿÿ'}, {'name': 'group_type', 'len': None, 'default': '\x00('}], 'fd11': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'data_length', 'len': 1, 'default': None}, {'name': 'value', 'len': None, 'default': '\x00\x00'}], 'fd13': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}], 'fd1b': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'authenticated', 'len': 1, 'default': '\x00'}, {'name': 'handle', 'len': 2, 'default': 'þÿ'}, {'name': 'value', 'len': None, 'default': None}], 'fd1d': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'authenticated', 'len': 1, 'default': '\x00'}, {'name': 'handle', 'len': 2, 'default': 'þÿ'}, {'name': 'value', 'len': None, 'default': None}], 'fd1e': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}], 'fd86': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'value', 'len': None, 'default': None}], 'fd88': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'start_handle', 'len': 2, 'default': '\x01\x00'}, {'name': 'end_handle', 'len': 2, 'default': 'þÿ'}, {'name': 'type', 'len': None, 'default': None}], 'fd8a': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'handle', 'len': 2, 'default': None}], 'fd8c': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'offset', 'len': 2, 'default': '\x00\x00'}, {'name': 'type', 'len': 1, 'default': '\x00'}], 'fd8e': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'handles', 'len': None, 'default': None}], 'fd92': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'handle', 'len': 2, 'default': None}, {'name': 'value', 'len': None, 'default': None}], 'fd96': [{'name': 'handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'offset', 'len': 1, 'default': None}, {'name': 'value', 'len': None, 'default': None}], 'fdb2': [{'name': 'start_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'end_handle', 'len': 2, 'default': 'ÿÿ'}], 'fdb4': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'start_handle', 'len': 2, 'default': '\x01\x00'}, {'name': 'end_handle', 'len': 2, 'default': 'ÿÿ'}, {'name': 'read_type', 'len': 2, 'default': None}], 'fdfc': [{'name': 'uuid', 'len': 2, 'default': '(\x00'}, {'name': 'numAttrs', 'len': 2, 'default': '\x00\x01'}], 'fdfd': [{'name': 'handle', 'len': 2, 'default': '\x00\x01'}], 'fdfe': [{'name': 'uuid', 'len': None, 'default': '\x00\x00x00'}, {'name': 'permissions', 'len': 1, 'default': '\x03'}], 'fe00': [{'name': 'profile_role', 'len': 1, 'default': '\x08'}, {'name': 'max_scan_rsps', 'len': 1, 'default': '\xa0'}, {'name': 'irk', 'len': 16, 'default': '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'}, {'name': 'csrk', 'len': 16, 'default': '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'}, {'name': 'sign_counter', 'len': 4, 'default': '\x01\x00\x00\x00'}], 'fe03': [{'name': 'addr_type', 'len': 1, 'default': None}, {'name': 'addr', 'len': 6, 'default': None}], 'fe04': [{'name': 'mode', 'len': 1, 'default': None}, {'name': 'active_scan', 'len': 1, 'default': '\x01'}, {'name': 'white_list', 'len': 1, 'default': '\x00'}], 'fe05': [], 'fe06': [{'name': 'event_type', 'len': 1, 'default': '\x00'}, {'name': 'init_addr_type', 'len': 1, 'default': '\x00'}, {'name': 'init_addrs', 'len': 6, 'default': '\x00\x00\x00\x00\x00\x00'}, {'name': 'channel_map', 'len': 1, 'default': '\x07'}, {'name': 'filter_policy', 'len': 1, 'default': '\x00'}], 'fe07': [{'name': 'ad_type', 'len': 1, 'default': '\x01'}, {'name': 'data_length', 'len': 1, 'default': None}, {'name': 'advert_data', 'len': None, 'default': '\x02\x01\x07'}], 'fe08': [], 'fe09': [{'name': 'high_duty_cycle', 'len': 1, 'default': '\x00'}, {'name': 'white_list', 'len': 1, 'default': '\x00'}, {'name': 'addr_type_peer', 'len': 1, 'default': '\x00'}, {'name': 'peer_addr', 'len': 6, 'default': None}], 'fe0a': [{'name': 'conn_handle', 'len': 2, 'default': '\x00\x00'}, {'name': 'disconnect_reason', 'len': 1, 'default': '\x13'}], 'fe30': [{'name': 'param_id', 'len': 1, 'default': None}, {'name': 'param_value', 'len': 2, 'default': None}], 'fe31': [{'name': 'param_id', 'len': 1, 'default': None}], 'fe80': [{'name': 'reset_type', 'len': 1, 'default': '\x01'}], '0c03': []}
hci_events = {'ff': {'name': event.HCI_LE_ExtEvent, 'structure': [{'name': 'ext_event', 'len': None}]}}
ext_events = {'0501': {'name': event.ATT_ErrorRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'req_op_code', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'error_code', 'len': 1}]}, '0502': {'name': event.ATT_ExchangeMTUReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'client_rx_mtu', 'len': 2}]}, '0503': {'name': event.ATT_ExchangeMTURsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'server_rx_mtu', 'len': 2}]}, '0504': {'name': event.ATT_FindInfoReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'start_handle', 'len': 2}, {'name': 'end_handle', 'len': 2}]}, '0505': {'name': event.ATT_FindInfoRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'format', 'len': 1}, {'name': 'results', 'len': None}], 'parsing': [('results', lambda ble, original: ble._parse_find_info_results(original['results'], original['format']))]}, '0506': {'name': event.ATT_FindByTypeValueReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'start_handle', 'len': 2}, {'name': 'end_handle', 'len': 2}]}, '0507': {'name': event.ATT_FindByTypeValueRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'start_handle', 'len': 2}, {'name': 'end_handle', 'len': 2}, {'name': 'value', 'len': None}]}, '0508': {'name': event.ATT_ReadByTypeReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'start_handle', 'len': 2}, {'name': 'end_handle', 'len': 2}, {'name': 'type', 'len': None}]}, '0509': {'name': event.ATT_ReadByTypeRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'length', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'value', 'len': None}]}, '050b': {'name': event.ATT_ReadRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'value', 'len': None}]}, '050c': {'name': event.ATT_ReadBlobReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'offset', 'len': 2}]}, '050d': {'name': event.ATT_ReadBlobRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'value', 'len': None}]}, '050f': {'name': event.ATT_ReadMultiRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'results', 'len': None}]}, '0510': {'name': event.ATT_ReadByGrpTypeReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'start_handle', 'len': 2}, {'name': 'end_handle', 'len': 2}, {'name': 'group_type', 'len': 2}]}, '0511': {'name': event.ATT_ReadByGrpTypeRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}]}, '0512': {'name': event.ATT_WriteReq, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'signature', 'len': 1}, {'name': 'command', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'value', 'len': None}]}, '0513': {'name': event.ATT_WriteRsp, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}]}, '051b': {'name': event.ATT_HandleValueNotification, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'values', 'len': None}]}, '051d': {'name': event.ATT_HandleValueIndication, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'handle', 'len': 2}, {'name': 'values', 'len': None}]}, '051e': {'name': event.ATT_HandleValueConfirmation, 'structure': [{'name': 'conn_handle', 'len': 2}]}, '0580': {'name': event.GATT_ClientCharCfgUpdated, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'pdu_len', 'len': 1}, {'name': 'attr_handle', 'len': 2}, {'name': 'value', 'len': 1}]}, '0600': {'name': event.GAP_DeviceInitDone, 'structure': [{'name': 'dev_addr', 'len': 6}, {'name': 'data_pkt_len', 'len': 2}, {'name': 'num_data_pkts', 'len': 1}, {'name': 'irk', 'len': 16}, {'name': 'csrk', 'len': 16}]}, '0601': {'name': event.GAP_DeviceDiscoveryDone, 'structure': [{'name': 'num_devs', 'len': 1}, {'name': 'devices', 'len': None}], 'parsing': [('devices', lambda ble, original: ble._parse_devices(original['devices']))]}, '0602': {'name': event.GAP_AdvertDataUpdateDone, 'structure': [{'name': 'ad_type', 'len': 1}]}, '0603': {'name': event.GAP_MakeDiscoverableDone, 'structure': []}, '0604': {'name': event.GAP_EndDiscoverableDone, 'structure': []}, '0605': {'name': event.GAP_LinkEstablished, 'structure': [{'name': 'dev_addr_type', 'len': 1}, {'name': 'dev_addr', 'len': 6}, {'name': 'conn_handle', 'len': 2}, {'name': 'conn_interval', 'len': 2}, {'name': 'conn_latency', 'len': 2}, {'name': 'conn_timeout', 'len': 2}, {'name': 'clock_accuracy', 'len': 1}]}, '0606': {'name': event.GAP_LinkTerminated, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'value', 'len': None}]}, '0607': {'name': event.GAP_LinkParamUpdate, 'structure': [{'name': 'conn_handle', 'len': 2}, {'name': 'conn_interval', 'len': 2}, {'name': 'conn_latency', 'len': 2}, {'name': 'conn_timeout', 'len': 2}]}, '060d': {'name': event.GAP_DeviceInformation, 'structure': [{'name': 'event_type', 'len': 1}, {'name': 'addr_type', 'len': 1}, {'name': 'addr', 'len': 6}, {'name': 'rssi', 'len': 1}, {'name': 'data_len', 'len': 1}, {'name': 'data_field', 'len': None}]}, '067f': {'name': event.GAP_HCI_ExtensionCommandStatus, 'structure': [{'name': 'op_code', 'len': 2}, {'name': 'data_len', 'len': 1}, {'name': 'param_value', 'len': None}], 'parsing': [('op_code', lambda ble, original: ble._parse_opcodes(original['op_code']))]}} |
# Time - O (N) | Space O(N)
def tournamentWinner(competitions, results):
points = {}
for comp in range(len(competitions)):
if results[comp] == 1:
if competitions[comp][0] not in points:
points[competitions[comp][0]] = 3
else:
points[competitions[comp][0]] = points[competitions[comp][0]] + 3
else:
if competitions[comp][1] not in points:
points[competitions[comp][1]] = 3
else:
points[competitions[comp][1]] = points[competitions[comp][1]] + 3
winner = ""
maxPoints = -1
for key in points:
if points[key] > maxPoints:
winner = key
maxPoints = points[key]
return winner | def tournament_winner(competitions, results):
points = {}
for comp in range(len(competitions)):
if results[comp] == 1:
if competitions[comp][0] not in points:
points[competitions[comp][0]] = 3
else:
points[competitions[comp][0]] = points[competitions[comp][0]] + 3
elif competitions[comp][1] not in points:
points[competitions[comp][1]] = 3
else:
points[competitions[comp][1]] = points[competitions[comp][1]] + 3
winner = ''
max_points = -1
for key in points:
if points[key] > maxPoints:
winner = key
max_points = points[key]
return winner |
# Game Properties
WIDTH = 600
HEIGHT = 600
FPS = 30
# Game Colours
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0) | width = 600
height = 600
fps = 30
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0) |
class MailException(Exception):
pass
| class Mailexception(Exception):
pass |
# def alias(alias_var):
#
# @property
# def func(cls):
# return getattr(cls, alias_var)
#
# return func
# we get bonus 1 for free!
# def alias(alias_var, write=False):
#
# def getter(cls):
# return getattr(cls, alias_var)
#
# def setter(cls, value):
# if write is True:
# setattr(cls, alias_var, value)
# else:
# raise AttributeError("can't set attribute")
#
# return property(getter, setter)
class Alias:
def __init__(self, alias_var, write=False):
self.alias_var, self.write = alias_var, write
def __get__(self, instance, owner):
if instance is None:
return getattr(owner, self.alias_var)
else:
return getattr(instance, self.alias_var)
def __set__(self, instance, value):
if self.write is True:
setattr(instance, self.alias_var, value)
else:
raise AttributeError("can't set attribute")
alias = Alias
| class Alias:
def __init__(self, alias_var, write=False):
(self.alias_var, self.write) = (alias_var, write)
def __get__(self, instance, owner):
if instance is None:
return getattr(owner, self.alias_var)
else:
return getattr(instance, self.alias_var)
def __set__(self, instance, value):
if self.write is True:
setattr(instance, self.alias_var, value)
else:
raise attribute_error("can't set attribute")
alias = Alias |
products = [
{
'_id': "1",
'name': "Airpods Wireless Bluetooth Headphones",
'image': "/images/airpods.jpg",
'description':
"Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working",
'brand': "Apple",
'category': "Electronics",
'price': 89.99,
'countInStock': 10,
'rating': 4.5,
'numReviews': 12,
},
{
'_id': "2",
'name': "iPhone 11 Pro 256GB Memory",
'image': "/images/phone.jpg",
'description':
"Introducing the iPhone 11 Pro. A transformative triple-camera system that adds tons of capability without complexity. An unprecedented leap in battery life",
'brand': "Apple",
'category': "Electronics",
'price': 599.99,
'countInStock': 7,
'rating': 4.0,
'numReviews': 8,
},
{
'_id': "3",
'name': "Cannon EOS 80D DSLR Camera",
'image': "/images/camera.jpg",
'description':
"Characterized by versatile imaging specs, the Canon EOS 80D further clarifies itself using a pair of robust focusing systems and an intuitive design",
'brand': "Cannon",
'category': "Electronics",
'price': 929.99,
'countInStock': 5,
'rating': 3,
'numReviews': 12,
},
{
'_id': "4",
'name': "Sony Playstation 4 Pro White Version",
'image': "/images/playstation.jpg",
'description':
"The ultimate home entertainment center starts with PlayStation. Whether you are into gaming, HD movies, television, music",
'brand': "Sony",
'category': "Electronics",
'price': 399.99,
'countInStock': 11,
'rating': 5,
'numReviews': 12,
},
{
'_id': "5",
'name': "Logitech G-Series Gaming Mouse",
'image': "/images/mouse.jpg",
'description':
"Get a better handle on your games with this Logitech LIGHTSYNC gaming mouse. The six programmable buttons allow customization for a smooth playing experience",
'brand': "Logitech",
'category': "Electronics",
'price': 49.99,
'countInStock': 7,
'rating': 3.5,
'numReviews': 10,
},
{
'_id': "6",
'name': "Amazon Echo Dot 3rd Generation",
'image': "/images/alexa.jpg",
'description':
"Meet Echo Dot - Our most popular smart speaker with a fabric design. It is our most compact smart speaker that fits perfectly into small space",
'brand': "Amazon",
'category': "Electronics",
'price': 29.99,
'countInStock': 0,
'rating': 4,
'numReviews': 12,
},
] | products = [{'_id': '1', 'name': 'Airpods Wireless Bluetooth Headphones', 'image': '/images/airpods.jpg', 'description': 'Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working', 'brand': 'Apple', 'category': 'Electronics', 'price': 89.99, 'countInStock': 10, 'rating': 4.5, 'numReviews': 12}, {'_id': '2', 'name': 'iPhone 11 Pro 256GB Memory', 'image': '/images/phone.jpg', 'description': 'Introducing the iPhone 11 Pro. A transformative triple-camera system that adds tons of capability without complexity. An unprecedented leap in battery life', 'brand': 'Apple', 'category': 'Electronics', 'price': 599.99, 'countInStock': 7, 'rating': 4.0, 'numReviews': 8}, {'_id': '3', 'name': 'Cannon EOS 80D DSLR Camera', 'image': '/images/camera.jpg', 'description': 'Characterized by versatile imaging specs, the Canon EOS 80D further clarifies itself using a pair of robust focusing systems and an intuitive design', 'brand': 'Cannon', 'category': 'Electronics', 'price': 929.99, 'countInStock': 5, 'rating': 3, 'numReviews': 12}, {'_id': '4', 'name': 'Sony Playstation 4 Pro White Version', 'image': '/images/playstation.jpg', 'description': 'The ultimate home entertainment center starts with PlayStation. Whether you are into gaming, HD movies, television, music', 'brand': 'Sony', 'category': 'Electronics', 'price': 399.99, 'countInStock': 11, 'rating': 5, 'numReviews': 12}, {'_id': '5', 'name': 'Logitech G-Series Gaming Mouse', 'image': '/images/mouse.jpg', 'description': 'Get a better handle on your games with this Logitech LIGHTSYNC gaming mouse. The six programmable buttons allow customization for a smooth playing experience', 'brand': 'Logitech', 'category': 'Electronics', 'price': 49.99, 'countInStock': 7, 'rating': 3.5, 'numReviews': 10}, {'_id': '6', 'name': 'Amazon Echo Dot 3rd Generation', 'image': '/images/alexa.jpg', 'description': 'Meet Echo Dot - Our most popular smart speaker with a fabric design. It is our most compact smart speaker that fits perfectly into small space', 'brand': 'Amazon', 'category': 'Electronics', 'price': 29.99, 'countInStock': 0, 'rating': 4, 'numReviews': 12}] |
_base_ = [
'../_base_/models/stylegan/stylegan3_base.py',
'../_base_/datasets/unconditional_imgs_flip_lanczos_resize_256x256.py',
'../_base_/default_runtime.py'
]
synthesis_cfg = {
'type': 'SynthesisNetwork',
'channel_base': 16384,
'channel_max': 512,
'magnitude_ema_beta': 0.999
}
r1_gamma = 2. # set by user
d_reg_interval = 16
model = dict(
type='StaticUnconditionalGAN',
generator=dict(out_size=256, img_channels=3, synthesis_cfg=synthesis_cfg),
discriminator=dict(in_size=256, channel_multiplier=1),
gan_loss=dict(type='GANLoss', gan_type='wgan-logistic-ns'),
disc_auxiliary_loss=dict(loss_weight=r1_gamma / 2.0 * d_reg_interval))
imgs_root = 'data/ffhq/images'
data = dict(
samples_per_gpu=4,
train=dict(dataset=dict(imgs_root=imgs_root)),
val=dict(imgs_root=imgs_root))
ema_half_life = 10. # G_smoothing_kimg
custom_hooks = [
dict(
type='VisualizeUnconditionalSamples',
output_dir='training_samples',
interval=5000),
dict(
type='ExponentialMovingAverageHook',
module_keys=('generator_ema', ),
interp_mode='lerp',
interval=1,
start_iter=0,
momentum_policy='rampup',
momentum_cfg=dict(
ema_kimg=10, ema_rampup=0.05, batch_size=32, eps=1e-8),
priority='VERY_HIGH')
]
inception_pkl = 'work_dirs/inception_pkl/ffhq-lanczos-256x256.pkl'
metrics = dict(
fid50k=dict(
type='FID',
num_images=50000,
inception_pkl=inception_pkl,
inception_args=dict(type='StyleGAN'),
bgr2rgb=True))
inception_path = None
evaluation = dict(
type='GenerativeEvalHook',
interval=10000,
metrics=dict(
type='FID',
num_images=50000,
inception_pkl=inception_pkl,
inception_args=dict(type='StyleGAN', inception_path=inception_path),
bgr2rgb=True),
sample_kwargs=dict(sample_model='ema'))
checkpoint_config = dict(interval=10000, by_epoch=False, max_keep_ckpts=30)
lr_config = None
total_iters = 800002
| _base_ = ['../_base_/models/stylegan/stylegan3_base.py', '../_base_/datasets/unconditional_imgs_flip_lanczos_resize_256x256.py', '../_base_/default_runtime.py']
synthesis_cfg = {'type': 'SynthesisNetwork', 'channel_base': 16384, 'channel_max': 512, 'magnitude_ema_beta': 0.999}
r1_gamma = 2.0
d_reg_interval = 16
model = dict(type='StaticUnconditionalGAN', generator=dict(out_size=256, img_channels=3, synthesis_cfg=synthesis_cfg), discriminator=dict(in_size=256, channel_multiplier=1), gan_loss=dict(type='GANLoss', gan_type='wgan-logistic-ns'), disc_auxiliary_loss=dict(loss_weight=r1_gamma / 2.0 * d_reg_interval))
imgs_root = 'data/ffhq/images'
data = dict(samples_per_gpu=4, train=dict(dataset=dict(imgs_root=imgs_root)), val=dict(imgs_root=imgs_root))
ema_half_life = 10.0
custom_hooks = [dict(type='VisualizeUnconditionalSamples', output_dir='training_samples', interval=5000), dict(type='ExponentialMovingAverageHook', module_keys=('generator_ema',), interp_mode='lerp', interval=1, start_iter=0, momentum_policy='rampup', momentum_cfg=dict(ema_kimg=10, ema_rampup=0.05, batch_size=32, eps=1e-08), priority='VERY_HIGH')]
inception_pkl = 'work_dirs/inception_pkl/ffhq-lanczos-256x256.pkl'
metrics = dict(fid50k=dict(type='FID', num_images=50000, inception_pkl=inception_pkl, inception_args=dict(type='StyleGAN'), bgr2rgb=True))
inception_path = None
evaluation = dict(type='GenerativeEvalHook', interval=10000, metrics=dict(type='FID', num_images=50000, inception_pkl=inception_pkl, inception_args=dict(type='StyleGAN', inception_path=inception_path), bgr2rgb=True), sample_kwargs=dict(sample_model='ema'))
checkpoint_config = dict(interval=10000, by_epoch=False, max_keep_ckpts=30)
lr_config = None
total_iters = 800002 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
if not root:
return 0
if root.val % 2 == 0:
if root.left is not None:
root.left.has_even_parent = True
if root.right is not None:
root.right.has_even_parent = True
if hasattr(root, "has_even_parent"):
if root.left is not None:
root.left.has_even_grand_parent = True
if root.right is not None:
root.right.has_even_grand_parent = True
value = 0
if hasattr(root, "has_even_grand_parent"):
value = root.val
return value + self.sumEvenGrandparent(root.left) + self.sumEvenGrandparent(root.right)
| class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sum_even_grandparent(self, root: TreeNode) -> int:
if not root:
return 0
if root.val % 2 == 0:
if root.left is not None:
root.left.has_even_parent = True
if root.right is not None:
root.right.has_even_parent = True
if hasattr(root, 'has_even_parent'):
if root.left is not None:
root.left.has_even_grand_parent = True
if root.right is not None:
root.right.has_even_grand_parent = True
value = 0
if hasattr(root, 'has_even_grand_parent'):
value = root.val
return value + self.sumEvenGrandparent(root.left) + self.sumEvenGrandparent(root.right) |
#
# Constants, shared by all scenes
#
# Scene keys (any unique values):
SCENE_A = 'scene A'
SCENE_B = 'scene B'
SCENE_C = 'scene C'
# Message ID's (any unique values):
SEND_MESSAGE = 'send message'
GET_DATA = 'get data'
WHITE = (255, 255, 255)
GRAYA = (50, 50, 50)
GRAYB = (100, 100, 100)
GRAYC = (150, 150, 150)
| scene_a = 'scene A'
scene_b = 'scene B'
scene_c = 'scene C'
send_message = 'send message'
get_data = 'get data'
white = (255, 255, 255)
graya = (50, 50, 50)
grayb = (100, 100, 100)
grayc = (150, 150, 150) |
# Time: O(n * 2^n)
# Space: O(2^n)
class Solution(object):
# @return a string
def countAndSay(self, n):
seq = "1"
for i in xrange(n - 1):
seq = self.getNext(seq)
return seq
def getNext(self, seq):
i, next_seq = 0, ""
while i < len(seq):
cnt = 1
while i < len(seq) - 1 and seq[i] == seq[i + 1]:
cnt += 1
i += 1
next_seq += str(cnt) + seq[i]
i += 1
return next_seq
| class Solution(object):
def count_and_say(self, n):
seq = '1'
for i in xrange(n - 1):
seq = self.getNext(seq)
return seq
def get_next(self, seq):
(i, next_seq) = (0, '')
while i < len(seq):
cnt = 1
while i < len(seq) - 1 and seq[i] == seq[i + 1]:
cnt += 1
i += 1
next_seq += str(cnt) + seq[i]
i += 1
return next_seq |
def checkWalletState(cli, totalIds, isAbbr, isCrypto):
if cli._activeWallet:
assert len(cli._activeWallet.idsToSigners) == totalIds
if totalIds > 0:
activeSigner = cli._activeWallet.idsToSigners[
cli._activeWallet.defaultId]
if isAbbr:
assert activeSigner.verkey.startswith("~"), \
"verkey {} doesn't look like abbreviated verkey".\
format(activeSigner.verkey)
assert cli._activeWallet.defaultId != activeSigner.verkey, \
"new DID should not be equal to abbreviated verkey"
if isCrypto:
assert not activeSigner.verkey.startswith("~"), \
"verkey {} doesn't look like cryptographic verkey". \
format(activeSigner.verkey)
assert cli._activeWallet.defaultId == activeSigner.verkey, \
"new DID should be equal to verkey"
def getTotalIds(cli):
if cli._activeWallet:
return len(cli._activeWallet.idsToSigners)
else:
return 0
def testNewIdWithIncorrectSeed(be, do, aliceCLI):
totalIds = getTotalIds(aliceCLI)
be(aliceCLI)
# Seed not of length 32 or 64
do("new DID with seed aaaaaaaaaaa",
expect=["Seed needs to be 32 or 64 characters (if hex) long"])
checkWalletState(aliceCLI, totalIds=totalIds, isAbbr=False, isCrypto=False)
# Seed of length 64 but not hex
do("new DID with seed "
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
expect=["Seed needs to be 32 or 64 characters (if hex) long"])
checkWalletState(aliceCLI, totalIds=totalIds, isAbbr=False,
isCrypto=False)
# Seed of length 64 and hex
do("new DID with seed "
"2af3d062450c942be50ee766ce2571a6c75c0aca0de322293e7e9f116959c9c3",
expect=["Current DID set to"])
checkWalletState(aliceCLI, totalIds=totalIds + 1, isAbbr=False,
isCrypto=False)
def testNewIdIsNotInvalidCommand(be, do, aliceCLI):
totalIds = getTotalIds(aliceCLI)
be(aliceCLI)
do("new DID", not_expect=["Invalid command"])
checkWalletState(aliceCLI, totalIds=totalIds +
1, isAbbr=False, isCrypto=False)
def testNewId(be, do, aliceCLI):
totalIds = getTotalIds(aliceCLI)
be(aliceCLI)
do("new DID",
expect=["Current DID set to"])
checkWalletState(aliceCLI, totalIds=totalIds +
1, isAbbr=False, isCrypto=False)
| def check_wallet_state(cli, totalIds, isAbbr, isCrypto):
if cli._activeWallet:
assert len(cli._activeWallet.idsToSigners) == totalIds
if totalIds > 0:
active_signer = cli._activeWallet.idsToSigners[cli._activeWallet.defaultId]
if isAbbr:
assert activeSigner.verkey.startswith('~'), "verkey {} doesn't look like abbreviated verkey".format(activeSigner.verkey)
assert cli._activeWallet.defaultId != activeSigner.verkey, 'new DID should not be equal to abbreviated verkey'
if isCrypto:
assert not activeSigner.verkey.startswith('~'), "verkey {} doesn't look like cryptographic verkey".format(activeSigner.verkey)
assert cli._activeWallet.defaultId == activeSigner.verkey, 'new DID should be equal to verkey'
def get_total_ids(cli):
if cli._activeWallet:
return len(cli._activeWallet.idsToSigners)
else:
return 0
def test_new_id_with_incorrect_seed(be, do, aliceCLI):
total_ids = get_total_ids(aliceCLI)
be(aliceCLI)
do('new DID with seed aaaaaaaaaaa', expect=['Seed needs to be 32 or 64 characters (if hex) long'])
check_wallet_state(aliceCLI, totalIds=totalIds, isAbbr=False, isCrypto=False)
do('new DID with seed xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy', expect=['Seed needs to be 32 or 64 characters (if hex) long'])
check_wallet_state(aliceCLI, totalIds=totalIds, isAbbr=False, isCrypto=False)
do('new DID with seed 2af3d062450c942be50ee766ce2571a6c75c0aca0de322293e7e9f116959c9c3', expect=['Current DID set to'])
check_wallet_state(aliceCLI, totalIds=totalIds + 1, isAbbr=False, isCrypto=False)
def test_new_id_is_not_invalid_command(be, do, aliceCLI):
total_ids = get_total_ids(aliceCLI)
be(aliceCLI)
do('new DID', not_expect=['Invalid command'])
check_wallet_state(aliceCLI, totalIds=totalIds + 1, isAbbr=False, isCrypto=False)
def test_new_id(be, do, aliceCLI):
total_ids = get_total_ids(aliceCLI)
be(aliceCLI)
do('new DID', expect=['Current DID set to'])
check_wallet_state(aliceCLI, totalIds=totalIds + 1, isAbbr=False, isCrypto=False) |
expected_output = {
"instance": {
"0": {
"level": {
"L2": {
"interfaces": {
"To-GENIE01R07-LAG-7": {
"system_id": {
"0691.58ff.79a2": {
"hold_time": 22,
"hostname": "GENIE01R07",
"ipv4_adj_sid": "Label 524213",
"ipv4_neighbor": "10.11.97.22",
"ipv6_neighbor": "::",
"l_circ_typ": "L2",
"last_restart_at": "Never",
"max_hold": 30,
"mt_enabled": "No",
"nbr_sys_typ": "L2",
"number_of_restarts": 0,
"priority": 0,
"restart_support": "Disabled",
"restart_supressed": "Disabled",
"restart_status": "Not currently being helped",
"snpa": "00:23:3e:ff:a6:27",
"state": "Up",
"topology": "Unicast",
"up_time": "58d 03:24:48",
}
}
},
"To-GENIE04XR1-LAG-4": {
"system_id": {
"0670.70ff.b258": {
"hold_time": 23,
"hostname": "GENIE04XR1",
"ipv4_adj_sid": "Label 524127",
"ipv4_neighbor": "10.11.79.245",
"ipv6_neighbor": "::",
"l_circ_typ": "L2",
"last_restart_at": "Never",
"max_hold": 30,
"mt_enabled": "No",
"nbr_sys_typ": "L2",
"number_of_restarts": 0,
"priority": 0,
"restart_support": "Disabled",
"restart_supressed": "Disabled",
"restart_status": "Not currently being helped",
"snpa": "84:26:2b:ff:e9:9e",
"state": "Up",
"topology": "Unicast",
"up_time": "36d 23:21:57",
}
}
},
"To-GENIE03R07-LAG-9": {
"system_id": {
"0691.58ff.79aa": {
"hold_time": 22,
"hostname": "GENIE03R07",
"ipv4_adj_sid": "Label 524214",
"ipv4_neighbor": "10.11.79.242",
"ipv6_neighbor": "::",
"l_circ_typ": "L2",
"last_restart_at": "Never",
"max_hold": 30,
"mt_enabled": "No",
"nbr_sys_typ": "L2",
"number_of_restarts": 0,
"priority": 0,
"restart_support": "Disabled",
"restart_supressed": "Disabled",
"restart_status": "Not currently being helped",
"snpa": "00:23:3e:ff:bc:27",
"state": "Up",
"topology": "Unicast",
"up_time": "58d 03:24:48",
}
}
},
}
}
}
},
"1": {
"level": {
"L2": {
"interfaces": {
"To-GENIE01R07-LAG-7": {
"system_id": {
"0691.58ff.79a2": {
"hold_time": 22,
"hostname": "GENIE01R07",
"ipv4_adj_sid": "Label 524213",
"ipv4_neighbor": "10.11.97.22",
"ipv6_neighbor": "::",
"l_circ_typ": "L2",
"last_restart_at": "Never",
"max_hold": 30,
"mt_enabled": "No",
"nbr_sys_typ": "L2",
"number_of_restarts": 0,
"priority": 0,
"restart_support": "Disabled",
"restart_supressed": "Disabled",
"restart_status": "Not currently being helped",
"snpa": "00:23:3e:ff:a6:27",
"state": "Up",
"topology": "Unicast",
"up_time": "58d 03:24:48",
}
}
}
}
}
}
},
}
}
| expected_output = {'instance': {'0': {'level': {'L2': {'interfaces': {'To-GENIE01R07-LAG-7': {'system_id': {'0691.58ff.79a2': {'hold_time': 22, 'hostname': 'GENIE01R07', 'ipv4_adj_sid': 'Label 524213', 'ipv4_neighbor': '10.11.97.22', 'ipv6_neighbor': '::', 'l_circ_typ': 'L2', 'last_restart_at': 'Never', 'max_hold': 30, 'mt_enabled': 'No', 'nbr_sys_typ': 'L2', 'number_of_restarts': 0, 'priority': 0, 'restart_support': 'Disabled', 'restart_supressed': 'Disabled', 'restart_status': 'Not currently being helped', 'snpa': '00:23:3e:ff:a6:27', 'state': 'Up', 'topology': 'Unicast', 'up_time': '58d 03:24:48'}}}, 'To-GENIE04XR1-LAG-4': {'system_id': {'0670.70ff.b258': {'hold_time': 23, 'hostname': 'GENIE04XR1', 'ipv4_adj_sid': 'Label 524127', 'ipv4_neighbor': '10.11.79.245', 'ipv6_neighbor': '::', 'l_circ_typ': 'L2', 'last_restart_at': 'Never', 'max_hold': 30, 'mt_enabled': 'No', 'nbr_sys_typ': 'L2', 'number_of_restarts': 0, 'priority': 0, 'restart_support': 'Disabled', 'restart_supressed': 'Disabled', 'restart_status': 'Not currently being helped', 'snpa': '84:26:2b:ff:e9:9e', 'state': 'Up', 'topology': 'Unicast', 'up_time': '36d 23:21:57'}}}, 'To-GENIE03R07-LAG-9': {'system_id': {'0691.58ff.79aa': {'hold_time': 22, 'hostname': 'GENIE03R07', 'ipv4_adj_sid': 'Label 524214', 'ipv4_neighbor': '10.11.79.242', 'ipv6_neighbor': '::', 'l_circ_typ': 'L2', 'last_restart_at': 'Never', 'max_hold': 30, 'mt_enabled': 'No', 'nbr_sys_typ': 'L2', 'number_of_restarts': 0, 'priority': 0, 'restart_support': 'Disabled', 'restart_supressed': 'Disabled', 'restart_status': 'Not currently being helped', 'snpa': '00:23:3e:ff:bc:27', 'state': 'Up', 'topology': 'Unicast', 'up_time': '58d 03:24:48'}}}}}}}, '1': {'level': {'L2': {'interfaces': {'To-GENIE01R07-LAG-7': {'system_id': {'0691.58ff.79a2': {'hold_time': 22, 'hostname': 'GENIE01R07', 'ipv4_adj_sid': 'Label 524213', 'ipv4_neighbor': '10.11.97.22', 'ipv6_neighbor': '::', 'l_circ_typ': 'L2', 'last_restart_at': 'Never', 'max_hold': 30, 'mt_enabled': 'No', 'nbr_sys_typ': 'L2', 'number_of_restarts': 0, 'priority': 0, 'restart_support': 'Disabled', 'restart_supressed': 'Disabled', 'restart_status': 'Not currently being helped', 'snpa': '00:23:3e:ff:a6:27', 'state': 'Up', 'topology': 'Unicast', 'up_time': '58d 03:24:48'}}}}}}}}} |
def dummy(environ, start_response):
start_response('200 OK', [])
yield [b'dummy']
| def dummy(environ, start_response):
start_response('200 OK', [])
yield [b'dummy'] |
# program to convert temperature from celcius to farenheit
x = float(input("Enter the temperature in celcius: "))
f = (x * 9 / 5) + 32
print(f"Temperaturn in farenheit: {f}")
| x = float(input('Enter the temperature in celcius: '))
f = x * 9 / 5 + 32
print(f'Temperaturn in farenheit: {f}') |
# Please see __init__.py in this folder for documentation
stain_color_map = {
'hematoxylin': [0.65, 0.70, 0.29],
'eosin': [0.07, 0.99, 0.11],
'dab': [0.27, 0.57, 0.78],
'null': [0.0, 0.0, 0.0]
}
| stain_color_map = {'hematoxylin': [0.65, 0.7, 0.29], 'eosin': [0.07, 0.99, 0.11], 'dab': [0.27, 0.57, 0.78], 'null': [0.0, 0.0, 0.0]} |
class Zipper:
@staticmethod
def from_tree(tree):
return Zipper(dict(tree), [])
def __init__(self, tree, ancestors):
self.tree = tree
self.ancestors = ancestors
def value(self):
return self.tree['value']
def set_value(self, value):
self.tree['value'] = value
return self
def left(self):
if self.tree['left'] is None:
return None
return Zipper(self.tree['left'], self.ancestors + [self.tree])
def set_left(self, tree):
self.tree['left'] = tree
return self
def right(self):
if self.tree['right'] is None:
return None
return Zipper(self.tree['right'], self.ancestors + [self.tree])
def set_right(self, tree):
self.tree['right'] = tree
return self
def up(self):
return Zipper(self.ancestors[-1], self.ancestors[:-1])
def to_tree(self):
if any(self.ancestors):
return self.ancestors[0]
return self.tree
| class Zipper:
@staticmethod
def from_tree(tree):
return zipper(dict(tree), [])
def __init__(self, tree, ancestors):
self.tree = tree
self.ancestors = ancestors
def value(self):
return self.tree['value']
def set_value(self, value):
self.tree['value'] = value
return self
def left(self):
if self.tree['left'] is None:
return None
return zipper(self.tree['left'], self.ancestors + [self.tree])
def set_left(self, tree):
self.tree['left'] = tree
return self
def right(self):
if self.tree['right'] is None:
return None
return zipper(self.tree['right'], self.ancestors + [self.tree])
def set_right(self, tree):
self.tree['right'] = tree
return self
def up(self):
return zipper(self.ancestors[-1], self.ancestors[:-1])
def to_tree(self):
if any(self.ancestors):
return self.ancestors[0]
return self.tree |
def randomData(val):
data = []
random = [1, 4, 6, 10, 13]
for i in range(len(val)):
if i in random:
data.append(val[i])
return data
| def random_data(val):
data = []
random = [1, 4, 6, 10, 13]
for i in range(len(val)):
if i in random:
data.append(val[i])
return data |
class Solution:
def findDuplicate(self, nums):
n = len(nums)
temp = [0] * n
for i in nums:
temp[i] += 1
if temp[i] > 1:
return i
b = Solution()
print(b.findDuplicate([1,3,4,2,2])) | class Solution:
def find_duplicate(self, nums):
n = len(nums)
temp = [0] * n
for i in nums:
temp[i] += 1
if temp[i] > 1:
return i
b = solution()
print(b.findDuplicate([1, 3, 4, 2, 2])) |
n,l,k=map(int,input().split())
oo=[]
for i in range(n):
x,y=map(int,input().split())
t=0
if l>=x: t=100
if l>=y: t+=40
if t>0: oo.append(t)
oo.sort(reverse=True)
print(sum(oo[:k])) | (n, l, k) = map(int, input().split())
oo = []
for i in range(n):
(x, y) = map(int, input().split())
t = 0
if l >= x:
t = 100
if l >= y:
t += 40
if t > 0:
oo.append(t)
oo.sort(reverse=True)
print(sum(oo[:k])) |
def findClosestValueInBst(tree, target):
currentNode = tree
closest = tree.value
while currentNode is not None:
if abs(target-currentNode.value) < abs(target-closest):
closest = currentNode.value
if target<currentNode.value:
currentNode = currentNode.left
elif target>currentNode.value:
currentNode = currentNode.right
else:
break
return closest
# This is the class of the input tree. Do not edit.
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
| def find_closest_value_in_bst(tree, target):
current_node = tree
closest = tree.value
while currentNode is not None:
if abs(target - currentNode.value) < abs(target - closest):
closest = currentNode.value
if target < currentNode.value:
current_node = currentNode.left
elif target > currentNode.value:
current_node = currentNode.right
else:
break
return closest
class Bst:
def __init__(self, value):
self.value = value
self.left = None
self.right = None |
class CircularBufferAdaptor:
def __init__(self, l: list):
self._buffer = l
self._buffer_len = len(self._buffer)
def __getitem__(self, index: int):
return self._buffer[self._get_index(index)]
def _get_index(self, index: int):
return index % self._buffer_len
def from_offset(self, offset: int):
for i in range(self._buffer_len):
yield self[i + offset]
| class Circularbufferadaptor:
def __init__(self, l: list):
self._buffer = l
self._buffer_len = len(self._buffer)
def __getitem__(self, index: int):
return self._buffer[self._get_index(index)]
def _get_index(self, index: int):
return index % self._buffer_len
def from_offset(self, offset: int):
for i in range(self._buffer_len):
yield self[i + offset] |
_base_ = [
'../_base_/models/retinanet_r50_fpn_icdar2021.py',
'../_base_/datasets/icdar2021_detection.py',
'../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
# data = dict(
# samples_per_gpu=1,
# workers_per_gpu=2)
| _base_ = ['../_base_/models/retinanet_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py']
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) |
FORMAT_VERSION = 131
NEW_FLOAT_EXT = 70 # [Float64:IEEE float]
BIT_BINARY_EXT = 77 # [UInt32:Len, UInt8:Bits, Len:Data]
SMALL_INTEGER_EXT = 97 # [UInt8:Int]
INTEGER_EXT = 98 # [Int32:Int]
FLOAT_EXT = 99 # [31:Float String] Float in string format (formatted "%.20e", sscanf "%lf"). Superseded by NEW_FLOAT_EXT
ATOM_EXT = 100 # 100 [UInt16:Len, Len:AtomName] max Len is 255
REFERENCE_EXT = 101 # 101 [atom:Node, UInt32:ID, UInt8:Creation]
PORT_EXT = 102 # [atom:Node, UInt32:ID, UInt8:Creation]
PID_EXT = 103 # [atom:Node, UInt32:ID, UInt32:Serial, UInt8:Creation]
SMALL_TUPLE_EXT = 104 # [UInt8:Arity, N:Elements]
LARGE_TUPLE_EXT = 105 # [UInt32:Arity, N:Elements]
NIL_EXT = 106 # empty list
STRING_EXT = 107 # [UInt32:Len, Len:Characters]
LIST_EXT = 108 # [UInt32:Len, Elements, Tail]
BINARY_EXT = 109 # [UInt32:Len, Len:Data]
SMALL_BIG_EXT = 110 # [UInt8:n, UInt8:Sign, n:nums]
LARGE_BIG_EXT = 111 # [UInt32:n, UInt8:Sign, n:nums]
NEW_FUN_EXT = 112 # [UInt32:Size, UInt8:Arity, 16*Uint6-MD5:Uniq, UInt32:Index, UInt32:NumFree, atom:Module, int:OldIndex, int:OldUniq, pid:Pid, NunFree*ext:FreeVars]
EXPORT_EXT = 113 # [atom:Module, atom:Function, smallint:Arity]
NEW_REFERENCE_EXT = 114 # [UInt16:Len, atom:Node, UInt8:Creation, Len*UInt32:ID]
SMALL_ATOM_EXT = 115 # [UInt8:Len, Len:AtomName]
FUN_EXT = 117 # [UInt4:NumFree, pid:Pid, atom:Module, int:Index, int:Uniq, NumFree*ext:FreeVars]
COMPRESSED = 80 # [UInt4:UncompressedSize, N:ZlibCompressedData]
MAP_EXT = 116 # [Uint64:Arity,N:K-V]
ATOM_UTF8_EXT = 118
SMALL_ATOM_UTF8_EXT = 119
| format_version = 131
new_float_ext = 70
bit_binary_ext = 77
small_integer_ext = 97
integer_ext = 98
float_ext = 99
atom_ext = 100
reference_ext = 101
port_ext = 102
pid_ext = 103
small_tuple_ext = 104
large_tuple_ext = 105
nil_ext = 106
string_ext = 107
list_ext = 108
binary_ext = 109
small_big_ext = 110
large_big_ext = 111
new_fun_ext = 112
export_ext = 113
new_reference_ext = 114
small_atom_ext = 115
fun_ext = 117
compressed = 80
map_ext = 116
atom_utf8_ext = 118
small_atom_utf8_ext = 119 |
DEFAULT_FORMAT = {
'users': {
'meta': {
'last_id': '0'
}
},
'rooms': {
'meta': {
'last_id': '0'
}
},
'messages': {
'meta': {
'last_id': '0'
}
}
}
| default_format = {'users': {'meta': {'last_id': '0'}}, 'rooms': {'meta': {'last_id': '0'}}, 'messages': {'meta': {'last_id': '0'}}} |
DEBUG = True
SERVER_NAME = 'localhost:8000'
SECRET_KEY = 'insecurekeyfordev'
# SQLAlchemy.
db_uri = 'postgresql://flaskwallet:walletpassword@postgres:5432/flaskwallet'
SQLALCHEMY_DATABASE_URI = db_uri
SQLALCHEMY_TRACK_MODIFICATIONS = False
| debug = True
server_name = 'localhost:8000'
secret_key = 'insecurekeyfordev'
db_uri = 'postgresql://flaskwallet:walletpassword@postgres:5432/flaskwallet'
sqlalchemy_database_uri = db_uri
sqlalchemy_track_modifications = False |
protocol_version = 1
last_refresh_time = 0
cert = None
data_path = None
config = None
proxy = None
session = None
socks5_server = None
last_api_error = ""
quota_list = {}
quota = 0
server_host = ""
server_port = 0
balance = 0
| protocol_version = 1
last_refresh_time = 0
cert = None
data_path = None
config = None
proxy = None
session = None
socks5_server = None
last_api_error = ''
quota_list = {}
quota = 0
server_host = ''
server_port = 0
balance = 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.