hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
0c79a3fc909266657859ec6f1fef5e42cc8f960d
742
py
Python
blender/2.79/scripts/presets/interaction/blender.py
uzairakbar/bpy2.79
3a3e0004ac6783c4e4b89d939e4432de99026a85
[ "MIT" ]
2
2019-11-27T09:05:42.000Z
2020-02-20T01:25:23.000Z
blender/2.79/scripts/presets/interaction/blender.py
uzairakbar/bpy2.79
3a3e0004ac6783c4e4b89d939e4432de99026a85
[ "MIT" ]
null
null
null
blender/2.79/scripts/presets/interaction/blender.py
uzairakbar/bpy2.79
3a3e0004ac6783c4e4b89d939e4432de99026a85
[ "MIT" ]
4
2020-02-19T20:02:26.000Z
2022-02-11T18:47:56.000Z
# Configuration Blender import bpy bpy.context.user_preferences.view.use_mouse_depth_cursor = False bpy.context.user_preferences.view.use_mouse_depth_navigate = False bpy.context.user_preferences.view.use_zoom_to_mouse = False bpy.context.user_preferences.view.use_rotate_around_active = False bpy.context.user_preferences.edit.use_drag_immediately = False bpy.context.user_preferences.edit.use_insertkey_xyz_to_rgb = False bpy.context.user_preferences.inputs.select_mouse = 'RIGHT' bpy.context.user_preferences.inputs.view_zoom_method = 'DOLLY' bpy.context.user_preferences.inputs.view_zoom_axis = 'VERTICAL' bpy.context.user_preferences.inputs.view_rotate_method = 'TURNTABLE' bpy.context.user_preferences.inputs.invert_mouse_zoom = False
49.466667
68
0.861186
108
742
5.564815
0.314815
0.183028
0.25624
0.457571
0.693844
0.582363
0.524126
0.139767
0
0
0
0
0.052561
742
14
69
53
0.854908
0.028302
0
0
0
0
0.037552
0
0
0
0
0
0
1
0
true
0
0.083333
0
0.083333
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
0c79c37d225ec1c6d80e48b67b03336578f10162
334
py
Python
client/ui/roundrect.py
rrsilaya/spaceteam
eca853d82f14d1d5f5f892977dfb35d20da40d0b
[ "MIT" ]
null
null
null
client/ui/roundrect.py
rrsilaya/spaceteam
eca853d82f14d1d5f5f892977dfb35d20da40d0b
[ "MIT" ]
null
null
null
client/ui/roundrect.py
rrsilaya/spaceteam
eca853d82f14d1d5f5f892977dfb35d20da40d0b
[ "MIT" ]
null
null
null
def create_rounded_rectangle(canvas, x1, y1, x2, y2, r=25, **kwargs): points = (x1+r, y1, x1+r, y1, x2-r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y1+r, x2, y2-r, x2, y2-r, x2, y2, x2-r, y2, x2-r, y2, x1+r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y2-r, x1, y1+r, x1, y1+r, x1, y1) return canvas.create_polygon(points, kwargs, smooth=True)
83.5
203
0.598802
77
334
2.558442
0.220779
0.101523
0.076142
0.060914
0.304569
0.304569
0
0
0
0
0
0.166667
0.173653
334
3
204
111.333333
0.547101
0
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0cb8965b375d02d5a557489ce15ad2ffa88f827d
1,009
py
Python
build/env/lib/python2.7/site-packages/ipython-0.10-py2.7.egg/IPython/platutils_dummy.py
lumanjiao/XLS_BigData
2c4c37872b8636df1c8b0e005bc12a635a753c7a
[ "Apache-2.0" ]
11
2019-03-20T07:38:35.000Z
2021-06-18T09:42:46.000Z
build/env/lib/python2.6/site-packages/ipython-0.10-py2.6.egg/IPython/platutils_dummy.py
lockhart39/HueQualityAndIngestionApp
c75e55a43a8bdeb7aa0f5bf2101ec72b01dcac1c
[ "Apache-2.0" ]
null
null
null
build/env/lib/python2.6/site-packages/ipython-0.10-py2.6.egg/IPython/platutils_dummy.py
lockhart39/HueQualityAndIngestionApp
c75e55a43a8bdeb7aa0f5bf2101ec72b01dcac1c
[ "Apache-2.0" ]
5
2019-06-29T03:13:02.000Z
2020-04-23T04:47:11.000Z
# -*- coding: utf-8 -*- """ Platform specific utility functions, dummy version This has empty implementation of the platutils functions, used for unsupported operating systems. Authors ------- - Ville Vainio <vivainio@gmail.com> """ #***************************************************************************** # Copyright (C) 2008-2009 The IPython Development Team # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** # This variable is part of the expected API of the module: ignore_termtitle = True def set_term_title(*args,**kw): """Dummy no-op.""" pass def find_cmd(cmd): """Find the full path to a command using which.""" return os.popen('which %s' % cmd).read().strip() def get_long_path_name(path): """Dummy no-op.""" return path
29.676471
78
0.583746
123
1,009
4.731707
0.707317
0.034364
0.030928
0
0
0
0
0
0
0
0
0.020118
0.162537
1,009
33
79
30.575758
0.668639
0.758176
0
0
0
0
0.037559
0
0
0
0
0
0
1
0.428571
false
0.142857
0
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
3
0cbc457024d9857d554e3acd309760654010fb26
14,959
py
Python
app/api/rules/rules.py
ligross/attr_lingvo
5331c77264b1e624a6f8833e52ffa43e48789eb4
[ "MIT" ]
null
null
null
app/api/rules/rules.py
ligross/attr_lingvo
5331c77264b1e624a6f8833e52ffa43e48789eb4
[ "MIT" ]
7
2020-07-21T01:39:18.000Z
2022-02-19T03:25:01.000Z
app/api/rules/rules.py
ligross/attr_lingvo
5331c77264b1e624a6f8833e52ffa43e48789eb4
[ "MIT" ]
1
2020-10-27T10:11:25.000Z
2020-10-27T10:11:25.000Z
import regex as re UNIFORM_ROWS = ( r'(NOUN,\s*NOUN,\s*NOUN)', r'(ADJF,\s*ADJF,\s*ADJF)', r'(ADJS,\s*ADJS,\s*ADJS)', r'(VERB,\s*VERB,\s*VERB)', r'(INFN,\s*INFN,\s*INFN)', r'((и|да и|ни|или|либо) NOUN,\s*(и|да и|ни|или|либо) NOUN,\s*(и|да и|ни|или|либо) NOUN)', r'(NOUN,\s*NOUN (да|и|либо|или|да и) NOUN)', r'(NOUN,\s*(да|и|да и|также|тоже|также и|либо|или) NOUN,\s*(да|и|да и|также|тоже|также и|либо|или) NOUN)', r'(NOUN,\s*(а|но) NOUN,\s*NOUN)', r'(NOUN,\s*NOUN,\s*(а|но) NOUN)', r'(NOUN и NOUN,\s*(а|но) NOUN)', ) SENTENCES_SPLIT_LIST = ( r'([^,]\n+\s+\n+)', r'(\n+([А-Я]{1}))' ) ADDITIONAL_ABBREVIATIONS = ( 'оф', 'производствен', *set(map(str, range(0, 100))), ) COLLATION_ROWS = ( r'((^|\s|,)если .+,\s*то .+$)', r'((^|\s|,)как,\s*так и .+$)', r'((^|\s|,)не только,\s*и .+$)', r'((^|\s|,)не только,\s*но и .+$)', r'((^|\s|,)не столько,\s*сколько .+$)', r'(,\s*в то время как .+$)', r'(^в то время как .+,.+$)', r'(,\s*тогда как .+$)', r'(^тогда как .+,.+$)', r'(^между тем как .+,.+$)', r'(,\s*между тем как .+$)', r'(^ровно как .+,.+$)', r'(,\s*ровно как .+$)', r'(^так же как .+,.+$)', r'(,\s*так же как .+$)', r'((^|\s|,)хотя и .+,\s*но .+$)', r'((^|\s|,)не то чтобы .+,\s*но .+$)', r'((^|\s|,)поскольку .+,\s*постольку .+$)', r'((\s|,|:)постольку,\s*постольку .+$)', ) COMPLEX_SYNTAX_ROWS = ( r'(,\s*(и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и .+,\s*который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то, что|невзирая на то, что|правда,|так что|чем|нежели) \w+)', r'(,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя/хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели \w+,\s*(и|а|но|да)|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и) \w+)', r'(,\s*(и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и) .+:)', r'(:\s*\S+,\s*(а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и) \w+)', r'(,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели)\s*:\s*\w+)', r'(:\s*.+,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели)\s*\w+)', r'(,\s*(и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и .+,\s*который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели) .+:\s*\w+)', r'(,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели .+,\s*и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и)\s*:\s*\w+)', r'(:\s*.+,\s*.+,\s*(и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и .+,\s*который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели) \w+)', r'(:\s*.+,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели .+,\s*(и|а|но|да)|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и)\s*:\s*\w+)', r'(,\s*(и|а|но|да|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и .+:\s*.+,\s*(который|чей|что|какой|где|куда|откуда)|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели) \w*)', r'(,\s*(который|чей|что|какой|где|куда|откуда|когда|что|чтобы|будто|будто бы|как|словно|ли|кто|что|который|какой|чтобы|как будто|будто|словно|насколько|пока|пока не|как|как только|лишь только|едва только|стоило как|не прошло как|если|если бы|когда|кабы|как раз|скоро|ежели|если бы|когда бы|коли|коль|для того чтобы|с той целью чтобы|дабы|только бы|лишь бы|потому что|оттого что|благодаря тому что|так как|из-за того что|ибо|благодаря тому что|в виду того что|тем более что|хотя|хоть|пусть|пускай|даром что|несмотря на то,\s*что|невзирая на то,\s*что|правда,|так что|чем|нежели .+:\s*(и|а|но|да)|тоже|также|ни|зато|однако|то ли|или|только|не то|да и|но и) \w+)', ) MODAL_POSTFIX_EXCLUSIONS = ( 'кто-то', 'что-то', 'когда-то', 'какой-то', 'чей-то', 'сколько-то', 'как-то', 'каков-то', 'чего-то', 'чем-то', 'чём-то', 'где-то', 'куда-то', 'откуда-то', 'почему-то', 'зачем-то', 'то-то' ) SYNTAX_SPLICES_EXCLUSIONS = ('нет', 'нет-нет', 'нетнет') VERB_FORMS = ('VERB', 'INFN', 'PRTF', 'PRTS', 'GRND') UNIFORM_ROWS_REGEX = re.compile('|'.join(UNIFORM_ROWS), flags=re.IGNORECASE) COMPARATIVES_REGEX_POS = re.compile('(^|[\\s,:\-—«»"\'])(с целью|из расч(е|ё)та) (INFN)($|[\\s,.:\-—«»"\'])', flags=re.IGNORECASE) COMPARATIVES_REGEX = re.compile('(^|[\\s,:\-—«»"\'])(кроме|помимо|включая|наряду с)([\\s,:«»"\'])', flags=re.IGNORECASE) COMPARATIVE_CONSTRUCTIONS_REGEX = re.compile('((,\\s*)(как|будто|словно|точно|как будто) (\w+)*.*(\.|$))|(^(как|будто|словно|точно|как будто) .*,\\s*.*\.$)', flags=re.IGNORECASE) SYNTAX_SPLICES_REGEX_POS = re.compile('(^|[\\s,:—«»"\'])([а-яА-Яё\-]+)\s+(да и|да)\s+([а-яА-Яё\-]+)($|[\\s,.:—«»"\'])', flags=re.IGNORECASE) SYNTAX_SPLICES_REGEX = re.compile( r'(^|[\s,:\-—«»"\'])(что было,\s*то было|что было,\s*то и есть|что было,\s*то есть|что есть,\s*то есть|что есть,\s*то и есть|что есть,\s*то и будет|что есть,\s*то будет)($|[\s,.:\-—«»"\'])', flags=re.IGNORECASE) COMPARATIVE_CLAUSES_REGEX = re.compile( r'((как|подобно тому как|ровно тому как) .+,\s*\b)|(,\s*как .+,\s*\b)|((подобно тому|ровно тому,\s*как) \b)|((как будто|будто|словно|точно) .+,\s*\b)|(, (как будто|будто|словно|точно) \b)', flags=re.IGNORECASE) EPINTHETIC_CONSTRUCTIONS_REGEX = re.compile(r'(\s+(-|—|—)\s+.+\s+(-|—|—)\s+)|(\(.+\))', flags=re.IGNORECASE) COLLATION_CLAUSES_REGEX = re.compile("|".join(COLLATION_ROWS), flags=re.IGNORECASE) COMPLEX_SYNTAX_REGEX = re.compile('|'.join(COMPLEX_SYNTAX_ROWS), flags=re.IGNORECASE) APPEAL_REGEX = re.compile('((^|,\s)(Name|Patr|Surn)(,\s|!|\.|$))|((^|,\s)(Name (Patr|Surn))(,\s|!|\.|$))|((^|,\s)(Name Patr Surn)(,\s|!|\.|$))|((^|,\s)(Surn Name)(,\s|!|\.|$))|((^|\s)эй,\s*(NPRO|NOUN|ADJF|ADJF|Anum)(,|!|$))', flags=re.IGNORECASE) OURS_PRONOUNS, THEIRS_PRONOUNS = ('я', 'мы', 'мой', 'наш'), \ ('он', 'вы', 'ты', 'она', 'они', 'её', 'ee', 'его', 'их', 'ваш', 'твой') PRONOUNS_EXCLUSIONS = ('кто', 'что', 'чей', 'какой', 'как', 'каков', 'чего', 'чем', 'где', 'куда', 'откуда') COMPLEX_WORDS_REGEX = re.compile(r'(^|\s|,|—|:|«|»|"|\')([А-ЯЁa-яё]+)(-|—)([а-яё]+)($|\s|,|\.|:|—|«|»|"|\')', flags=re.IGNORECASE) MODAL_POSTFIX_REGEX = re.compile(r'(\s+|^)[a-яё]+(\-|\—)то(\s+|!|\?|\.|$)') SENTENCES_SPLIT_REGEX = re.compile(r'\n+\s*\n+', flags=re.IGNORECASE) SENTENCES_SPLIT_ADD_REGEX = re.compile(r'(\n+)([А-ЯЁ]{1})([^А-ЯЁ]{1})') STANDALONE_CONSTRUCTIONS_REGEX = re.compile( r'(\b(?P<first>[a-яё]+)((\s+(-|—|–)\s+)(?P<second>.+(-|—|–)\s+))|(\b(?P<first>[a-яё]+)(,\s*(то есть|или|как)\s+))(?P<second>.+))', flags=re.IGNORECASE) SINGLE_VERB_PREDICATES = {'first_case': ({'pos': ('VERB',), 'mood': ('indc',), 'tense': ('pres', 'futr'), 'numbers': ('plur', 'sing'), 'person': ('1per', '2per'), }, None), 'second_case': ({'pos': ('VERB',), 'mood': ('impr',), 'number': ('plur', 'sing'), }, None), 'third_case': ({'pos': ('VERB',), 'person': ('3per',), 'number': ('plur', 'sing'), 'mood': ('indc',), 'tense': ('pres', 'futr'), }, None), 'fourth_case': ({'pos': ('VERB',), 'tense': ('past',), 'number': ('sing',), 'gender': ('neut',) }, None), 'fifth_case': ({'pos': ('VERB',), 'person': ('3per',), 'number': ('sing',), 'tense': ('pres',), }, None), 'sixth_case': ({ 'pos': ('PRTS',), 'gender': ('neut',), 'voice': ('pssv',) }, None), 'seventh_case': ({ 'pos': ('INFN',), }, None) } SINGLE_VERB_SUBJECTS = {'first_case': ({'pos': ('NOUN', 'NPRO'), 'number': ('plur', 'sing'), 'case': ('nomn',) }, None), 'second_case': ({ 'pos': ('NOUN',), 'number': ('plur', 'sing'), 'case': ('nomn',) }, None), 'third_case': ({ 'pos': ('NOUN',), 'number': ('plur', 'sing'), 'case': ('gen1', 'gen2') }, ('много', 'мало', 'несколько')), 'fourth_case': ({'pos': ('NOUN', 'NPRO'), 'number': ('plur', 'sing'), 'case': ('gen1', 'gen2') }, 'у'), 'fifth_case': ({'pos': ('NOUN', 'NPRO'), 'number': ('plur', 'sing'), 'case': ('datv',) }, None), 'sixth_case': ({ 'pos': ('VERB',), 'number': ('plur', 'sing'), 'tense': ('pres', 'futr', 'past'), }, None) }
77.507772
677
0.539408
2,213
14,959
3.633077
0.103479
0.007463
0.027363
0.01791
0.767413
0.723134
0.674005
0.662935
0.650622
0.650622
0
0.001334
0.248145
14,959
192
678
77.911458
0.710056
0
0
0.230769
0
0.118343
0.618223
0.222141
0
0
0
0
0
1
0
false
0
0.005917
0
0.005917
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0cbf383510b406690e1e6d201506b41a2c33d3af
4,137
py
Python
antelope/refs/flow_ref.py
AntelopeLCA/antelope_lca
18ae7621713c8cc92c7d8fcc7c0810c1ca3fea32
[ "BSD-3-Clause" ]
null
null
null
antelope/refs/flow_ref.py
AntelopeLCA/antelope_lca
18ae7621713c8cc92c7d8fcc7c0810c1ca3fea32
[ "BSD-3-Clause" ]
null
null
null
antelope/refs/flow_ref.py
AntelopeLCA/antelope_lca
18ae7621713c8cc92c7d8fcc7c0810c1ca3fea32
[ "BSD-3-Clause" ]
null
null
null
from .base import EntityRef, InvalidQuery from ..flows import Flow ''' FlowRef could conceivably be used to store characterizations (as opposed to LcFlows, where they're useless) Think about this for future. ''' class FlowRef(EntityRef, Flow): """ Flows can lookup: """ _etype = 'flow' _ref_field = 'referenceQuantity' def __init__(self, *args, **kwargs): super(FlowRef, self).__init__(*args, **kwargs) try: self._add_synonym(self._localitem('name'), set_name=True) except (KeyError, AttributeError): pass if self.has_property('casnumber'): self._add_synonym(self._localitem('casnumber')) self._flowable.add_term(self.link) self._chars_seen = dict() @property def _addl(self): return self.unit ''' def has_characterization(self, quantity, location='GLO'): """ A flow ref keeps track of characterizations by link :param quantity: :param location: :return: """ if quantity.uuid in self._characterizations.keys(): if location == 'GLO' or location is None: return True if location in self._characterizations[quantity.uuid].locations(): return True return False def add_characterization(self, quantity, value=None, **kwargs): q = quantity.uuid if q in self._characterizations.keys(): if value is None: return c = self._characterizations[q] else: c = Characterization(self, quantity) self._characterizations[q] = c if value is not None: if isinstance(value, dict): c.update_values(**value) else: kwargs['overwrite'] = kwargs.pop('overwrite', False) c.add_value(value=value, **kwargs) return c def characterizations(self): for i in self._characterizations.values(): yield i ''' def __setitem__(self, key, value): """ trade one DRY for another... this is not too bad though. :param key: :param value: :return: """ self._catch_context(key, value) self._catch_flowable(key.lower(), value) super(FlowRef, self).__setitem__(key, value) def serialize(self, characterizations=False, domesticate=False, **kwargs): j = super(FlowRef, self).serialize(domesticate=domesticate) j['referenceQuantity'] = self.reference_entity.external_ref return j ''' Interface methods ''' def get_context(self): try: return self._query.get_context(self.context) except InvalidQuery: return self._the_query.get_context(self.context) # this one can bypass -- by talking directly to the catalog def targets(self, direction=None, **kwargs): return self._query.targets(self.external_ref, direction, **kwargs) def terminate(self, **kwargs): return self.targets(**kwargs) def originate(self, direction=None, **kwargs): return self._query.originate(self.external_ref, direction, **kwargs) def profile(self, **kwargs): return self._query.profile(self.external_ref, **kwargs) def characterize(self, quantity, value, context=None, location='GLO', **kwargs): if context is None: context = self.context flowable = self.name self.pop_char(quantity, context, location) return self._query.characterize(flowable, self.reference_entity, quantity, value, context=context, origin=self.origin, location=location, **kwargs) def cf(self, quantity, **kwargs): return quantity.cf(self, **kwargs) ''' Characterization caching ''' def see_char(self, qq, cx, loc, qrr): self._chars_seen[qq, cx, loc] = qrr def chk_char(self, qq, cx, loc): return self._chars_seen[qq, cx, loc] def pop_char(self, qq, cx, loc): return self._chars_seen.pop((qq, cx, loc), None)
31.580153
121
0.606478
465
4,137
5.24086
0.294624
0.045137
0.017234
0.025851
0.170702
0.097251
0.059089
0.027903
0.027903
0
0
0
0.284264
4,137
130
122
31.823077
0.823033
0.040609
0
0.037037
0
0
0.025444
0
0
0
0
0
0
1
0.259259
false
0.018519
0.037037
0.148148
0.574074
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0cd361b8cd235724bb06591947cd96d589b6f379
771
py
Python
qcloudsdkvpc/DeteleSubnetAclRuleRequest.py
f3n9/qcloudcli
b965a4f0e6cdd79c1245c1d0cd2ca9c460a56f19
[ "Apache-2.0" ]
null
null
null
qcloudsdkvpc/DeteleSubnetAclRuleRequest.py
f3n9/qcloudcli
b965a4f0e6cdd79c1245c1d0cd2ca9c460a56f19
[ "Apache-2.0" ]
null
null
null
qcloudsdkvpc/DeteleSubnetAclRuleRequest.py
f3n9/qcloudcli
b965a4f0e6cdd79c1245c1d0cd2ca9c460a56f19
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from qcloudsdkcore.request import Request class DeteleSubnetAclRuleRequest(Request): def __init__(self): super(DeteleSubnetAclRuleRequest, self).__init__( 'vpc', 'qcloudcliV1', 'DeteleSubnetAclRule', 'vpc.api.qcloud.com') def get_networkAclId(self): return self.get_params().get('networkAclId') def set_networkAclId(self, networkAclId): self.add_param('networkAclId', networkAclId) def get_subnetIds(self): return self.get_params().get('subnetIds') def set_subnetIds(self, subnetIds): self.add_param('subnetIds', subnetIds) def get_vpcId(self): return self.get_params().get('vpcId') def set_vpcId(self, vpcId): self.add_param('vpcId', vpcId)
27.535714
78
0.675746
85
771
5.894118
0.329412
0.035928
0.083832
0.101796
0.155689
0.155689
0
0
0
0
0
0.003226
0.19585
771
27
79
28.555556
0.804839
0.027237
0
0
0
0
0.137701
0
0
0
0
0
0
1
0.411765
false
0
0.058824
0.176471
0.705882
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0ce664babd298621aebe932ec3af2a01a7c52846
184
py
Python
train_sentencepiece.py
sinchir0/try_sentencepiece
aaf0fb78a404e51da8d3e072fb6153eb18aeceb2
[ "MIT" ]
null
null
null
train_sentencepiece.py
sinchir0/try_sentencepiece
aaf0fb78a404e51da8d3e072fb6153eb18aeceb2
[ "MIT" ]
null
null
null
train_sentencepiece.py
sinchir0/try_sentencepiece
aaf0fb78a404e51da8d3e072fb6153eb18aeceb2
[ "MIT" ]
null
null
null
import sentencepiece as spm # モデルの学習 spm.SentencePieceTrainer.Train( input='all_tweet.txt', model_prefix='sentencepiece', vocab_size=2000, character_coverage=0.9995 )
18.4
33
0.744565
22
184
6.045455
0.909091
0
0
0
0
0
0
0
0
0
0
0.058065
0.157609
184
9
34
20.444444
0.8
0.032609
0
0
0
0
0.147727
0
0
0
0
0
0
1
0
true
0
0.142857
0
0.142857
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
0ced9da0e9ef880c02c9b9021e2be5e9311e1c76
2,146
py
Python
manticore/core/cpu/disasm.py
evanpjensen/manticore
3f74e3b7f80757b493bdce3d13178043513ea102
[ "Apache-2.0" ]
null
null
null
manticore/core/cpu/disasm.py
evanpjensen/manticore
3f74e3b7f80757b493bdce3d13178043513ea102
[ "Apache-2.0" ]
null
null
null
manticore/core/cpu/disasm.py
evanpjensen/manticore
3f74e3b7f80757b493bdce3d13178043513ea102
[ "Apache-2.0" ]
null
null
null
from abc import abstractproperty, abstractmethod import capstone as cs class Instruction(object): """Capstone-like instruction to be used internally """ @property @abstractmethod def address(self): pass @property @abstractmethod def mnemonic(self): pass @property @abstractmethod def op_str(self): pass @property @abstractmethod def size(self): pass @property @abstractmethod def operands(self): pass # FIXME (theo) eliminate one of the two of insn_name, name @property @abstractmethod def insn_name(self): pass @property @abstractmethod def name(self): pass class Disasm(object): """Abstract class for different disassembler interfaces""" def __init__(self, disasm): self.disasm = disasm @abstractmethod def disassemble_instruction(self, code, pc): """Get next instruction based on the disassembler in use :param str code: binary blob to be disassembled :param long pc: program counter """ class CapstoneDisasm(Disasm): def __init__(self, arch, mode): try: cap = cs.Cs(arch, mode) except Exception as e: raise e cap.detail = True cap.syntax = 0 super().__init__(cap) def disassemble_instruction(self, code, pc): """Get next instruction using the Capstone disassembler :param str code: binary blob to be disassembled :param long pc: program counter """ return next(self.disasm.disasm(code, pc)) def init_disassembler(disassembler, arch, mode, view=None): """Initialize disassembler engine :param disassembler: Name of disassembler to use :type disassembler: str :param arch: capstone constant indicating target architecture :type arch: int :param mode: capstone constant indicating disassembler mode :type mode: int """ if disassembler == "capstone": return CapstoneDisasm(arch, mode) else: raise NotImplementedError("Disassembler not implemented")
22.829787
65
0.640727
235
2,146
5.774468
0.378723
0.100221
0.128961
0.110538
0.292557
0.170965
0.170965
0.170965
0.170965
0.092852
0
0.000649
0.282386
2,146
93
66
23.075269
0.880519
0.321994
0
0.461538
0
0
0.026667
0
0
0
0
0.010753
0
1
0.230769
false
0.134615
0.038462
0
0.365385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
1
0
0
0
0
0
3
0cedec85e34947069a16cfe92eff78dfd10b3ddb
107
py
Python
7 kyu/Disemvowel Trolls/Disemvowel Trolls.py
anthonyjatoba/codewars
76b0d66dd1ba76a4d136b658920cdf85fd5c4b06
[ "MIT" ]
null
null
null
7 kyu/Disemvowel Trolls/Disemvowel Trolls.py
anthonyjatoba/codewars
76b0d66dd1ba76a4d136b658920cdf85fd5c4b06
[ "MIT" ]
null
null
null
7 kyu/Disemvowel Trolls/Disemvowel Trolls.py
anthonyjatoba/codewars
76b0d66dd1ba76a4d136b658920cdf85fd5c4b06
[ "MIT" ]
null
null
null
def disemvowel(string): for v in 'aeiouAEIOU': string = string.replace(v, '') return string
26.75
38
0.626168
13
107
5.153846
0.692308
0
0
0
0
0
0
0
0
0
0
0
0.252336
107
4
39
26.75
0.8375
0
0
0
0
0
0.092593
0
0
0
0
0
0
1
0.25
false
0
0
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0cf120b9ed88b3695431646c93f45f913af0d3da
331
py
Python
CAIL2020/cocr/torchocr/datasets/det_modules/__init__.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
71
2020-07-16T01:49:27.000Z
2022-03-27T16:55:00.000Z
CAIL2020/cocr/torchocr/datasets/det_modules/__init__.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
11
2020-09-18T14:26:25.000Z
2022-02-09T23:49:33.000Z
CAIL2020/cocr/torchocr/datasets/det_modules/__init__.py
ShenDezhou/CAIL
c4cfa98ab4ecedbce34a7a5a186830486047540c
[ "Apache-2.0" ]
16
2020-07-15T07:24:30.000Z
2022-03-19T05:41:11.000Z
# -*- coding: utf-8 -*- # @Time : 2019/12/4 10:53 # @Author : THU """ 此模块包含了检测算法的图片预处理组件,如随机裁剪,随机缩放,随机旋转,label制作等 """ from .iaa_augment import IaaAugment from .augment import * from .random_crop_data import EastRandomCropData,PSERandomCrop from .make_border_map import MakeBorderMap from .make_shrink_map import MakeShrinkMap
25.461538
62
0.767372
43
331
5.744186
0.744186
0.105263
0
0
0
0
0
0
0
0
0
0.041522
0.126888
331
12
63
27.583333
0.813149
0.326284
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
0b283cdcdb096fa155a7582691ad256e1838b2ca
252
py
Python
hitbtcapi/compat.py
aopina1/HitBTC_API
6762407c5cc6636d0b6c9fdae8f221733a84aa24
[ "MIT" ]
12
2018-04-13T12:49:23.000Z
2021-11-20T06:20:46.000Z
hitbtcapi/compat.py
aopina1/HitBTC_API
6762407c5cc6636d0b6c9fdae8f221733a84aa24
[ "MIT" ]
1
2019-03-07T06:29:25.000Z
2019-03-07T06:29:25.000Z
hitbtcapi/compat.py
aopina1/HitBTC_API
6762407c5cc6636d0b6c9fdae8f221733a84aa24
[ "MIT" ]
6
2018-06-23T15:53:42.000Z
2021-01-22T02:27:02.000Z
# coding: utf-8 import inspect import six if six.PY2: from itertools import imap from urllib import quote from urlparse import urlparse elif six.PY3: imap = map from urllib.parse import quote from urllib.parse import urlparse
18
37
0.722222
37
252
4.918919
0.486486
0.164835
0.164835
0.230769
0
0
0
0
0
0
0
0.015625
0.238095
252
13
38
19.384615
0.932292
0.051587
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.7
0
0.7
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
0b5307eda66551a7e13055ef2b35924e935a05c3
648
py
Python
scaleapi/evaluation_tasks.py
scaleapi/scaleapi-python-client
5c38b89ca76a1b935288761d962094822034d6cb
[ "Apache-2.0" ]
43
2016-10-18T04:02:18.000Z
2022-02-24T22:54:19.000Z
scaleapi/evaluation_tasks.py
scaleapi/scaleapi-python-client
5c38b89ca76a1b935288761d962094822034d6cb
[ "Apache-2.0" ]
12
2017-05-03T03:54:53.000Z
2022-02-09T01:36:54.000Z
scaleapi/evaluation_tasks.py
scaleapi/scaleapi-python-client
5c38b89ca76a1b935288761d962094822034d6cb
[ "Apache-2.0" ]
27
2017-03-14T18:20:00.000Z
2021-09-16T17:49:45.000Z
class EvaluationTask: """EvaluationTask class, containing EvaluationTask information.""" def __init__(self, json, client): self._json = json self.id = json["id"] self.initial_response = getattr(json, "initial_response", None) self.expected_response = json["expected_response"] self._client = client def __hash__(self): return hash(self.id) def __str__(self): return f"EvaluationTask(id={self.id})" def __repr__(self): return f"EvaluationTask({self._json})" def as_dict(self): """Returns all attributes as a dictionary""" return self._json
28.173913
71
0.638889
73
648
5.328767
0.369863
0.082262
0.046272
0.128535
0
0
0
0
0
0
0
0
0.24537
648
22
72
29.454545
0.795501
0.152778
0
0
0
0
0.169145
0.104089
0
0
0
0
0
1
0.333333
false
0
0
0.2
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0b5ae682351da51bb5dc616b9d725febe886d2ab
3,068
py
Python
aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/DumpMetaDataSourceForOuterRequest.py
bricklayer-Liu/aliyun-openapi-python-sdk
20da2554de22679fc7c5462c483663e4d79512aa
[ "Apache-2.0" ]
1
2021-03-08T02:59:17.000Z
2021-03-08T02:59:17.000Z
aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/DumpMetaDataSourceForOuterRequest.py
bricklayer-Liu/aliyun-openapi-python-sdk
20da2554de22679fc7c5462c483663e4d79512aa
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/DumpMetaDataSourceForOuterRequest.py
bricklayer-Liu/aliyun-openapi-python-sdk
20da2554de22679fc7c5462c483663e4d79512aa
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkemr.endpoint import endpoint_data class DumpMetaDataSourceForOuterRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Emr', '2016-04-08', 'DumpMetaDataSourceForOuter') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_DumpAllDatabase(self): return self.get_query_params().get('DumpAllDatabase') def set_DumpAllDatabase(self,DumpAllDatabase): self.add_query_param('DumpAllDatabase',DumpAllDatabase) def get_DumpLimit(self): return self.get_query_params().get('DumpLimit') def set_DumpLimit(self,DumpLimit): self.add_query_param('DumpLimit',DumpLimit) def get_ClusterId(self): return self.get_query_params().get('ClusterId') def set_ClusterId(self,ClusterId): self.add_query_param('ClusterId',ClusterId) def get_DumpAllTable(self): return self.get_query_params().get('DumpAllTable') def set_DumpAllTable(self,DumpAllTable): self.add_query_param('DumpAllTable',DumpAllTable) def get_PartitionValuess(self): return self.get_query_params().get('PartitionValues') def set_PartitionValuess(self, PartitionValuess): for depth1 in range(len(PartitionValuess)): if PartitionValuess[depth1] is not None: self.add_query_param('PartitionValues.' + str(depth1 + 1) , PartitionValuess[depth1]) def get_TableId(self): return self.get_query_params().get('TableId') def set_TableId(self,TableId): self.add_query_param('TableId',TableId) def get_DatabaseId(self): return self.get_query_params().get('DatabaseId') def set_DatabaseId(self,DatabaseId): self.add_query_param('DatabaseId',DatabaseId) def get_DumpAllPartition(self): return self.get_query_params().get('DumpAllPartition') def set_DumpAllPartition(self,DumpAllPartition): self.add_query_param('DumpAllPartition',DumpAllPartition)
34.863636
90
0.769557
387
3,068
5.919897
0.315245
0.02357
0.054998
0.066783
0.121781
0.121781
0.121781
0
0
0
0
0.006372
0.130378
3,068
88
91
34.863636
0.852324
0.245763
0
0
0
0
0.142028
0.011612
0
0
0
0
0
1
0.395833
false
0
0.041667
0.1875
0.645833
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0b5e6ce71344c754d3ad4981179a4231d435f26c
226
py
Python
EDMScripts/ManualStateSelector.py
jstammers/EDMSuite
2841c0edef32a496855ca41deaa0f710b017ae2f
[ "MIT" ]
6
2017-02-02T17:54:23.000Z
2021-07-03T12:41:36.000Z
EDMScripts/ManualStateSelector.py
jstammers/EDMSuite
2841c0edef32a496855ca41deaa0f710b017ae2f
[ "MIT" ]
null
null
null
EDMScripts/ManualStateSelector.py
jstammers/EDMSuite
2841c0edef32a496855ca41deaa0f710b017ae2f
[ "MIT" ]
11
2015-03-19T18:23:38.000Z
2021-02-18T11:05:51.000Z
from System import Random rand = Random() def randomBool(): if rand.Next(0,2) < 1: return "True" else: return "False" def run_script(): print("(" + randomBool() + ", " + randomBool() + ", " + randomBool() + ")" )
15.066667
77
0.579646
26
226
5
0.730769
0.307692
0
0
0
0
0
0
0
0
0
0.016949
0.216814
226
14
78
16.142857
0.717514
0
0
0
0
0
0.066964
0
0
0
0
0
0
1
0.222222
false
0
0.111111
0
0.555556
0.111111
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0b6553ea027221c317d66767ff4781f228bd10eb
94
py
Python
helios/store/tests/__init__.py
panosl/helios
22ceb736709aaa336def81d801797d72321a737e
[ "BSD-3-Clause" ]
2
2021-01-26T02:37:19.000Z
2021-12-02T14:15:22.000Z
helios/store/tests/__init__.py
panosl/helios
22ceb736709aaa336def81d801797d72321a737e
[ "BSD-3-Clause" ]
null
null
null
helios/store/tests/__init__.py
panosl/helios
22ceb736709aaa336def81d801797d72321a737e
[ "BSD-3-Clause" ]
null
null
null
from helios.store.tests.cart import CART_TESTS __test__ = { 'CART_TESTS': CART_TESTS, }
13.428571
46
0.723404
13
94
4.692308
0.538462
0.442623
0
0
0
0
0
0
0
0
0
0
0.170213
94
6
47
15.666667
0.782051
0
0
0
0
0
0.106383
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0b6c46970e7fae680de602fd27ea491690157796
50,175
py
Python
mypy/types.py
bavardage/mypy
b116b6844a40d57eac23e5254b221aa79ea69094
[ "PSF-2.0" ]
1
2021-08-23T21:06:32.000Z
2021-08-23T21:06:32.000Z
mypy/types.py
bavardage/mypy
b116b6844a40d57eac23e5254b221aa79ea69094
[ "PSF-2.0" ]
null
null
null
mypy/types.py
bavardage/mypy
b116b6844a40d57eac23e5254b221aa79ea69094
[ "PSF-2.0" ]
null
null
null
"""Classes for representing mypy types.""" from abc import abstractmethod import copy from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Sequence, Optional, Union ) import mypy.nodes from mypy.nodes import INVARIANT, SymbolNode from mypy import experiments T = TypeVar('T') JsonDict = Dict[str, Any] class Type(mypy.nodes.Context): """Abstract base class for all types.""" line = 0 can_be_true = True can_be_false = True def __init__(self, line: int = -1) -> None: self.line = line def get_line(self) -> int: return self.line def accept(self, visitor: 'TypeVisitor[T]') -> T: raise RuntimeError('Not implemented') def __repr__(self) -> str: return self.accept(TypeStrVisitor()) def serialize(self) -> JsonDict: raise NotImplementedError('Cannot serialize {} instance'.format(self.__class__.__name__)) @classmethod def deserialize(cls, data: JsonDict) -> 'Type': classname = data['.class'] glo = globals() if classname in glo: cl = glo[classname] if 'deserialize' in cl.__dict__: return cl.deserialize(data) raise NotImplementedError('unexpected .class {}'.format(classname)) class TypeVarId: # A type variable is uniquely identified by its raw id and meta level. # For plain variables (type parameters of generic classes and # functions) raw ids are allocated by semantic analysis, using # positive ids 1, 2, ... for generic class parameters and negative # ids -1, ... for generic function type arguments. This convention # is only used to keep type variable ids distinct when allocating # them; the type checker makes no distinction between class and # function type variables. # Metavariables are allocated unique ids starting from 1. raw_id = 0 # type: int # Level of the variable in type inference. Currently either 0 for # declared types, or 1 for type inference metavariables. meta_level = 0 # type: int # Class variable used for allocating fresh ids for metavariables. next_raw_id = 1 # type: int def __init__(self, raw_id: int, meta_level: int = 0) -> None: self.raw_id = raw_id self.meta_level = meta_level @staticmethod def new(meta_level: int) -> 'TypeVarId': raw_id = TypeVarId.next_raw_id TypeVarId.next_raw_id += 1 return TypeVarId(raw_id, meta_level) def __repr__(self) -> str: return self.raw_id.__repr__() def __eq__(self, other: object) -> bool: if isinstance(other, TypeVarId): return (self.raw_id == other.raw_id and self.meta_level == other.meta_level) else: return False def __ne__(self, other: object) -> bool: return not (self == other) def __hash__(self) -> int: return hash((self.raw_id, self.meta_level)) def is_meta_var(self) -> bool: return self.meta_level > 0 class TypeVarDef(mypy.nodes.Context): """Definition of a single type variable.""" name = '' id = None # type: TypeVarId values = None # type: List[Type] # Value restriction, empty list if no restriction upper_bound = None # type: Type variance = INVARIANT # type: int line = 0 def __init__(self, name: str, id: Union[TypeVarId, int], values: Optional[List[Type]], upper_bound: Type, variance: int = INVARIANT, line: int = -1) -> None: self.name = name if isinstance(id, int): id = TypeVarId(id) self.id = id self.values = values self.upper_bound = upper_bound self.variance = variance self.line = line @staticmethod def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef': new_id = TypeVarId.new(meta_level=1) return TypeVarDef(old.name, new_id, old.values, old.upper_bound, old.variance, old.line) def get_line(self) -> int: return self.line def __repr__(self) -> str: if self.values: return '{} in {}'.format(self.name, tuple(self.values)) elif not is_named_instance(self.upper_bound, 'builtins.object'): return '{} <: {}'.format(self.name, self.upper_bound) else: return self.name def serialize(self) -> JsonDict: assert not self.id.is_meta_var() return {'.class': 'TypeVarDef', 'name': self.name, 'id': self.id.raw_id, 'values': None if self.values is None else [v.serialize() for v in self.values], 'upper_bound': self.upper_bound.serialize(), 'variance': self.variance, } @classmethod def deserialize(cls, data: JsonDict) -> 'TypeVarDef': assert data['.class'] == 'TypeVarDef' return TypeVarDef(data['name'], data['id'], None if data['values'] is None else [Type.deserialize(v) for v in data['values']], Type.deserialize(data['upper_bound']), data['variance'], ) class UnboundType(Type): """Instance type that has not been bound during semantic analysis.""" name = '' args = None # type: List[Type] # should this type be wrapped in an Optional? optional = False # is this type a return type? is_ret_type = False def __init__(self, name: str, args: List[Type] = None, line: int = -1, optional: bool = False, is_ret_type: bool = False) -> None: if not args: args = [] self.name = name self.args = args self.optional = optional self.is_ret_type = is_ret_type super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_unbound_type(self) def serialize(self) -> JsonDict: return {'.class': 'UnboundType', 'name': self.name, 'args': [a.serialize() for a in self.args], } @classmethod def deserialize(self, data: JsonDict) -> 'UnboundType': assert data['.class'] == 'UnboundType' return UnboundType(data['name'], [Type.deserialize(a) for a in data['args']]) class ErrorType(Type): """The error type is used as the result of failed type operations.""" def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_error_type(self) class TypeList(Type): """A list of types [...]. This is only used for the arguments of a Callable type, i.e. for [arg, ...] in Callable[[arg, ...], ret]. This is not a real type but a syntactic AST construct. """ items = None # type: List[Type] def __init__(self, items: List[Type], line: int = -1) -> None: super().__init__(line) self.items = items def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_type_list(self) def serialize(self) -> JsonDict: return {'.class': 'TypeList', 'items': [t.serialize() for t in self.items], } @classmethod def deserialize(self, data: JsonDict) -> 'TypeList': assert data['.class'] == 'TypeList' return TypeList([Type.deserialize(t) for t in data['items']]) class AnyType(Type): """The type 'Any'.""" def __init__(self, implicit: bool = False, line: int = -1) -> None: super().__init__(line) self.implicit = implicit def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_any(self) def serialize(self) -> JsonDict: return {'.class': 'AnyType'} @classmethod def deserialize(cls, data: JsonDict) -> 'AnyType': assert data['.class'] == 'AnyType' return AnyType() class Void(Type): """The return type 'None'. This can only be used as the return type in a callable type and as the result type of calling such callable. """ can_be_true = False source = '' # May be None; function that generated this value def __init__(self, source: str = None, line: int = -1) -> None: self.source = source super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_void(self) def with_source(self, source: str) -> 'Void': return Void(source, self.line) def serialize(self) -> JsonDict: return {'.class': 'Void'} @classmethod def deserialize(cls, data: JsonDict) -> 'Void': assert data['.class'] == 'Void' return Void() class UninhabitedType(Type): """This type has no members. This type is almost the bottom type, except it is not a subtype of Void. With strict Optional checking, it is the only common subtype between all other types, which allows `meet` to be well defined. Without strict Optional checking, NoneTyp fills this role. In general, for any type T that isn't Void: join(UninhabitedType, T) = T meet(UninhabitedType, T) = UninhabitedType is_subtype(UninhabitedType, T) = True """ can_be_true = False can_be_false = False def __init__(self, line: int = -1) -> None: super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_uninhabited_type(self) def serialize(self) -> JsonDict: return {'.class': 'UninhabitedType'} @classmethod def deserialize(cls, data: JsonDict) -> 'UninhabitedType': assert data['.class'] == 'UninhabitedType' return UninhabitedType() class NoneTyp(Type): """The type of 'None'. Without strict Optional checking: This is only used internally during type inference. Programs cannot declare a variable of this type, and the type checker refuses to infer this type for a variable. However, subexpressions often have this type. Note that this is not used as the result type when calling a function with a void type, even though semantically such a function returns a None value; the void type is used instead so that we can report an error if the caller tries to do anything with the return value. With strict Optional checking: This type can be written by users as 'None', except as the return value of a function, where 'None' means Void. """ can_be_true = False def __init__(self, is_ret_type: bool = False, line: int = -1) -> None: super().__init__(line) self.is_ret_type = is_ret_type def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_none_type(self) def serialize(self) -> JsonDict: return {'.class': 'NoneTyp', 'is_ret_type': self.is_ret_type, } @classmethod def deserialize(self, data: JsonDict) -> 'NoneTyp': assert data['.class'] == 'NoneTyp' return NoneTyp(is_ret_type=data['is_ret_type']) class ErasedType(Type): """Placeholder for an erased type. This is used during type inference. This has the special property that it is ignored during type inference. """ def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_erased_type(self) class DeletedType(Type): """Type of deleted variables. These can be used as lvalues but not rvalues. """ source = '' # May be None; name that generated this value def __init__(self, source: str = None, line: int = -1) -> None: self.source = source super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_deleted_type(self) def serialize(self) -> JsonDict: return {'.class': 'DeletedType', 'source': self.source} @classmethod def deserialize(self, data: JsonDict) -> 'DeletedType': assert data['.class'] == 'DeletedType' return DeletedType(data['source']) class Instance(Type): """An instance type of form C[T1, ..., Tn]. The list of type variables may be empty. """ type = None # type: mypy.nodes.TypeInfo args = None # type: List[Type] erased = False # True if result of type variable substitution def __init__(self, typ: mypy.nodes.TypeInfo, args: List[Type], line: int = -1, erased: bool = False) -> None: self.type = typ self.args = args self.erased = erased super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_instance(self) type_ref = None # type: str def serialize(self) -> JsonDict: data = {'.class': 'Instance', } # type: JsonDict assert self.type is not None data['type_ref'] = self.type.alt_fullname or self.type.fullname() if self.args: data['args'] = [arg.serialize() for arg in self.args] return data @classmethod def deserialize(cls, data: JsonDict) -> 'Instance': assert data['.class'] == 'Instance' args = [] # type: List[Type] if 'args' in data: args_list = data['args'] assert isinstance(args_list, list) args = [Type.deserialize(arg) for arg in args_list] inst = Instance(None, args) inst.type_ref = data['type_ref'] # Will be fixed up by fixup.py later. return inst class TypeVarType(Type): """A type variable type. This refers to either a class type variable (id > 0) or a function type variable (id < 0). """ name = '' # Name of the type variable (for messages and debugging) id = None # type: TypeVarId values = None # type: List[Type] # Value restriction, empty list if no restriction upper_bound = None # type: Type # Upper bound for values # See comments in TypeVarDef for more about variance. variance = INVARIANT # type: int def __init__(self, binder: TypeVarDef, line: int = -1) -> None: self.name = binder.name self.id = binder.id self.values = binder.values self.upper_bound = binder.upper_bound self.variance = binder.variance super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_type_var(self) def erase_to_union_or_bound(self) -> Type: if self.values: return UnionType.make_simplified_union(self.values) else: return self.upper_bound def serialize(self) -> JsonDict: assert not self.id.is_meta_var() return {'.class': 'TypeVarType', 'name': self.name, 'id': self.id.raw_id, 'values': [v.serialize() for v in self.values], 'upper_bound': self.upper_bound.serialize(), 'variance': self.variance, } @classmethod def deserialize(cls, data: JsonDict) -> 'TypeVarType': assert data['.class'] == 'TypeVarType' tvdef = TypeVarDef(data['name'], data['id'], [Type.deserialize(v) for v in data['values']], Type.deserialize(data['upper_bound']), data['variance']) return TypeVarType(tvdef) class FunctionLike(Type): """Abstract base class for function types.""" can_be_false = False @abstractmethod def is_type_obj(self) -> bool: pass def is_concrete_type_obj(self) -> bool: return self.is_type_obj() @abstractmethod def type_object(self) -> mypy.nodes.TypeInfo: pass @abstractmethod def items(self) -> List['CallableType']: pass @abstractmethod def with_name(self, name: str) -> 'FunctionLike': pass # Corresponding instance type (e.g. builtins.type) fallback = None # type: Instance @classmethod def deserialize(cls, data: JsonDict) -> 'FunctionLike': return cast(FunctionLike, super().deserialize(data)) _dummy = object() # type: Any class CallableType(FunctionLike): """Type of a non-overloaded callable object (function).""" arg_types = None # type: List[Type] # Types of function arguments arg_kinds = None # type: List[int] # mypy.nodes.ARG_ constants arg_names = None # type: List[str] # None if not a keyword argument min_args = 0 # Minimum number of arguments; derived from arg_kinds is_var_arg = False # Is it a varargs function? derived from arg_kinds ret_type = None # type: Type # Return value type name = '' # Name (may be None; for error messages) definition = None # type: SymbolNode # For error messages. May be None. # Type variables for a generic function variables = None # type: List[TypeVarDef] # Is this Callable[..., t] (with literal '...')? is_ellipsis_args = False # Is this callable constructed for the benefit of a classmethod's 'cls' argument? is_classmethod_class = False # Was this type implicitly generated instead of explicitly specified by the user? implicit = False # Defined for signatures that require special handling (currently only value is 'dict' # for a signature similar to 'dict') special_sig = None # type: Optional[str] def __init__(self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], ret_type: Type, fallback: Instance, name: str = None, definition: SymbolNode = None, variables: List[TypeVarDef] = None, line: int = -1, is_ellipsis_args: bool = False, implicit: bool = False, is_classmethod_class: bool = False, special_sig: Optional[str] = None, ) -> None: if variables is None: variables = [] self.arg_types = arg_types self.arg_kinds = arg_kinds self.arg_names = arg_names self.min_args = arg_kinds.count(mypy.nodes.ARG_POS) self.is_var_arg = mypy.nodes.ARG_STAR in arg_kinds self.ret_type = ret_type self.fallback = fallback assert not name or '<bound method' not in name self.name = name self.definition = definition self.variables = variables self.is_ellipsis_args = is_ellipsis_args self.implicit = implicit self.special_sig = special_sig super().__init__(line) def copy_modified(self, arg_types: List[Type] = _dummy, arg_kinds: List[int] = _dummy, arg_names: List[str] = _dummy, ret_type: Type = _dummy, fallback: Instance = _dummy, name: str = _dummy, definition: SymbolNode = _dummy, variables: List[TypeVarDef] = _dummy, line: int = _dummy, is_ellipsis_args: bool = _dummy, special_sig: Optional[str] = _dummy) -> 'CallableType': return CallableType( arg_types=arg_types if arg_types is not _dummy else self.arg_types, arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds, arg_names=arg_names if arg_names is not _dummy else self.arg_names, ret_type=ret_type if ret_type is not _dummy else self.ret_type, fallback=fallback if fallback is not _dummy else self.fallback, name=name if name is not _dummy else self.name, definition=definition if definition is not _dummy else self.definition, variables=variables if variables is not _dummy else self.variables, line=line if line is not _dummy else self.line, is_ellipsis_args=( is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args), implicit=self.implicit, is_classmethod_class=self.is_classmethod_class, special_sig=special_sig if special_sig is not _dummy else self.special_sig, ) def is_type_obj(self) -> bool: return self.fallback.type is not None and self.fallback.type.fullname() == 'builtins.type' def is_concrete_type_obj(self) -> bool: return self.is_type_obj() and self.is_classmethod_class def type_object(self) -> mypy.nodes.TypeInfo: assert self.is_type_obj() ret = self.ret_type if isinstance(ret, TupleType): ret = ret.fallback return cast(Instance, ret).type def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_callable_type(self) def with_name(self, name: str) -> 'CallableType': """Return a copy of this type with the specified name.""" ret = self.ret_type if isinstance(ret, Void): ret = ret.with_source(name) return self.copy_modified(ret_type=ret, name=name) def max_fixed_args(self) -> int: n = len(self.arg_types) if self.is_var_arg: n -= 1 return n def items(self) -> List['CallableType']: return [self] def is_generic(self) -> bool: return bool(self.variables) def type_var_ids(self) -> List[TypeVarId]: a = [] # type: List[TypeVarId] for tv in self.variables: a.append(tv.id) return a def serialize(self) -> JsonDict: # TODO: As an optimization, leave out everything related to # generic functions for non-generic functions. return {'.class': 'CallableType', 'arg_types': [(None if t is None else t.serialize()) for t in self.arg_types], 'arg_kinds': self.arg_kinds, 'arg_names': self.arg_names, 'ret_type': self.ret_type.serialize(), 'fallback': self.fallback.serialize(), 'name': self.name, # We don't serialize the definition (only used for error messages). 'variables': [v.serialize() for v in self.variables], 'is_ellipsis_args': self.is_ellipsis_args, 'implicit': self.implicit, 'is_classmethod_class': self.is_classmethod_class, } @classmethod def deserialize(cls, data: JsonDict) -> 'CallableType': assert data['.class'] == 'CallableType' # TODO: Set definition to the containing SymbolNode? return CallableType([(None if t is None else Type.deserialize(t)) for t in data['arg_types']], data['arg_kinds'], data['arg_names'], Type.deserialize(data['ret_type']), Instance.deserialize(data['fallback']), name=data['name'], variables=[TypeVarDef.deserialize(v) for v in data['variables']], is_ellipsis_args=data['is_ellipsis_args'], implicit=data['implicit'], is_classmethod_class=data['is_classmethod_class'], ) class Overloaded(FunctionLike): """Overloaded function type T1, ... Tn, where each Ti is CallableType. The variant to call is chosen based on static argument types. Overloaded function types can only be defined in stub files, and thus there is no explicit runtime dispatch implementation. """ _items = None # type: List[CallableType] # Must not be empty def __init__(self, items: List[CallableType]) -> None: self._items = items self.fallback = items[0].fallback super().__init__(items[0].line) def items(self) -> List[CallableType]: return self._items def name(self) -> str: return self._items[0].name def is_type_obj(self) -> bool: # All the items must have the same type object status, so it's # sufficient to query only (any) one of them. return self._items[0].is_type_obj() def type_object(self) -> mypy.nodes.TypeInfo: # All the items must have the same type object, so it's sufficient to # query only (any) one of them. return self._items[0].type_object() def with_name(self, name: str) -> 'Overloaded': ni = [] # type: List[CallableType] for it in self._items: ni.append(it.with_name(name)) return Overloaded(ni) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_overloaded(self) def serialize(self) -> JsonDict: return {'.class': 'Overloaded', 'items': [t.serialize() for t in self.items()], } @classmethod def deserialize(self, data: JsonDict) -> 'Overloaded': assert data['.class'] == 'Overloaded' return Overloaded([CallableType.deserialize(t) for t in data['items']]) class TupleType(Type): """The tuple type Tuple[T1, ..., Tn] (at least one type argument). Instance variables: items: tuple item types fallback: the underlying instance type that is used for non-tuple methods (this is currently always builtins.tuple, but it could be different for named tuples, for example) implicit: if True, derived from a tuple expression (t,....) instead of Tuple[t, ...] """ items = None # type: List[Type] fallback = None # type: Instance implicit = False def __init__(self, items: List[Type], fallback: Instance, line: int = -1, implicit: bool = False) -> None: self.items = items self.fallback = fallback self.implicit = implicit self.can_be_true = len(self.items) > 0 self.can_be_false = len(self.items) == 0 super().__init__(line) def length(self) -> int: return len(self.items) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_tuple_type(self) def serialize(self) -> JsonDict: return {'.class': 'TupleType', 'items': [t.serialize() for t in self.items], 'fallback': self.fallback.serialize(), 'implicit': self.implicit, } @classmethod def deserialize(cls, data: JsonDict) -> 'TupleType': assert data['.class'] == 'TupleType' return TupleType([Type.deserialize(t) for t in data['items']], Instance.deserialize(data['fallback']), implicit=data['implicit']) def copy_modified(self, *, fallback: Instance = None, items: List[Type] = None) -> 'TupleType': if fallback is None: fallback = self.fallback if items is None: items = self.items return TupleType(items, fallback, self.line) def slice(self, begin: int, stride: int, end: int) -> 'TupleType': return TupleType(self.items[begin:end:stride], self.fallback, self.line, self.implicit) class StarType(Type): """The star type *type_parameter. This is not a real type but a syntactic AST construct. """ type = None # type: Type def __init__(self, type: Type, line: int = -1) -> None: self.type = type super().__init__(line) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_star_type(self) class UnionType(Type): """The union type Union[T1, ..., Tn] (at least one type argument).""" items = None # type: List[Type] def __init__(self, items: List[Type], line: int = -1) -> None: self.items = items self.can_be_true = any(item.can_be_true for item in items) self.can_be_false = any(item.can_be_false for item in items) super().__init__(line) @staticmethod def make_union(items: List[Type], line: int = -1) -> Type: if len(items) > 1: return UnionType(items, line) elif len(items) == 1: return items[0] else: if experiments.STRICT_OPTIONAL: return UninhabitedType() else: return Void() @staticmethod def make_simplified_union(items: List[Type], line: int = -1) -> Type: while any(isinstance(typ, UnionType) for typ in items): all_items = [] # type: List[Type] for typ in items: if isinstance(typ, UnionType): all_items.extend(typ.items) else: all_items.append(typ) items = all_items if any(isinstance(typ, AnyType) for typ in items): return AnyType() from mypy.subtypes import is_subtype removed = set() # type: Set[int] for i, ti in enumerate(items): if i in removed: continue # Keep track of the truishness info for deleted subtypes which can be relevant cbt = cbf = False for j, tj in enumerate(items): if i != j and is_subtype(tj, ti): removed.add(j) cbt = cbt or tj.can_be_true cbf = cbf or tj.can_be_false # if deleted subtypes had more general truthiness, use that if not ti.can_be_true and cbt: items[i] = true_or_false(ti) elif not ti.can_be_false and cbf: items[i] = true_or_false(ti) simplified_set = [items[i] for i in range(len(items)) if i not in removed] return UnionType.make_union(simplified_set) def length(self) -> int: return len(self.items) def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_union_type(self) def has_readable_member(self, name: str) -> bool: """For a tree of unions of instances, check whether all instances have a given member. TODO: Deal with attributes of TupleType etc. TODO: This should probably be refactored to go elsewhere. """ return all((isinstance(x, UnionType) and x.has_readable_member(name)) or (isinstance(x, Instance) and x.type.has_readable_member(name)) for x in self.items) def serialize(self) -> JsonDict: return {'.class': 'UnionType', 'items': [t.serialize() for t in self.items], } @classmethod def deserialize(cls, data: JsonDict) -> 'UnionType': assert data['.class'] == 'UnionType' return UnionType([Type.deserialize(t) for t in data['items']]) class PartialType(Type): """Type such as List[?] where type arguments are unknown, or partial None type. These are used for inferring types in multiphase initialization such as this: x = [] # x gets a partial type List[?], as item type is unknown x.append(1) # partial type gets replaced with normal type List[int] Or with None: x = None # x gets a partial type None if c: x = 1 # Infer actual type int for x """ # None for the 'None' partial type; otherwise a generic class type = None # type: Optional[mypy.nodes.TypeInfo] var = None # type: mypy.nodes.Var inner_types = None # type: List[Type] def __init__(self, type: Optional['mypy.nodes.TypeInfo'], var: 'mypy.nodes.Var', inner_types: List[Type]) -> None: self.type = type self.var = var self.inner_types = inner_types def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_partial_type(self) class EllipsisType(Type): """The type ... (ellipsis). This is not a real type but a syntactic AST construct, used in Callable[..., T], for example. A semantically analyzed type will never have ellipsis types. """ def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_ellipsis_type(self) def serialize(self) -> JsonDict: return {'.class': 'EllipsisType'} @classmethod def deserialize(self, data: JsonDict) -> 'EllipsisType': assert data['.class'] == 'EllipsisType' return EllipsisType() class TypeType(Type): """For types like Type[User]. This annotates variables that are class objects, constrained by the type argument. See PEP 484 for more details. We may encounter expressions whose values are specific classes; those are represented as callables (possibly overloaded) corresponding to the class's constructor's signature and returning an instance of that class. The difference with Type[C] is that those callables always represent the exact class given as the return type; Type[C] represents any class that's a subclass of C, and C may also be a type variable or a union (or Any). Many questions around subtype relationships between Type[C1] and def(...) -> C2 are answered by looking at the subtype relationships between C1 and C2, since Type[] is considered covariant. There's an unsolved problem with constructor signatures (also unsolved in PEP 484): calling a variable whose type is Type[C] assumes the constructor signature for C, even though a subclass of C might completely change the constructor signature. For now we just assume that users of Type[C] are careful not to do that (in the future we might detect when they are violating that assumption). """ # This can't be everything, but it can be a class reference, # a generic class instance, a union, Any, a type variable... item = None # type: Type def __init__(self, item: Type, *, line: int = -1) -> None: super().__init__(line) self.item = item def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_type_type(self) def serialize(self) -> JsonDict: return {'.class': 'TypeType', 'item': self.item.serialize()} @classmethod def deserialize(cls, data: JsonDict) -> 'TypeType': assert data['.class'] == 'TypeType' return TypeType(Type.deserialize(data['item'])) # # Visitor-related classes # class TypeVisitor(Generic[T]): """Visitor class for types (Type subclasses). The parameter T is the return type of the visit methods. """ def _notimplemented_helper(self, name: str) -> NotImplementedError: return NotImplementedError("Method {}.visit_{}() not implemented\n" .format(type(self).__name__, name) + "This is a known bug, track development in " + "'https://github.com/JukkaL/mypy/issues/730'") @abstractmethod def visit_unbound_type(self, t: UnboundType) -> T: pass def visit_type_list(self, t: TypeList) -> T: raise self._notimplemented_helper('type_list') def visit_error_type(self, t: ErrorType) -> T: raise self._notimplemented_helper('error_type') @abstractmethod def visit_any(self, t: AnyType) -> T: pass @abstractmethod def visit_void(self, t: Void) -> T: pass @abstractmethod def visit_none_type(self, t: NoneTyp) -> T: pass @abstractmethod def visit_uninhabited_type(self, t: UninhabitedType) -> T: pass def visit_erased_type(self, t: ErasedType) -> T: raise self._notimplemented_helper('erased_type') @abstractmethod def visit_deleted_type(self, t: DeletedType) -> T: pass @abstractmethod def visit_type_var(self, t: TypeVarType) -> T: pass @abstractmethod def visit_instance(self, t: Instance) -> T: pass @abstractmethod def visit_callable_type(self, t: CallableType) -> T: pass def visit_overloaded(self, t: Overloaded) -> T: raise self._notimplemented_helper('overloaded') @abstractmethod def visit_tuple_type(self, t: TupleType) -> T: pass def visit_star_type(self, t: StarType) -> T: raise self._notimplemented_helper('star_type') @abstractmethod def visit_union_type(self, t: UnionType) -> T: pass @abstractmethod def visit_partial_type(self, t: PartialType) -> T: pass def visit_ellipsis_type(self, t: EllipsisType) -> T: raise self._notimplemented_helper('ellipsis_type') @abstractmethod def visit_type_type(self, t: TypeType) -> T: pass class TypeTranslator(TypeVisitor[Type]): """Identity type transformation. Subclass this and override some methods to implement a non-trivial transformation. """ def visit_unbound_type(self, t: UnboundType) -> Type: return t def visit_type_list(self, t: TypeList) -> Type: return t def visit_error_type(self, t: ErrorType) -> Type: return t def visit_any(self, t: AnyType) -> Type: return t def visit_void(self, t: Void) -> Type: return t def visit_none_type(self, t: NoneTyp) -> Type: return t def visit_uninhabited_type(self, t: UninhabitedType) -> Type: return t def visit_erased_type(self, t: ErasedType) -> Type: return t def visit_deleted_type(self, t: DeletedType) -> Type: return t def visit_instance(self, t: Instance) -> Type: return Instance(t.type, self.translate_types(t.args), t.line) def visit_type_var(self, t: TypeVarType) -> Type: return t def visit_partial_type(self, t: PartialType) -> Type: return t def visit_callable_type(self, t: CallableType) -> Type: return t.copy_modified(arg_types=self.translate_types(t.arg_types), ret_type=t.ret_type.accept(self), variables=self.translate_variables(t.variables)) def visit_tuple_type(self, t: TupleType) -> Type: return TupleType(self.translate_types(t.items), cast(Any, t.fallback.accept(self)), t.line) def visit_star_type(self, t: StarType) -> Type: return StarType(t.type.accept(self), t.line) def visit_union_type(self, t: UnionType) -> Type: return UnionType(self.translate_types(t.items), t.line) def visit_ellipsis_type(self, t: EllipsisType) -> Type: return t def translate_types(self, types: List[Type]) -> List[Type]: return [t.accept(self) for t in types] def translate_variables(self, variables: List[TypeVarDef]) -> List[TypeVarDef]: return variables def visit_overloaded(self, t: Overloaded) -> Type: items = [] # type: List[CallableType] for item in t.items(): new = item.accept(self) if isinstance(new, CallableType): items.append(new) else: raise RuntimeError('CallableType expectected, but got {}'.format(type(new))) return Overloaded(items=items) def visit_type_type(self, t: TypeType) -> Type: return TypeType(t.item.accept(self), line=t.line) class TypeStrVisitor(TypeVisitor[str]): """Visitor for pretty-printing types into strings. This is mostly for debugging/testing. Do not preserve original formatting. Notes: - Represent unbound types as Foo? or Foo?[...]. - Represent the NoneTyp type as None. """ def visit_unbound_type(self, t: UnboundType)-> str: s = t.name + '?' if t.args != []: s += '[{}]'.format(self.list_str(t.args)) return s def visit_type_list(self, t: TypeList) -> str: return '<TypeList {}>'.format(self.list_str(t.items)) def visit_error_type(self, t: ErrorType) -> str: return '<ERROR>' def visit_any(self, t: AnyType) -> str: return 'Any' def visit_void(self, t: Void) -> str: return 'void' def visit_none_type(self, t: NoneTyp) -> str: # Fully qualify to make this distinct from the None value. return "builtins.None" def visit_uninhabited_type(self, t: UninhabitedType) -> str: return "<uninhabited>" def visit_erased_type(self, t: ErasedType) -> str: return "<Erased>" def visit_deleted_type(self, t: DeletedType) -> str: if t.source is None: return "<Deleted>" else: return "<Deleted '{}'>".format(t.source) def visit_instance(self, t: Instance) -> str: s = t.type.fullname() if t.type is not None else '<?>' if t.erased: s += '*' if t.args != []: s += '[{}]'.format(self.list_str(t.args)) return s def visit_type_var(self, t: TypeVarType) -> str: if t.name is None: # Anonymous type variable type (only numeric id). return '`{}'.format(t.id) else: # Named type variable type. return '{}`{}'.format(t.name, t.id) def visit_callable_type(self, t: CallableType) -> str: s = '' bare_asterisk = False for i in range(len(t.arg_types)): if s != '': s += ', ' if t.arg_kinds[i] == mypy.nodes.ARG_NAMED and not bare_asterisk: s += '*, ' bare_asterisk = True if t.arg_kinds[i] == mypy.nodes.ARG_STAR: s += '*' if t.arg_kinds[i] == mypy.nodes.ARG_STAR2: s += '**' if t.arg_names[i]: s += t.arg_names[i] + ': ' s += str(t.arg_types[i]) if t.arg_kinds[i] == mypy.nodes.ARG_OPT: s += ' =' s = '({})'.format(s) if not isinstance(t.ret_type, Void): s += ' -> {}'.format(t.ret_type) if t.variables: s = '{} {}'.format(t.variables, s) return 'def {}'.format(s) def visit_overloaded(self, t: Overloaded) -> str: a = [] for i in t.items(): a.append(i.accept(self)) return 'Overload({})'.format(', '.join(a)) def visit_tuple_type(self, t: TupleType) -> str: s = self.list_str(t.items) if t.fallback and t.fallback.type: fallback_name = t.fallback.type.fullname() if fallback_name != 'builtins.tuple': return 'Tuple[{}, fallback={}]'.format(s, t.fallback.accept(self)) return 'Tuple[{}]'.format(s) def visit_star_type(self, t: StarType) -> str: s = t.type.accept(self) return '*{}'.format(s) def visit_union_type(self, t: UnionType) -> str: s = self.list_str(t.items) return 'Union[{}]'.format(s) def visit_partial_type(self, t: PartialType) -> str: if t.type is None: return '<partial None>' else: return '<partial {}[{}]>'.format(t.type.name(), ', '.join(['?'] * len(t.type.type_vars))) def visit_ellipsis_type(self, t: EllipsisType) -> str: return '...' def visit_type_type(self, t: TypeType) -> str: return 'Type[{}]'.format(t.item.accept(self)) def list_str(self, a: List[Type]) -> str: """Convert items of an array to strings (pretty-print types) and join the results with commas. """ res = [] for t in a: if isinstance(t, Type): res.append(t.accept(self)) else: res.append(str(t)) return ', '.join(res) # These constants define the method used by TypeQuery to combine multiple # query results, e.g. for tuple types. The strategy is not used for empty # result lists; in that case the default value takes precedence. ANY_TYPE_STRATEGY = 0 # Return True if any of the results are True. ALL_TYPES_STRATEGY = 1 # Return True if all of the results are True. class TypeQuery(TypeVisitor[bool]): """Visitor for performing simple boolean queries of types. This class allows defining the default value for leafs to simplify the implementation of many queries. """ default = False # Default result strategy = 0 # Strategy for combining multiple values (ANY_TYPE_STRATEGY or ALL_TYPES_...). def __init__(self, default: bool, strategy: int) -> None: """Construct a query visitor. Use the given default result and strategy for combining multiple results. The strategy must be either ANY_TYPE_STRATEGY or ALL_TYPES_STRATEGY. """ self.default = default self.strategy = strategy def visit_unbound_type(self, t: UnboundType) -> bool: return self.default def visit_type_list(self, t: TypeList) -> bool: return self.default def visit_error_type(self, t: ErrorType) -> bool: return self.default def visit_any(self, t: AnyType) -> bool: return self.default def visit_void(self, t: Void) -> bool: return self.default def visit_uninhabited_type(self, t: UninhabitedType) -> bool: return self.default def visit_none_type(self, t: NoneTyp) -> bool: return self.default def visit_erased_type(self, t: ErasedType) -> bool: return self.default def visit_deleted_type(self, t: DeletedType) -> bool: return self.default def visit_type_var(self, t: TypeVarType) -> bool: return self.default def visit_partial_type(self, t: PartialType) -> bool: return self.default def visit_instance(self, t: Instance) -> bool: return self.query_types(t.args) def visit_callable_type(self, t: CallableType) -> bool: # FIX generics return self.query_types(t.arg_types + [t.ret_type]) def visit_tuple_type(self, t: TupleType) -> bool: return self.query_types(t.items) def visit_star_type(self, t: StarType) -> bool: return t.type.accept(self) def visit_union_type(self, t: UnionType) -> bool: return self.query_types(t.items) def visit_overloaded(self, t: Overloaded) -> bool: return self.query_types(t.items()) def visit_type_type(self, t: TypeType) -> bool: return t.item.accept(self) def query_types(self, types: Sequence[Type]) -> bool: """Perform a query for a list of types. Use the strategy constant to combine the results. """ if not types: # Use default result for empty list. return self.default if self.strategy == ANY_TYPE_STRATEGY: # Return True if at least one component is true. res = False for t in types: res = res or t.accept(self) if res: break return res else: # Return True if all components are true. res = True for t in types: res = res and t.accept(self) if not res: break return res def strip_type(typ: Type) -> Type: """Make a copy of type without 'debugging info' (function name).""" if isinstance(typ, CallableType): return typ.copy_modified(name=None) elif isinstance(typ, Overloaded): return Overloaded([cast(CallableType, strip_type(item)) for item in typ.items()]) else: return typ def replace_leading_arg_type(t: CallableType, self_type: Type) -> CallableType: """Return a copy of a callable type with a different self argument type. Assume that the callable is the signature of a method. """ return t.copy_modified(arg_types=[self_type] + t.arg_types[1:]) def is_named_instance(t: Type, fullname: str) -> bool: return (isinstance(t, Instance) and t.type is not None and t.type.fullname() == fullname) def copy_type(t: Type) -> Type: """ Build a copy of the type; used to mutate the copy with truthiness information """ return copy.copy(t) def true_only(t: Type) -> Type: """ Restricted version of t with only True-ish values """ if not t.can_be_true: # All values of t are False-ish, so there are no true values in it return UninhabitedType(line=t.line) elif not t.can_be_false: # All values of t are already True-ish, so true_only is idempotent in this case return t elif isinstance(t, UnionType): # The true version of a union type is the union of the true versions of its components new_items = [true_only(item) for item in t.items] return UnionType.make_simplified_union(new_items, line=t.line) else: new_t = copy_type(t) new_t.can_be_false = False return new_t def false_only(t: Type) -> Type: """ Restricted version of t with only False-ish values """ if not t.can_be_false: # All values of t are True-ish, so there are no false values in it return UninhabitedType(line=t.line) elif not t.can_be_true: # All values of t are already False-ish, so false_only is idempotent in this case return t elif isinstance(t, UnionType): # The false version of a union type is the union of the false versions of its components new_items = [false_only(item) for item in t.items] return UnionType.make_simplified_union(new_items, line=t.line) else: new_t = copy_type(t) new_t.can_be_true = False return new_t def true_or_false(t: Type) -> Type: """ Unrestricted version of t with both True-ish and False-ish values """ new_t = copy_type(t) new_t.can_be_true = type(new_t).can_be_true new_t.can_be_false = type(new_t).can_be_false return new_t
33.651911
99
0.6001
6,293
50,175
4.650564
0.091212
0.013155
0.015684
0.013668
0.383483
0.32478
0.250803
0.163671
0.143614
0.129263
0
0.002007
0.295007
50,175
1,490
100
33.674497
0.825347
0.216941
0
0.316969
0
0
0.057248
0
0
0
0
0.002013
0.023479
1
0.214514
false
0.018143
0.007471
0.109925
0.503735
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0b7ae0e628e0def3b7be3cd9371f36738267282e
260
py
Python
airtable/perform_request.py
jlouie95618/airtable-python
dafdbb2028bbf63a2a1c1daa3e8adf5db7d071bd
[ "MIT" ]
2
2015-09-20T13:43:05.000Z
2016-04-12T02:48:50.000Z
airtable/perform_request.py
jlouie95618/airtable-python
dafdbb2028bbf63a2a1c1daa3e8adf5db7d071bd
[ "MIT" ]
null
null
null
airtable/perform_request.py
jlouie95618/airtable-python
dafdbb2028bbf63a2a1c1daa3e8adf5db7d071bd
[ "MIT" ]
null
null
null
import requests def performRequest(): header = { 'Authorization': 'Bearer keyrpG4FPpEqZ0ubg'} r = requests.get('https://api.airtable.com/v0/app9uvKeuVL1pOfCD/Cuisines/recgruzSZ0BvRB63q', headers = header) print r print r.text performRequest()
28.888889
114
0.734615
27
260
7.074074
0.777778
0.062827
0
0
0
0
0
0
0
0
0
0.036036
0.146154
260
9
115
28.888889
0.824324
0
0
0
0
0
0.417625
0
0
0
0
0
0
0
null
null
0
0.142857
null
null
0.285714
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
3
0badd93e16eff8024db03e59cd8ff370d92844f5
415
py
Python
dropbox_problem/problem_8.py
loftwah/Daily-Coding-Problem
0327f0b4f69ef419436846c831110795c7a3c1fe
[ "MIT" ]
129
2018-10-14T17:52:29.000Z
2022-01-29T15:45:57.000Z
dropbox_problem/problem_8.py
loftwah/Daily-Coding-Problem
0327f0b4f69ef419436846c831110795c7a3c1fe
[ "MIT" ]
2
2019-11-30T23:28:23.000Z
2020-01-03T16:30:32.000Z
dropbox_problem/problem_8.py
loftwah/Daily-Coding-Problem
0327f0b4f69ef419436846c831110795c7a3c1fe
[ "MIT" ]
60
2019-02-21T09:18:31.000Z
2022-03-25T21:01:04.000Z
"""This problem was asked by Dropbox. Given a list of words, determine whether the words can be chained to form a circle. A word X can be placed in front of another word Y in a circle if the last character of X is same as the first character of Y. For example, the words ['chair', 'height', 'racket', touch', 'tunic'] can form the following circle: chair --> racket --> touch --> height --> tunic --> chair."""
51.875
84
0.703614
71
415
4.112676
0.591549
0.054795
0
0
0
0
0
0
0
0
0
0
0.192771
415
8
85
51.875
0.871642
0.985542
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
0baea31e34c0cc50f2feaf646fd4265f07656e22
870
py
Python
projects/ia-algorithms/states.py
ricktrovato/PyScientific
0d6b8ed40e79817ff37b3d3a77bf42bb16217e73
[ "MIT" ]
null
null
null
projects/ia-algorithms/states.py
ricktrovato/PyScientific
0d6b8ed40e79817ff37b3d3a77bf42bb16217e73
[ "MIT" ]
null
null
null
projects/ia-algorithms/states.py
ricktrovato/PyScientific
0d6b8ed40e79817ff37b3d3a77bf42bb16217e73
[ "MIT" ]
null
null
null
class State: def __init__(self, element = None): if element == None: # create initial state self.element = self.get_initial_state() else: self.element = element def get_initial_state(self): """ Este metodo retorna o estado incial da busca """ initial_state = "Default" return initial_state def successor_function(self, data): """ Esta é a função sucessora. Gera todo os possiveis elementes que podem ser alcançados a partir do estado atual. """ return data[self.element] def objective_function(self, objective): """ Este método verifica se o caminho está no estado objetivo """ # verifica que o element atual eh o carregamento return self.element == objective
27.1875
72
0.583908
97
870
5.113402
0.536082
0.110887
0.064516
0
0
0
0
0
0
0
0
0
0.348276
870
31
73
28.064516
0.87478
0.324138
0
0
0
0
0.014199
0
0
0
0
0.096774
0
1
0.307692
false
0
0
0
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
0
0
0
1
0
0
3
0bb1a4837654146a82ca092954d2ee4a129b663a
132
py
Python
src/general_utility/lib_util.py
se4u/mvlsa
19b91d190466b94b3eea72a6fcd43ac623b71a0e
[ "MIT" ]
12
2015-08-07T10:11:32.000Z
2021-04-16T02:42:58.000Z
src/general_utility/lib_util.py
se4u/mvlsa
19b91d190466b94b3eea72a6fcd43ac623b71a0e
[ "MIT" ]
1
2015-06-22T16:52:13.000Z
2015-06-22T16:52:13.000Z
src/general_utility/lib_util.py
se4u/mvlsa
19b91d190466b94b3eea72a6fcd43ac623b71a0e
[ "MIT" ]
6
2015-06-14T17:39:36.000Z
2021-04-16T02:42:59.000Z
def count_and_print(f, l): c=0 for e in l: f.write(e) f.write("\n") c+=1 f.close() return c
14.666667
26
0.439394
24
132
2.333333
0.666667
0.214286
0
0
0
0
0
0
0
0
0
0.025641
0.409091
132
8
27
16.5
0.692308
0
0
0
0
0
0.015152
0
0
0
0
0
0
1
0.125
false
0
0
0
0.25
0.125
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e7e374f2f6f65878955f87ae52d3ad7480eb984d
186
py
Python
tests/_support/namespacing.py
crazy-penguins/raft
3eb829f1c0d90608743cadac4c5a04017c93c607
[ "BSD-2-Clause" ]
null
null
null
tests/_support/namespacing.py
crazy-penguins/raft
3eb829f1c0d90608743cadac4c5a04017c93c607
[ "BSD-2-Clause" ]
null
null
null
tests/_support/namespacing.py
crazy-penguins/raft
3eb829f1c0d90608743cadac4c5a04017c93c607
[ "BSD-2-Clause" ]
null
null
null
from raft import Collection, task, call from package import module @task def top_pre(c): pass @task(call(top_pre)) def toplevel(c): pass ns = Collection(module, toplevel)
10.941176
39
0.704301
28
186
4.607143
0.535714
0.124031
0
0
0
0
0
0
0
0
0
0
0.198925
186
16
40
11.625
0.865772
0
0
0.222222
0
0
0
0
0
0
0
0
0
1
0.222222
false
0.222222
0.222222
0
0.444444
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
3
e7e79ace5dc23236a9f10589e8e5e659d94c8209
146
py
Python
dissector/apps.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
3
2019-05-12T21:11:53.000Z
2019-09-15T18:11:21.000Z
dissector/apps.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
21
2019-06-26T05:01:01.000Z
2022-03-11T23:47:21.000Z
dissector/apps.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
8
2019-06-13T08:51:12.000Z
2021-02-17T11:14:46.000Z
from django.apps import AppConfig class ClearLinuxDissectorConfig(AppConfig): name = 'dissector' verbose_name = 'Clear Linux Dissector'
20.857143
43
0.767123
15
146
7.4
0.8
0
0
0
0
0
0
0
0
0
0
0
0.164384
146
6
44
24.333333
0.909836
0
0
0
0
0
0.205479
0
0
0
0
0
0
1
0
false
0
0.25
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
3
e7f03ca24c5ea04812cc5ab1f2a3aaa50ea2f653
1,352
py
Python
t/02-run.py
jeffa/window-viewport
7eadeb24c08418473d9ab3e1c88770a6fef89487
[ "MIT" ]
null
null
null
t/02-run.py
jeffa/window-viewport
7eadeb24c08418473d9ab3e1c88770a6fef89487
[ "MIT" ]
null
null
null
t/02-run.py
jeffa/window-viewport
7eadeb24c08418473d9ab3e1c88770a6fef89487
[ "MIT" ]
null
null
null
import unittest from math import sin #import window.viewport from window.viewport import viewport class TestLoad(unittest.TestCase): def test_defaults(self): w2v = viewport( Wb = 0, Wt = 1, Wl = 0, Wr = 1, Vb = 9, Vt = 0, Vl = 0, Vr = 9 ) self.assertEqual( w2v.Dx(.5), 4.5, 'correct Dx()' ) self.assertEqual( int(w2v.Dy(.6)), 3, 'correct Dy()' ) x = 0 y = sin(x) self.assertEqual( int(w2v.Dx(x)), 0, 'correct Dx() sin wave 1/5' ) self.assertEqual( int(w2v.Dy(y)), 9, 'correct Dy() sin wave 1/5' ) x = 0.1 y = sin(x) self.assertEqual( int(w2v.Dx(x)), 0, 'correct Dx() sin wave 2/5' ) self.assertEqual( int(w2v.Dy(y)), 8, 'correct Dy() sin wave 2/5' ) x = 0.2 y = sin(x) self.assertEqual( int(w2v.Dx(x)), 1, 'correct Dx() sin wave 3/5' ) self.assertEqual( int(w2v.Dy(y)), 7, 'correct Dy() sin wave 3/5' ) x = 0.3 y = sin(x) self.assertEqual( int(w2v.Dx(x)), 2, 'correct Dx() sin wave 4/5' ) self.assertEqual( int(w2v.Dy(y)), 6, 'correct Dy() sin wave 4/5' ) x = 0.4 y = sin(x) self.assertEqual( int(w2v.Dx(x)), 3, 'correct Dx() sin wave 5/5' ) self.assertEqual( int(w2v.Dy(y)), 5, 'correct Dy() sin wave 5/5' ) if __name__ == '__main__': unittest.main()
33.8
88
0.54142
222
1,352
3.256757
0.198198
0.248963
0.273859
0.319502
0.452282
0.42047
0.42047
0.24758
0.24758
0.127248
0
0.066941
0.281805
1,352
39
89
34.666667
0.677652
0.016272
0
0.166667
0
0
0.21219
0
0
0
0
0
0.4
1
0.033333
false
0
0.1
0
0.166667
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e7f73de4c3b1206ddb084491790ac4e8d1dd724f
851
py
Python
StaticMethods/PopulationCorrelationCoefficient.py
KaranShah197/Statistical-Calculator
797d452b2934939353eb93a61b0ec7a4e5910c3d
[ "MIT" ]
null
null
null
StaticMethods/PopulationCorrelationCoefficient.py
KaranShah197/Statistical-Calculator
797d452b2934939353eb93a61b0ec7a4e5910c3d
[ "MIT" ]
null
null
null
StaticMethods/PopulationCorrelationCoefficient.py
KaranShah197/Statistical-Calculator
797d452b2934939353eb93a61b0ec7a4e5910c3d
[ "MIT" ]
null
null
null
from StaticMethods.Exceptions import exception from StaticMethods.CalulcateMean import calMean from StaticMethods.PopulationStandardDeviation import stddev from StaticMethods.addition import addition from StaticMethods.division import division from StaticMethods.multiplication import multiplication from StaticMethods.roundOff import roundOff from StaticMethods.subtraction import subtraction def calcPCC(xArray, yArray): xMean = calMean(xArray) yMean = calMean(yArray) length = len(xArray) xSd = stddev(xArray) ySd = stddev(xArray) total = 0 for i in range(0, length): total = addition(total, multiplication(division(xSd, subtraction(xMean, xArray[i])), division(ySd, subtraction(yMean, yArray[i])))) # total = subtraction(xMean, yArray[i]) res = division(length, total) return roundOff(res)
32.730769
139
0.761457
95
851
6.821053
0.336842
0.209877
0
0
0
0
0
0
0
0
0
0.002793
0.158637
851
25
140
34.04
0.902235
0.043478
0
0
0
0
0
0
0
0
0
0
0
1
0.052632
false
0
0.421053
0
0.526316
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
e7feee87b3264e9e085df60b9a9161b7a453d29c
322
py
Python
HLTrigger/Configuration/python/HLT_75e33/modules/hltEgammaGsfElectronsUnseeded_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:24:46.000Z
2021-11-30T16:24:46.000Z
HLTrigger/Configuration/python/HLT_75e33/modules/hltEgammaGsfElectronsUnseeded_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
4
2021-11-29T13:57:56.000Z
2022-03-29T06:28:36.000Z
HLTrigger/Configuration/python/HLT_75e33/modules/hltEgammaGsfElectronsUnseeded_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:16:05.000Z
2021-11-30T16:16:05.000Z
import FWCore.ParameterSet.Config as cms hltEgammaGsfElectronsUnseeded = cms.EDProducer("EgammaHLTPixelMatchElectronProducers", BSProducer = cms.InputTag("hltOnlineBeamSpot"), GsfTrackProducer = cms.InputTag("hltEgammaGsfTracksUnseeded"), TrackProducer = cms.InputTag(""), UseGsfTracks = cms.bool(True) )
35.777778
86
0.779503
25
322
10.04
0.72
0.131474
0
0
0
0
0
0
0
0
0
0
0.114907
322
8
87
40.25
0.880702
0
0
0
0
0
0.245342
0.192547
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0
1
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e7feff0ac2d1fa1d4e684383aac3b68beba895dd
251
py
Python
{{cookiecutter.repo_name}}/project/apps/main/views/__init__.py
DC23/simple-django-cookiecutter
8cb43f8f29aae5c237e94f7c9ceb706d239629eb
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/project/apps/main/views/__init__.py
DC23/simple-django-cookiecutter
8cb43f8f29aae5c237e94f7c9ceb706d239629eb
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/project/apps/main/views/__init__.py
DC23/simple-django-cookiecutter
8cb43f8f29aae5c237e94f7c9ceb706d239629eb
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Ignore unused imports warning # pylama: ignore=W0611 # You must import all views here from .index import IndexView from .er import ErView # Dev views, remove later from .debug import DebugView from .lorem import LoremView
19.307692
32
0.74502
36
251
5.194444
0.75
0
0
0
0
0
0
0
0
0
0
0.024155
0.175299
251
12
33
20.916667
0.879227
0.505976
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
f0025f721b30ca2ce633f4ee7f5a7c39b0186ca1
154
py
Python
tests/test_multi_group.py
astrojhgu/rt1d
cb49510ae9850d1491dcf9336e3994fb1b153438
[ "MIT" ]
null
null
null
tests/test_multi_group.py
astrojhgu/rt1d
cb49510ae9850d1491dcf9336e3994fb1b153438
[ "MIT" ]
null
null
null
tests/test_multi_group.py
astrojhgu/rt1d
cb49510ae9850d1491dcf9336e3994fb1b153438
[ "MIT" ]
null
null
null
""" test_multi_group.py Author: Jordan Mirocha Affiliation: University of Colorado at Boulder Created on: Sun Mar 24 01:04:54 2013 Description: """
11.846154
46
0.746753
23
154
4.913043
1
0
0
0
0
0
0
0
0
0
0
0.09375
0.168831
154
12
47
12.833333
0.789063
0.915584
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
f00df5f25030ac0a2b5538d5f3c23e0bea9b19d5
272
py
Python
nmd.py
gdmgent-1819-iot/labo1-nawatend
7c1ef2eb7119cafa42209b564f6cae2d42f836b0
[ "X11" ]
null
null
null
nmd.py
gdmgent-1819-iot/labo1-nawatend
7c1ef2eb7119cafa42209b564f6cae2d42f836b0
[ "X11" ]
null
null
null
nmd.py
gdmgent-1819-iot/labo1-nawatend
7c1ef2eb7119cafa42209b564f6cae2d42f836b0
[ "X11" ]
null
null
null
from sense_hat import SenseHat import random import time sense = SenseHat() while True: for i in ("N", "M","D"): c = (random.randint(1,256),random.randint(1,256),random.randint(1,256)) sense.show_letter(str(i),text_colour=c) time.sleep(1) time.sleep(2)
19.428571
75
0.676471
46
272
3.934783
0.565217
0.21547
0.232044
0.281768
0.281768
0.281768
0.281768
0.281768
0
0
0
0.061135
0.158088
272
14
76
19.428571
0.729258
0
0
0
0
0
0.010989
0
0
0
0
0
0
1
0
false
0
0.3
0
0.3
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
f01419050b178f3d53bc62df8d91f430e02178dd
5,180
py
Python
src/CIQS-CLI-Extension/cloudintelligencequickstart/models/__init__.py
Azure/CIQS-Azure-Cli-Extension
1203b3180f9d5a6db2ba443f437d115e996fb5be
[ "MIT" ]
1
2020-06-01T13:59:38.000Z
2020-06-01T13:59:38.000Z
src/CIQS-CLI-Extension/cloudintelligencequickstart/models/__init__.py
Azure/CIQS-Azure-Cli-Extension
1203b3180f9d5a6db2ba443f437d115e996fb5be
[ "MIT" ]
2
2018-06-02T00:06:53.000Z
2018-07-20T21:00:47.000Z
src/CIQS-CLI-Extension/cloudintelligencequickstart/models/__init__.py
Azure/CIQS-Azure-Cli-Extension
1203b3180f9d5a6db2ba443f437d115e996fb5be
[ "MIT" ]
2
2018-06-01T19:18:51.000Z
2021-01-10T10:56:29.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .microsoft_ciqs_models_gallery_person import MicrosoftCiqsModelsGalleryPerson from .microsoft_ciqs_models_gallery_resource_provider import MicrosoftCiqsModelsGalleryResourceProvider from .microsoft_ciqs_models_gallery_guide import MicrosoftCiqsModelsGalleryGuide from .microsoft_ciqs_models_gallery_try_it_now import MicrosoftCiqsModelsGalleryTryItNow from .microsoft_ciqs_models_gallery_content import MicrosoftCiqsModelsGalleryContent from .microsoft_ciqs_models_gallery_estimated_cost import MicrosoftCiqsModelsGalleryEstimatedCost from .microsoft_ciqs_models_gallery_link import MicrosoftCiqsModelsGalleryLink from .microsoft_ciqs_models_gallery_regex_entry import MicrosoftCiqsModelsGalleryRegexEntry from .microsoft_ciqs_models_error_info import MicrosoftCiqsModelsErrorInfo from .microsoft_ciqs_models_gallery_parameter import MicrosoftCiqsModelsGalleryParameter from .microsoft_ciqs_models_provisioning_steps_provisioning_step import MicrosoftCiqsModelsProvisioningStepsProvisioningStep from .microsoft_ciqs_models_provisioning_steps_azure_resource_group import MicrosoftCiqsModelsProvisioningStepsAzureResourceGroup from .microsoft_ciqs_models_provisioning_steps_azure_resource_list import MicrosoftCiqsModelsProvisioningStepsAzureResourceList from .microsoft_ciqs_models_provisioning_steps_aad_application import MicrosoftCiqsModelsProvisioningStepsAadApplication from .microsoft_ciqs_models_provisioning_steps_delete_azure_entities import MicrosoftCiqsModelsProvisioningStepsDeleteAzureEntities from .microsoft_ciqs_models_gallery_summary import MicrosoftCiqsModelsGallerySummary from .microsoft_ciqs_models_gallery_extended_property import MicrosoftCiqsModelsGalleryExtendedProperty from .microsoft_ciqs_models_gallery_template import MicrosoftCiqsModelsGalleryTemplate from .microsoft_ciqs_models_email_parameter import MicrosoftCiqsModelsEmailParameter from .microsoft_ciqs_models_email_template import MicrosoftCiqsModelsEmailTemplate from .microsoft_ciqs_models_gallery_offer_plan import MicrosoftCiqsModelsGalleryOfferPlan from .microsoft_ciqs_models_deployment_deployment import MicrosoftCiqsModelsDeploymentDeployment from .microsoft_ciqs_models_gallery_function_definition import MicrosoftCiqsModelsGalleryFunctionDefinition from .microsoft_ciqs_models_deployment_create_deployment_request import MicrosoftCiqsModelsDeploymentCreateDeploymentRequest from .microsoft_ciqs_models_deployment_provisioning_log import MicrosoftCiqsModelsDeploymentProvisioningLog from .microsoft_ciqs_models_deployment_deployment_provisioning_step import MicrosoftCiqsModelsDeploymentDeploymentProvisioningStep from .microsoft_ciqs_models_deployment_deployment_details import MicrosoftCiqsModelsDeploymentDeploymentDetails from .system_nullable_system_net_http_status_code import SystemNullableSystemNetHttpStatusCode from .microsoft_ciqs_models_deployment_deployment_provisioning_step_deployment_provisioning_step_hidden_properties import MicrosoftCiqsModelsDeploymentDeploymentProvisioningStepDeploymentProvisioningStepHiddenProperties from .microsoft_ciqs_api_models_execute_provisioning_step_response import MicrosoftCiqsApiModelsExecuteProvisioningStepResponse from .microsoft_ciqs_api_models_delete_deployment_result import MicrosoftCiqsApiModelsDeleteDeploymentResult __all__ = [ 'MicrosoftCiqsModelsGalleryPerson', 'MicrosoftCiqsModelsGalleryResourceProvider', 'MicrosoftCiqsModelsGalleryGuide', 'MicrosoftCiqsModelsGalleryTryItNow', 'MicrosoftCiqsModelsGalleryContent', 'MicrosoftCiqsModelsGalleryEstimatedCost', 'MicrosoftCiqsModelsGalleryLink', 'MicrosoftCiqsModelsGalleryRegexEntry', 'MicrosoftCiqsModelsErrorInfo', 'MicrosoftCiqsModelsGalleryParameter', 'MicrosoftCiqsModelsProvisioningStepsProvisioningStep', 'MicrosoftCiqsModelsProvisioningStepsAzureResourceGroup', 'MicrosoftCiqsModelsProvisioningStepsAzureResourceList', 'MicrosoftCiqsModelsProvisioningStepsAadApplication', 'MicrosoftCiqsModelsProvisioningStepsDeleteAzureEntities', 'MicrosoftCiqsModelsGallerySummary', 'MicrosoftCiqsModelsGalleryExtendedProperty', 'MicrosoftCiqsModelsGalleryTemplate', 'MicrosoftCiqsModelsEmailParameter', 'MicrosoftCiqsModelsEmailTemplate', 'MicrosoftCiqsModelsGalleryOfferPlan', 'MicrosoftCiqsModelsDeploymentDeployment', 'MicrosoftCiqsModelsGalleryFunctionDefinition', 'MicrosoftCiqsModelsDeploymentCreateDeploymentRequest', 'MicrosoftCiqsModelsDeploymentProvisioningLog', 'MicrosoftCiqsModelsDeploymentDeploymentProvisioningStep', 'MicrosoftCiqsModelsDeploymentDeploymentDetails', 'SystemNullableSystemNetHttpStatusCode', 'MicrosoftCiqsModelsDeploymentDeploymentProvisioningStepDeploymentProvisioningStepHiddenProperties', 'MicrosoftCiqsApiModelsExecuteProvisioningStepResponse', 'MicrosoftCiqsApiModelsDeleteDeploymentResult', ]
70.958904
219
0.883591
346
5,180
12.739884
0.320809
0.088476
0.115699
0.146098
0.232305
0.09755
0.050817
0.050817
0
0
0
0.000206
0.061004
5,180
72
220
71.944444
0.906044
0.058108
0
0
1
0
0.271757
0.271757
0
0
0
0
0
1
0
false
0
0.484375
0
0.484375
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
f0159487a3a208ba68c8a303eea3ea7840eec52c
1,883
py
Python
xquant/engine/commission.py
wbpyer/wbpyer
43ec15ce55994766a7c2948f353aeb205a774008
[ "MIT" ]
2
2019-10-16T11:09:08.000Z
2021-02-23T01:37:52.000Z
xquant/engine/commission.py
wbpyer/wbpyer
43ec15ce55994766a7c2948f353aeb205a774008
[ "MIT" ]
null
null
null
xquant/engine/commission.py
wbpyer/wbpyer
43ec15ce55994766a7c2948f353aeb205a774008
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Commission 佣金+费税模型 New in V0.3.4 @author: @version: 0.4 """ from abc import ABCMeta, abstractmethod import math class Commission(object): """ 佣金和费税 """ __metaclass__ = ABCMeta @abstractmethod def get_commission(self): raise NotImplementedError("Should implement get_commission()!") class ZeroCommission(Commission): """ 无费率 """ def get_commission(self): return 0.0 def __repr__(self): return "{class_name}".format(class_name=self.__class__.__name__) class PerShareCommission(Commission): """ 基于交易份额(或称数量)计算手续费,一般是上交所的过户费,每1000股收费1元 """ def __init__(self, rate=0.001, min_comm=0.0): self.rate_per_share = rate self.min_comm = min_comm def get_commission(self, quantity): return max(math.ceil(quantity * self.rate_per_share), self.min_comm) def __repr__(self): return "{class_name}(rate_per_share={rate}, min_commission={min_comm})".format( class_name=self.__class__.__name__, rate=self.rate_per_share, min_comm=self.min_comm) class PerMoneyCommission(Commission): """ 基于交易花费(trade cost)计算手续费,可以是期货点数或者人民币,允许设置最小手续费 """ def __init__(self, rate=1.5e-4, min_comm=0.0): """ 例如买焦合约共计10000点(单份合约*数量),默认费率万分1.5,则交易成本是1.5个点 参数: rate: 单边费率 min_comm: 最低手续费,默认为股票5元 """ self.rate_per_money = float(rate) self.min_comm = float(min_comm) def get_commission(self, full_cost): return max(full_cost * self.rate_per_money, self.min_comm) def __repr__(self): return "{class_name}(rate_per_money={rate}, min_commission={min_comm})".format( class_name=self.__class__.__name__, rate=self.rate_per_money, min_comm=self.min_comm) class PerTradeCommission(Commission): """ 基于交易次数计算手续费 """ pass
23.835443
97
0.65693
235
1,883
4.86383
0.331915
0.091864
0.057743
0.069991
0.328959
0.328959
0.194226
0.194226
0.194226
0.194226
0
0.023129
0.219331
1,883
78
98
24.141026
0.754422
0.144981
0
0.15625
0
0
0.114865
0.082432
0
0
0
0
0
1
0.28125
false
0.03125
0.0625
0.1875
0.71875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
f02c92f2dcbc7590e749bce523e634fee163add1
136
py
Python
data/IdeKey.py
gringofe/ulauncher-jetbrains-reloaded
7b5e0ae8de89bc486ed6b479bdbcd12689168507
[ "MIT" ]
null
null
null
data/IdeKey.py
gringofe/ulauncher-jetbrains-reloaded
7b5e0ae8de89bc486ed6b479bdbcd12689168507
[ "MIT" ]
null
null
null
data/IdeKey.py
gringofe/ulauncher-jetbrains-reloaded
7b5e0ae8de89bc486ed6b479bdbcd12689168507
[ "MIT" ]
null
null
null
""" Contains IdeKey type """ from typing import Literal IdeKey = Literal["clion", "idea", "phpstorm", "pycharm", "rider", "webstorm"]
22.666667
77
0.669118
15
136
6.066667
0.866667
0
0
0
0
0
0
0
0
0
0
0
0.139706
136
5
78
27.2
0.777778
0.147059
0
0
0
0
0.342593
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
f04a6e3e29fcd33e65d5c849f0ffb87ee4c5aa33
114
py
Python
Desafio16.py
sergioboff/Desafios-Curso-em-Video
f876396635b12c00bdd9523758364bbebfd70ae0
[ "MIT" ]
null
null
null
Desafio16.py
sergioboff/Desafios-Curso-em-Video
f876396635b12c00bdd9523758364bbebfd70ae0
[ "MIT" ]
null
null
null
Desafio16.py
sergioboff/Desafios-Curso-em-Video
f876396635b12c00bdd9523758364bbebfd70ae0
[ "MIT" ]
null
null
null
import math num = float (input('Digite um numero Real: ')) print ('O número inteiro é {}'.format(math.floor(num)))
38
55
0.692982
18
114
4.388889
0.888889
0
0
0
0
0
0
0
0
0
0
0
0.131579
114
3
55
38
0.79798
0
0
0
0
0
0.382609
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0.333333
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
f0553277b94344e5efba24dda486ea85a03637fc
521
py
Python
utest/application/plugins_for_loader/plugin_module.py
crylearner/RIDE3X
767f45b0c908f18ecc7473208def8dc7489f43b0
[ "ECL-2.0", "Apache-2.0" ]
1
2017-08-20T14:46:02.000Z
2017-08-20T14:46:02.000Z
utest/application/plugins_for_loader/plugin_module.py
crylearner/RIDE3X
767f45b0c908f18ecc7473208def8dc7489f43b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
utest/application/plugins_for_loader/plugin_module.py
crylearner/RIDE3X
767f45b0c908f18ecc7473208def8dc7489f43b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
from robotide.pluginapi import Plugin class ExamplePlugin1(Plugin): def __init__(self, application): Plugin.__init__(self, application) class ExamplePlugin2(Plugin): def __init__(self, application): Plugin.__init__(self, application) def turn_off(self, name): self._get_plugin_by_name(name).disable() def _get_plugin_by_name(self, name): for p in self.get_plugins(): if p.name == name: return p return None
22.652174
49
0.6238
60
521
4.983333
0.416667
0.107023
0.254181
0.113712
0.354515
0.354515
0.354515
0.354515
0.354515
0
0
0.005405
0.289827
521
22
50
23.681818
0.802703
0
0
0.285714
0
0
0
0
0
0
0
0
0
1
0.285714
false
0
0.071429
0
0.642857
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
b2b4fcaa06e9b8bf37d56b53f8e4d205e960bc6c
2,507
py
Python
tests.py
sandeep-gh/tailwind-tags
2ba139efada7e7c58daf74d624a39fdc494816cb
[ "MIT" ]
null
null
null
tests.py
sandeep-gh/tailwind-tags
2ba139efada7e7c58daf74d624a39fdc494816cb
[ "MIT" ]
null
null
null
tests.py
sandeep-gh/tailwind-tags
2ba139efada7e7c58daf74d624a39fdc494816cb
[ "MIT" ]
null
null
null
from tailwind_tags import * import tailwind_tags as tt #res = get_styReport(text/gray/6, mr/sb/2, mr/x/auto, W/6, G/cols/6) from addict import Dict #res = get_styReport(mr/4) res = tstr(sw/pink/"600/80") # r = fw.normal #pd/5 # resize/x/5 # res = r.keyvaleval() print(res) # dictionary from class name to abbrv used in # styval_dict = Dict() # for varn in dir(): # try: # module = getattr(tt, varn) # styval_dict[module.__name__] = varn # except: # pass # def styreport_resolvekv(key, val): # """ # resolve json expression of type : key'ObjectPosition': {'_val': 't'}} # """ # if key in styval_dict: # abbrv = styval_dict[key] # return f"{abbrv}.{val['_val']}" # elif '_val' in val: # return f"{key}/{val['_val']}" # elif '_color' in val: # colstr = val._color._val # cc, cv = colstr.replace("00", ""). split( # "-") # gray-400 --> gray, 400" # return f"{key}/{cc}/{cv}" # elif len(val.items()) == 1: # case: pd/x/4==> pd {'x': {'_val': '4'}} # [k, v] = list(val.items())[0] # return f"{key}/{k}/{v._val}" # else: # print("unable to resolve ", key, val, len(val.items())) # raise ValueError # def styreport_resolve(styreport): # """ # styreport: a dictionary # """ # res = [] # for k, v in styreport.items(): # if '_val' in v or '_color' in v or len(v.items()) == 1: # res.append(styreport_resolvekv(k, v)) # else: # print("no resolved ", k, v) # raise ValueError # res.append(*res.passthrough) # return res # clss = tstr(tbl.fixed, bds.collapse, bds.separate) # print(clss) # print(tstr(opacity/40)) # print(tstr(pink/4)) # print(tstr(offset/pink/4)) # clss = tstr(ring/offset/pink/4) # print(clss) # exp = mr/x/auto # res = exp.evaluate() # print(res) # clss = tstr(ring/offset/pink/4, duration/5, resize/5, ring/5) # print(clss) # clss = tstr(bd/st/5, bg/pink/5, ph/opacity/5, text/opacity/5) # print(clss) # clss = tstr(min/H/5) # print(clss) # print(tstr(container)) # print(tstr(W/5)) # print("scale = ", tstr(space/5, space/x/5)) # print("spacing = ", tstr(mr/x/5)) # print("spacing = ", tstr(mr/5)) # print(tstr(space/5)) # print(tstr(mr/sl/4)) # print(tstr(*[fz.xl, bg/gray/8, fc/gray/6, ta.center, bt.bd, # bdr.md, pd/1, shdw.md, mr/2, js.center, hover(bg/pink/4)])) # print(tstr(bg/"transparent")) # print(tstr(bd/2))
24.821782
76
0.561627
373
2,507
3.705094
0.348525
0.065123
0.021708
0.026049
0.088278
0.062229
0
0
0
0
0
0.027168
0.236538
2,507
100
77
25.07
0.69488
0.884324
0
0
0
0
0.028037
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0.2
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
b2d15d46979068deb6da2400371f8a30f44103ea
479
py
Python
count_bits.py
DemetriusStorm/100daysofcode
ce87a596b565c5740ae3c48adac91cba779b3833
[ "MIT" ]
null
null
null
count_bits.py
DemetriusStorm/100daysofcode
ce87a596b565c5740ae3c48adac91cba779b3833
[ "MIT" ]
null
null
null
count_bits.py
DemetriusStorm/100daysofcode
ce87a596b565c5740ae3c48adac91cba779b3833
[ "MIT" ]
null
null
null
""" Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case """ def count_bits(n): return sum([int(n) for n in bin(n)[2:]]) print(count_bits(0)) print(count_bits(4)) print(count_bits(7)) print(count_bits(9)) print(count_bits(10))
28.176471
115
0.749478
86
479
4.104651
0.593023
0.152975
0.1983
0.141643
0
0
0
0
0
0
0
0.05679
0.154489
479
16
116
29.9375
0.814815
0.617954
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
0.142857
0.285714
0.714286
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
0
1
0
3
b2d849ba980442faadf31ce9d66914db758ef67a
174
py
Python
andrew_li_django_website/andrew_site/settings/dev.py
Zeyu-Li/django_login
88d0b71e780e71c8f94ce9555192598c07c128b6
[ "MIT" ]
1
2019-06-05T17:11:00.000Z
2019-06-05T17:11:00.000Z
andrew_li_django_website/andrew_site/settings/dev.py
Zeyu-Li/django_ecommerse_app_deprecated
88d0b71e780e71c8f94ce9555192598c07c128b6
[ "MIT" ]
2
2019-05-31T17:14:14.000Z
2019-06-05T17:04:37.000Z
andrew_li_django_website/andrew_site/settings/dev.py
Zeyu-Li/django_ecommerse_app_deprecated
88d0b71e780e71c8f94ce9555192598c07c128b6
[ "MIT" ]
2
2019-05-22T17:44:52.000Z
2019-06-07T17:35:30.000Z
from andrew_site.settings.base import * # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a0oe6rx_q$6_or^+jw1zvw+uxq_t1+xn08#3&kd19p$4#hniyt'
34.8
66
0.787356
30
174
4.4
0.9
0.136364
0
0
0
0
0
0
0
0
0
0.070968
0.109195
174
4
67
43.5
0.780645
0.367816
0
0
0
0
0.462963
0.462963
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
b2e44c9bc71c86c0f942c6a1dc7e6e28a8bb9bce
312
py
Python
Task2/03_personal-info.py
telecomprofi/Cisco-DevOps-MDP-02
f44173d468319a90dc6b7c5ea92cd6b8b3762b45
[ "Apache-2.0" ]
null
null
null
Task2/03_personal-info.py
telecomprofi/Cisco-DevOps-MDP-02
f44173d468319a90dc6b7c5ea92cd6b8b3762b45
[ "Apache-2.0" ]
null
null
null
Task2/03_personal-info.py
telecomprofi/Cisco-DevOps-MDP-02
f44173d468319a90dc6b7c5ea92cd6b8b3762b45
[ "Apache-2.0" ]
null
null
null
#03_personal-info.py space= " " firstName = input("What is your first name?") lastName = input("What is your last name?") location = input("What is your location?") age = input("What is your age?") print("Hi "+ firstName + space + lastName +"! Your location is "+ location + " and you are "+age + " years old!")
39
113
0.669872
46
312
4.521739
0.5
0.173077
0.211538
0.288462
0
0
0
0
0
0
0
0.007722
0.169872
312
7
114
44.571429
0.795367
0.060897
0
0
0
0
0.455479
0
0
0
0
0
0
1
0
false
0
0
0
0
0.166667
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
b2ec8d45c198c1263c6122c6bbec3944de9c6d70
814
py
Python
release/stubs.min/System/Runtime/InteropServices/__init___parts/GuidAttribute.py
tranconbv/ironpython-stubs
a601759e6c6819beff8e6b639d18a24b7e351851
[ "MIT" ]
null
null
null
release/stubs.min/System/Runtime/InteropServices/__init___parts/GuidAttribute.py
tranconbv/ironpython-stubs
a601759e6c6819beff8e6b639d18a24b7e351851
[ "MIT" ]
null
null
null
release/stubs.min/System/Runtime/InteropServices/__init___parts/GuidAttribute.py
tranconbv/ironpython-stubs
a601759e6c6819beff8e6b639d18a24b7e351851
[ "MIT" ]
null
null
null
class GuidAttribute: """ Supplies an explicit System.Guid when an automatic GUID is undesirable. GuidAttribute(guid: str) """ def ZZZ(self): """hardcoded/mock instance of the class""" return GuidAttribute() instance=ZZZ() """hardcoded/returns an instance of the class""" def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,guid): """ __new__(cls: type,guid: str) """ pass Value=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the System.Guid of the class. Get: Value(self: GuidAttribute) -> str """
30.148148
215
0.681818
104
814
4.875
0.423077
0.029586
0.059172
0.112426
0.22288
0.22288
0.22288
0.22288
0.22288
0.22288
0
0
0.179361
814
26
216
31.307692
0.758982
0.455774
0
0.2
0
0
0
0
0
0
0
0
0
1
0.3
false
0.2
0
0
0.7
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
3
6511870d964056cf9883e3513ab19e3622715a7d
2,280
py
Python
ijson/backends/yajl2_c.py
simonw/ijson
f2ed122298a24b748f7a7f3c5dd197bba16b4421
[ "BSD-3-Clause" ]
394
2019-06-20T08:24:38.000Z
2022-03-31T23:20:51.000Z
ijson/backends/yajl2_c.py
simonw/ijson
f2ed122298a24b748f7a7f3c5dd197bba16b4421
[ "BSD-3-Clause" ]
67
2019-08-02T07:18:05.000Z
2022-03-16T13:47:00.000Z
ijson/backends/yajl2_c.py
simonw/ijson
f2ed122298a24b748f7a7f3c5dd197bba16b4421
[ "BSD-3-Clause" ]
34
2019-07-20T01:05:20.000Z
2022-03-19T07:32:05.000Z
# # Contributed by Rodrigo Tobar <rtobar@icrar.org> # # ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2016 # Copyright by UWA (in the framework of the ICRAR) # ''' Wrapper for _yajl2 C extension module ''' from ijson import common, compat, utils from . import _yajl2 _get_buf_size = lambda kwargs: kwargs.pop('buf_size', 64 * 1024) @utils.coroutine def basic_parse_basecoro(target, **kwargs): return _yajl2.basic_parse_basecoro(target.send, **kwargs) def basic_parse_gen(file, **kwargs): f = compat.bytes_reader(file) buf_size = _get_buf_size(kwargs) return _yajl2.basic_parse(f, buf_size, **kwargs) def basic_parse_async(file, **kwargs): buf_size = _get_buf_size(kwargs) return _yajl2.basic_parse_async(file, buf_size, **kwargs) @utils.coroutine def parse_basecoro(target, **kwargs): return _yajl2.parse_basecoro(target.send, **kwargs) def parse_gen(file, **kwargs): f = compat.bytes_reader(file) buf_size = _get_buf_size(kwargs) return _yajl2.parse(f, buf_size, **kwargs) def parse_async(file, **kwargs): buf_size = _get_buf_size(kwargs) return _yajl2.parse_async(file, buf_size, **kwargs) @utils.coroutine def kvitems_basecoro(target, prefix, map_type=None, **kwargs): return _yajl2.kvitems_basecoro(target.send, prefix, map_type, **kwargs) def kvitems_gen(file, prefix, map_type=None, **kwargs): f = compat.bytes_reader(file) buf_size = _get_buf_size(kwargs) return _yajl2.kvitems(f, buf_size, prefix, map_type, **kwargs) def kvitems_async(file, prefix, map_type=None, **kwargs): buf_size = _get_buf_size(kwargs) return _yajl2.kvitems_async(file, buf_size, prefix, map_type, **kwargs) @utils.coroutine def items_basecoro(target, prefix, map_type=None, **kwargs): return _yajl2.items_basecoro(target.send, prefix, map_type, **kwargs) def items_gen(file, prefix, map_type=None, **kwargs): f = compat.bytes_reader(file) buf_size = _get_buf_size(kwargs) return _yajl2.items(f, buf_size, prefix, map_type, **kwargs) def items_async(file, prefix, map_type=None, **kwargs): buf_size = _get_buf_size(kwargs) return _yajl2.items_async(file, buf_size, prefix, map_type, **kwargs) common.enrich_backend(globals())
32.112676
75
0.738596
333
2,280
4.753754
0.195195
0.114972
0.128869
0.065698
0.756159
0.753001
0.630449
0.630449
0.497789
0.366393
0
0.012251
0.140789
2,280
70
76
32.571429
0.795814
0.107456
0
0.363636
0
0
0.003958
0
0
0
0
0
0
1
0.272727
false
0
0.045455
0.090909
0.590909
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
651bd23a3c52dcbfe68daf8b4db86845bba58f38
21
py
Python
tests/pydecompile-test/decompiler-baselines/string_length.py
jaydeetay/pxt
aad1beaf15edc46e1327806367298cbc942dcbc1
[ "MIT" ]
977
2019-05-06T23:12:55.000Z
2022-03-29T19:11:44.000Z
tests/pydecompile-test/decompiler-baselines/string_length.py
jaydeetay/pxt
aad1beaf15edc46e1327806367298cbc942dcbc1
[ "MIT" ]
3,980
2019-05-09T20:48:14.000Z
2022-03-28T20:33:07.000Z
tests/pydecompile-test/decompiler-baselines/string_length.py
jaydeetay/pxt
aad1beaf15edc46e1327806367298cbc942dcbc1
[ "MIT" ]
306
2016-04-09T05:28:07.000Z
2019-05-02T14:23:29.000Z
x = "Okay" y = len(x)
10.5
10
0.47619
5
21
2
0.8
0
0
0
0
0
0
0
0
0
0
0
0.238095
21
2
11
10.5
0.625
0
0
0
0
0
0.181818
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
653e7b7882a6cac5af67e615cf5bad865f704e16
178
py
Python
src/dp/rest_api/v1/parsers/input/ratings/__init__.py
Michalesko/DP_API
73e27bf0bb06330d7903977d8cd4d1fdb57afaec
[ "MIT" ]
null
null
null
src/dp/rest_api/v1/parsers/input/ratings/__init__.py
Michalesko/DP_API
73e27bf0bb06330d7903977d8cd4d1fdb57afaec
[ "MIT" ]
null
null
null
src/dp/rest_api/v1/parsers/input/ratings/__init__.py
Michalesko/DP_API
73e27bf0bb06330d7903977d8cd4d1fdb57afaec
[ "MIT" ]
null
null
null
# coding: utf-8 __author__ = 'Miso' from postRateParser import post_user_rate_parser from postRatesParser import UserIntialRatingParser from getRateParser import get_rate_parser
29.666667
50
0.865169
22
178
6.590909
0.727273
0.137931
0
0
0
0
0
0
0
0
0
0.00625
0.101124
178
6
51
29.666667
0.9
0.073034
0
0
0
0
0.02439
0
0
0
0
0
0
1
0
false
0
0.75
0
0.75
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
e8f829a0799e8f426890fdf8a375f16c04472ba9
1,540
py
Python
software/pynguin/pynguin/generation/stoppingconditions/maxtimestoppingcondition.py
se2p/artifact-pynguin-ssbse2020
32b5f4d27ef1b81e5c541471e98fa6e50f5ce8a6
[ "CC-BY-4.0" ]
3
2020-08-20T10:27:13.000Z
2021-11-02T20:28:16.000Z
software/pynguin/pynguin/generation/stoppingconditions/maxtimestoppingcondition.py
se2p/artifact-pynguin-ssbse2020
32b5f4d27ef1b81e5c541471e98fa6e50f5ce8a6
[ "CC-BY-4.0" ]
null
null
null
software/pynguin/pynguin/generation/stoppingconditions/maxtimestoppingcondition.py
se2p/artifact-pynguin-ssbse2020
32b5f4d27ef1b81e5c541471e98fa6e50f5ce8a6
[ "CC-BY-4.0" ]
null
null
null
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pynguin. If not, see <https://www.gnu.org/licenses/>. """Provides a stopping condition that stops the search after a predefined amount of time.""" import time import pynguin.configuration as config from pynguin.generation.stoppingconditions.stoppingcondition import StoppingCondition class MaxTimeStoppingCondition(StoppingCondition): """Stop search after a predefined amount of time.""" def __init__(self): self._max_seconds = config.INSTANCE.budget self._start_time = 0 def limit(self) -> int: return self._max_seconds def is_fulfilled(self) -> bool: current_time = time.time_ns() return (current_time - self._start_time) / 1_000_000_000 > self._max_seconds def reset(self) -> None: self._start_time = time.time_ns() def set_limit(self, limit: int) -> None: self._max_seconds = limit def iterate(self) -> None: pass
34.222222
85
0.727273
219
1,540
4.990868
0.502283
0.025618
0.051235
0.05215
0.153705
0.153705
0.124428
0
0
0
0
0.009724
0.198701
1,540
44
86
35
0.876013
0.507143
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0.055556
0.166667
0.055556
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
3
3313582f0f4661e2168dd42d59a04ef8e197b715
127
py
Python
PBO_19188/Latihan4.1.list1.py
Fazlur9/PBO
357b739c0c20ed2aa0c3cc58d48bbae843e9e946
[ "MIT" ]
null
null
null
PBO_19188/Latihan4.1.list1.py
Fazlur9/PBO
357b739c0c20ed2aa0c3cc58d48bbae843e9e946
[ "MIT" ]
null
null
null
PBO_19188/Latihan4.1.list1.py
Fazlur9/PBO
357b739c0c20ed2aa0c3cc58d48bbae843e9e946
[ "MIT" ]
null
null
null
list1_int=[1,2,3,4,5,6] list_string=['info 1', 'info 2', 'info 3'] list_string=["PBO", "pemrograman web", "Grafika Komputer"]
42.333333
58
0.661417
23
127
3.521739
0.695652
0.246914
0
0
0
0
0
0
0
0
0
0.087719
0.102362
127
3
58
42.333333
0.622807
0
0
0
0
0
0.412698
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
3319a400d91fa0653e4e0b83d6ce2a48f79d23f9
524
py
Python
common/utils.py
jakubrachwalski/PriceAlertService
820e724feaded12c365de97df3d8ad887e680b50
[ "MIT" ]
null
null
null
common/utils.py
jakubrachwalski/PriceAlertService
820e724feaded12c365de97df3d8ad887e680b50
[ "MIT" ]
null
null
null
common/utils.py
jakubrachwalski/PriceAlertService
820e724feaded12c365de97df3d8ad887e680b50
[ "MIT" ]
null
null
null
__author__ = 'Jakub Rachwalski' import re from passlib.hash import pbkdf2_sha512 class Utils: @staticmethod def email_is_valid(email: str) -> bool: EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+") return True if EMAIL_REGEX.match(email) else False @staticmethod def hash_password(password: str) -> str: return pbkdf2_sha512.hash(password) @staticmethod def check_hashed_passwords(password: str, hashed: str) -> bool: return pbkdf2_sha512.verify(password, hashed)
24.952381
67
0.675573
63
524
5.396825
0.52381
0.105882
0.105882
0
0
0
0
0
0
0
0
0.028846
0.206107
524
20
68
26.2
0.788462
0
0
0.214286
0
0
0.064886
0
0
0
0
0
0
1
0.214286
false
0.357143
0.142857
0.142857
0.642857
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
1
0
0
0
3
331d95f22dc19ad473b1d8cf36307d7554931d28
1,011
py
Python
proud/unification/interface.py
RemuLang/proud
8e833863a0cc915d8c6e588aa812b1c6d1842347
[ "MIT" ]
16
2020-01-13T12:36:33.000Z
2022-02-18T16:08:50.000Z
proud/unification/interface.py
RemuLang/proud
8e833863a0cc915d8c6e588aa812b1c6d1842347
[ "MIT" ]
5
2020-01-14T01:28:34.000Z
2020-01-20T12:43:26.000Z
proud/unification/interface.py
RemuLang/proud
8e833863a0cc915d8c6e588aa812b1c6d1842347
[ "MIT" ]
1
2022-02-18T16:08:54.000Z
2022-02-18T16:08:54.000Z
from proud.unification.type_encode import * from proud.unification.tc_make import make from contextlib import contextmanager import typing as t class TCState: def __init__(self): make(self) def push_level(self) -> Level: raise NotImplementedError def new_var(self, *props, Var=None, **kwargs) -> Var: raise NotImplementedError def user_var(self, *props, Var=None, **kwargs) -> Var: """ create a tv, which can be treated as a closed one for all levels """ raise NotImplementedError def occur_in(self, var: T, ty: T) -> bool: raise NotImplementedError def inst(self, maybepoly: T, rigid=False) -> t.Tuple[t.Dict[T, Var], T]: raise NotImplementedError def infer(self, ty: T) -> T: raise NotImplementedError def unify(self, lhs: T, rhs: T) -> None: raise NotImplementedError def extract_row(self, rowt: Row) -> t.Optional[t.Dict[str, T]]: raise NotImplementedError
26.605263
76
0.641939
130
1,011
4.907692
0.453846
0.30094
0.296238
0.047022
0.087774
0.087774
0.087774
0
0
0
0
0
0.256182
1,011
37
77
27.324324
0.848404
0.063304
0
0.347826
0
0
0
0
0
0
0
0
0
1
0.391304
false
0
0.173913
0
0.608696
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
33293300412a4b98d1b9aac44eb4a06f676bf52f
10,879
py
Python
AoC20/day_03/__init__.py
a-recknagel/AoC20
7aa0013dc745bdc0ad357e1168b212bd065fd092
[ "MIT" ]
null
null
null
AoC20/day_03/__init__.py
a-recknagel/AoC20
7aa0013dc745bdc0ad357e1168b212bd065fd092
[ "MIT" ]
null
null
null
AoC20/day_03/__init__.py
a-recknagel/AoC20
7aa0013dc745bdc0ad357e1168b212bd065fd092
[ "MIT" ]
null
null
null
class Coord(tuple): def __add__(self, other): if isinstance(other, Coord) and len(self) == len(other): return Coord(i+j for i, j in zip(self, other)) def trees(inp, step: tuple): step = Coord(step) current = step while current[0] < len(inp): yield inp[current[0]][current[1] % len(inp[0])] == "#" current += step example_data = """\ ..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#\ """ data = """\ ....#.#..#.#.#.#......#....##.# ..##..#.#..#.##.....#.....#.... ....#..#...#..#..####.##.#.##.. ...............#.....##..##..#. ##...####..##.#..#...####...#.# ..#.#....##....##.........#...# .#..#.##..............#.....### ##..##..#.....#..#...#....#.... .#.........#..#...#.#.#.....#.. ......#...#..#.##..#.....#.#... .#...#.#.#.##.##.....###...#... ..........#.......#...#....#..# .....##..#.#...#...##.##....... ...#.###.#.#..##...#.#......... ###.###....#...###.#.##...#.... ...........#....#.....##....### #..#.......#.....#.....##....#. .##.#....#...#....#......#..##. ..#....#..#..#......#.......... #..#.........#.#....#.##...#.#. #....#.#.......#.#.#.#.......#. .#....#....#..##.##.#....#.#... ............#....#.#.#........# #..#..#.....#....#.##.##.#....# ....#......#..##..#....#...#... .............#.##....####...##. #.##..##..##.#.....#........... #.#...#......####.##..#.#...... .......#.#..#...#.#.###.......# #..#..........#...#....#....... ###...#.....#....#...#..#...#.. ...##..#.#.....#..#..#...#.#.## #.......#......##...##......#.. .....#..#.....#......#.....##.. ..#.....###......#.#..###....#. ....##........#...##.#..#..#... #...#.##...##..#####...##..##.. ...#.#.#.#.....#.#.........##.. .............#......#..##...#.. .#..#...##....#......#......#.. #.....#...##......#............ .#.#....##.#.#..##..#####..##.. ..#..#.....#..#.##..#.#......## .......#...#...#..#..##.#..##.. ...#.##....#....#..#..#..#..... .....#......#.....#.....#..#.#. ..........#####.#..#....##...## ....#...#...#....#.......#..... #.......#........#.##.####..### .#........#...##...#.....#....# ...#.............#........#.#.# ..##........#..##..##.##...#.#. ......##......#####.........##. ...##.....#.#.##....#####...... .#.#........####.......#.#....# .....#..#.#.#.......##...#...#. .....####.#...#.#..#...#..#...# #..#.....#...#..#..#.#....#..#. .....#.......#..#.##..#.#.....# .......#..##..###......#....... .......##.#.##..##.#.###...##.. ..#.....#.....#....##.##.#..#.# ###.#...#..##..#....#.#.#..#.#. #...#.#.........##........#.... #...#.#..###.....###..##....... .....##..#.#...#.....#....#...# ##...##..#.#.#..#.#.##..#....## .#.......#.#.........#.##..#... ....##.#............###.#...##. #.....##.###.#..#....##.....#.. ....#.#......##.####....#....#. .....#......##.#...#....##.#... ##...#.............#...#....... ..#..#......#.#..#..#.....###.. ....#...#.#...#...#.....#..###. .....#.......#....#...#...#...# ..####......#.#..###........... ..........#....###.#.#.....###. #.............#...#..#.###.#..# .......#...#.#.#.#...##...#..#. ...#.#..#..#...###.#.#......... #.###.#..#...#..#....#..#.#.... ...#.#.##..#...#.#......###.##. .##..#..##..#.....##.##....#.## ..##.........####.............. .#.#..###...#.........#...##.#. ....##.........#.........##...# ...#.#.......#..#...###.#.##.#. ..#....###......#.##........... .......#...#.....#.#..#.#...#.. .##..#...#..#...#..#...#.#..##. .##...#..##..##.#.#...##....... .#.##.#...#..#..#..........#.#. #.#.#...#......##...##..##..... .##..#............#.##....#.#.. .##.........##..#.....#...#...# ##.#.#.#.#...#.....##....##.#.. #..##......#..##.........#.#... ...#....#.#.#.##.....##........ ...#...#...#.##.#.#.#..#..#.... .......#..#.......##...#....##. #.....#.#......#.......#.##.#.# .##..#.....#.....#.#####.#....# ......#.#....#..............##. ##..#...........#.#.#.......#.. ..##...###...#.#.........#....# ..##..#.#....##.....#.#.......# ....###...#.###....###.......#. ..#.#.....#..#..#...........##. .###..#.#........#..#.....##.#. #.##........###.#..#.....#....# .#.#.....#.#.#..#...##.#...#... #.#.#...#.#........#..##..##... ..#.##....###.#.......#.#.#.... .....#...##...................# #..####.....###.#..........#... #.##.........###.#........#..#. ..##........#.......#..###..#.# ##..##..#.#..#..#.....#.#..#... ....#......#....#...#.#.#..##.# .##....#.##.#.#..###..#......## ###....###.##....##......###..# .##....#..###..##..#.###...##.. .#.......##..##.............##. .###..#.....#.....#.#.#..#...## ......##.###.#........#..#..... #####.....##.#.#...#...#.#.#... ##..##.####...##....#...#.#...# .#.##...#...#..#............... ##.##.#..#........#...#........ ..#.##.#....#...#.#.###..#....# .......#.#..#.....##.#.#...#.#. ..#.##...#...#......#...#.#.#.. .##.......##......#.....#...... .#....................#.#...### ..#.....#..##.#......##..#....# .....#.#...#...........#.#...## ...#..#....#.#..#.......#..#..# .#..#.#...#.#.#.....###........ .#.#.....#..#.##..#.#..##...... ..##..#..#.....###.##..#.....## .#..#.#...#.....#..#......##.#. .##.##.#.#.#.#.#...###..##...#. ......#.##.#..#.##.#...#.#..#.# ..#.....#.##....#......#..#.... .#.....#..###.............#...# .#.....#...#...#.#.#.#..#.#.... .#.....#......##.....#...#.#..# .#.#......##...#......#......#. ##....#...#..##.#...#..#....... ....#.#......#.##...#.........# #.#.##.#..#......#....#.......# .#..#.##..#..#........#.#...#.. ..#..#.#.#...#....#...#..#..### ....#....#..#......#..........# #.....#.......#..#....#.#.#..#. ....#.#..###.#.....#.####...... ##.#.#....##.#.#........#..#..# #.#...#...#.#...##..#.#..#.#... ##.#......###.##.......#..#.... #..#...#.......##....#.###..... .####.##....#..#..####.#....#.# #...#.#..#..................... ..###..#...##.....##........... ..#....#...###.#.........##.##. ......#.....#....#.#....##...## #..#.....#...#..##.....#....#.# ..#.#..#....##...###.#..##....# #....#..#..#..#.##.##.....#...# ......#.#..#..##.#.....#.#..### .....##...##..#...##..#...#.... ##....#...#..#...##..#...###..# .##.####..#......#.#..#.##....# ..###........###..#....##.#.... ...#.....##...##..##..##..#.... .#..#.#..##..#..#..##.....#...# ##.#..##...#..#...........##... ....#..#..###.....#....#..#..## ......##..#....##........#.#.## .#.##....##.#......#..##..#..## .....##.#..#.#.##.##.##..#...#. .#..##.#.....#####...#......... ....#....#...#..##.#.#..##...#. ...#..#...#............#..#.... ....#.#.#.##....##.###..#.#.... .........#...###.........#..#.# ...........#...##.#..#.#.#..#.. #..#.###..#.#..#..##.....#....# .#.#....#.#....#............... ...#.#..#.#..##.#.#.#.......#.. .#......#...#.####......#..#... ..##..#.#...#..#.......###..... .#.....#.#..##....##.####.##.#. .............##.#.#.....#..#.#. #.....##.#...#.#.#.######.##... .##...........#..#..##.####.... #.#............#....#.........# ..#.##.##.#..#....##....#..#.## #...#.##..##.##.#.....##.#....# ##.#..##.###..#.#.#..........#. ...##...#..#...#.#.#.###.###... #.....##......#...#.#...#...... #.#.#.#.#.#...#..#....###...#.. ...##.#...#.......#..#...##.#.. ..#..#..##.....#......##...###. .............#.##...#.#.###..#. ..#.#.....##..#.##..#...##..#.. ..#...#.##..###..........#..#.. #.##.##...###...........#....#. #.....##...#.#..............#.. ##..##.....#...#..####.#...##.. ...........#......##.###..####. #...#..##.##.######.....#.....# #.##.........##.#.#....##...#.. .##.#.......###.#.....#.....### ###.#.#.#.#.#.##......#..#..#.# ....#.###...#....#.##...##.##.. ....#..#.....#.#.#..#..##.#.... ....#..#..#.....#.#..##........ ..........#..##..##......##..#. #...##.......#...##.#...###..#. ..#.#.##.....##....#..#.##...#. .#.#.....#.......##.....##...#. #......#.........#.#.........#. .......#...##......#.........#. ..##..........#....#..#.......# .......#............#..#.#...#. #..#....#.#..#....##..#........ ....#..###.##..#.#..#.##..###.. ....###............##.#....#.#. ..#..#.##...#....#..####...#... ..#....#...#...##...#.#.#..#... ..#.........#.#.......#........ .........##.##.#..#.#...#.#..## #.....#.#....##.#####.......##. .#..#....#......#.##..#....#... ........#....#...........#...#. .......#......#..........#..##. .###.#......#..#.##..#...#.#... .....#..#..###...........#...#. ..#...##....###......#....#.... ...#.#..#.#.#......#.##.###.#.# .##....#...#..#.#..#........#.. ......##.###...##.#.#.........# .#...#..####..#.#..##........#. #..#...#..#..#.#...#..##...#..# ..###...###....#.#.#.##....#..# .#.#....#.#.#......##....#..#.# ##.#.#.####....#........#....#. ...#......#........#........... #.#............##......#.##.... ..##.#...#.....#.#..#.#..#.#.#. #.......##.....##...#.#.#...### ............#..#..#....#......# .#.##...###...#...###..#....... ...............#....#...#.#.#.. #..##..##.###...#..##...#.#.##. ..#..#.......#.##......#..#..#. #.....#............#......#...# .###.##......##.#...#.#.##..#.. .#..##..#..#..#.............#.. #...#...##..##........#........ ...#........#..###...........#. #.#..#.#...................#.## #...#.#..#.......##...###..#.#. ..####......#....#.#....#..#..# ....#...........#...#..#....... ...#..#....#.#.##...#.#.#.#.... #...##.#.##..#.......#.....#... .##....#...#.#....#....#.#...#. ##.#...#.#...##..#..##...##..#. #..#.#.........#.......#....... .....##.....#..#......##....#.# .###...##.#.#.#....#....#....#. #.#.#.............#.#..#....... #.......#..............#...#.## .#.#...#....#.........###...#.# ..##..###..#...#...#.#....##..# .#..#.#...#..#.....#....#..##.. ##.......##....#....###..#.#..# #.#.#####..........#.#...##..## ......#..#..#...#...##...#....# #..#......#...#...#..###....... ...####.....#.......#.#...##.#. ......#..#.....##..#........... #........#..#...#.....#...#.#.. ..#.....#..#......#.#.#.....#.. ..#.........#..##...#...#...#.. ##..##......#.........#........ ..#..#....#.##.#....###.#..#.## ..##..#..#.......###....#..#... ...#.#...#.....####.#.......... ........#..#..#.#.....#........ ...##..........#.#.#.....#..#.. ..#....#.......#............... .#..#.#.#.##..#..#.....#....... #.##.#.#..#..............#..... .#.#..#.....##..##....##.....#. .##.#..#........##.##...##..... #....##..#............#....#... ...............##.#...#..#..... ..#..##.##...#.#.....#......... .##..#.#.#.##.....#.#.#..#..##. ......#####.#...#..........##.. ..........##.##...#.....#.#.... ..##......#..#.###..#...#.##... .#...........#.....#.#........# .#...#................#......#. #...#.#..##.#####..##....#..... ...##...##..#.#..........#..... ##............#......##..##...# ###.#.......#..#...#..#..#...#. .#..##.....###.#.#............# ##.###.#.........#.......#.#..# ...#..##..#.....#.......#...... ......#.#..#.....##..#..##..... ...#........##..###.#....#..#.. ..#...##.##....#.##..###......# ..#...#.....#.####.....#...#.## ..........##....###..#...#####. ....#.#.#.#.#.##.............## .#.#.#.##......#......#....#.#. .##...##....#...#....#..###.#.#\ """
30.818697
64
0.020866
56
10,879
3.964286
0.482143
0.081081
0
0
0
0
0
0
0
0
0
0.000383
0.040537
10,879
353
65
30.818697
0.020885
0
0
0.005747
0
0
0.962776
0.920404
0
0
0
0
0
1
0.005747
false
0
0
0
0.011494
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
335ae3fec517e98135873e1648ce37ac4db01573
497
py
Python
greedypermutation/vizpoint.py
siddharthsheth/greedypermutation
a9637830c3f65250a1aa02480a381cfea2f64b90
[ "MIT" ]
6
2020-12-10T10:47:43.000Z
2021-11-04T15:37:04.000Z
greedypermutation/vizpoint.py
siddharthsheth/greedypermutation
a9637830c3f65250a1aa02480a381cfea2f64b90
[ "MIT" ]
2
2021-09-01T17:24:07.000Z
2021-09-01T17:24:14.000Z
greedypermutation/vizpoint.py
siddharthsheth/greedypermutation
a9637830c3f65250a1aa02480a381cfea2f64b90
[ "MIT" ]
2
2021-07-31T11:15:06.000Z
2021-09-02T17:33:41.000Z
from ds2viz.element import Circle class VizPoint(Circle): def __init__(self, x, y, radius = 1): super().__init__(radius) self.x, self.y = x, y self.align('center', (x,y)) def __iter__(self): yield self.x yield self.y def dist(self, other): return sum((a-b) ** 2 for a,b in zip(self, other)) ** (0.5) def __eq__(self, other): return list(self) == list(other) def __hash__(self): return hash((self.x, self.y))
23.666667
67
0.56338
74
497
3.513514
0.459459
0.076923
0.069231
0.076923
0
0
0
0
0
0
0
0.014085
0.285714
497
20
68
24.85
0.71831
0
0
0
0
0
0.012072
0
0
0
0
0
0
1
0.333333
false
0
0.066667
0.2
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
3362bac76293e635222932492e38a885869ea7c0
86
py
Python
Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py
djgoku/RosettaCodeData
91df62d46142e921b3eacdb52b0316c39ee236bc
[ "Info-ZIP" ]
null
null
null
Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py
djgoku/RosettaCodeData
91df62d46142e921b3eacdb52b0316c39ee236bc
[ "Info-ZIP" ]
null
null
null
Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py
djgoku/RosettaCodeData
91df62d46142e921b3eacdb52b0316c39ee236bc
[ "Info-ZIP" ]
null
null
null
>>> print ( '\n'.join(''.join(x) for x in zip('abc', 'ABC', '123')) ) aA1 bB2 cC3 >>>
14.333333
69
0.488372
15
86
2.8
0.8
0
0
0
0
0
0
0
0
0
0
0.084507
0.174419
86
5
70
17.2
0.507042
0
0
0
0
0
0.127907
0
0
0
0
0
0
0
null
null
0
0
null
null
0.2
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
3
6828ca5e75a65b2d836dce8fde97303e4f0ad4b4
326
py
Python
Aperture/ApertureSquare.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
null
null
null
Aperture/ApertureSquare.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
null
null
null
Aperture/ApertureSquare.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
null
null
null
""" Represents a square aperture. """ from BeamlineComponents.Aperture.ApertureRectangle import ApertureRectangle class ApertureSquare(ApertureRectangle): def __init__(self, side_length): AperatureRectangle.__init__(self, side_length, side_length) def sideLength(self): return self.lengthVertical()
25.076923
75
0.766871
31
326
7.709677
0.612903
0.125523
0.100418
0.150628
0
0
0
0
0
0
0
0
0.150307
326
12
76
27.166667
0.862816
0.088957
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0.166667
0.166667
0.833333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
6843f206645cbb5b5599a4ccf84ae2f1e16e715e
11,305
py
Python
src/deep_dialog/nlu/evaltest.py
aaivu/aaivu-task-oriented-conversational-agent
99e4caf5b6d44c57b38a661dc176b76ed869b051
[ "Apache-2.0" ]
2
2021-02-18T19:03:06.000Z
2021-05-05T12:28:59.000Z
src/deep_dialog/nlu/evaltest.py
aaivu/aaivu-task-oriented-conversational-agent
99e4caf5b6d44c57b38a661dc176b76ed869b051
[ "Apache-2.0" ]
null
null
null
src/deep_dialog/nlu/evaltest.py
aaivu/aaivu-task-oriented-conversational-agent
99e4caf5b6d44c57b38a661dc176b76ed869b051
[ "Apache-2.0" ]
3
2020-12-07T13:59:36.000Z
2021-01-07T02:19:39.000Z
import csv, numpy import pandas as pd from math import isnan from rasa.test import get_evaluation_metrics from pipeline_ensemble import test_stack_pipelines, test_pipelines from pipeline_ensemble_preprocessing import DictComparison # itargets = ('greeting', 'greeting', 'greeting', 'confirm_answer', 'deny', 'deny', 'thanks', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'ticket', 'moviename', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'greeting', 'confirm_answer', 'deny', 'deny', 'thanks', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'ticket', 'moviename', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'greeting', 'confirm_answer', 'deny', 'thanks', 'thanks', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'ticket', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'confirm_answer', 'confirm_answer', 'deny', 'thanks', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'ticket', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'confirm_answer', 'deny', 'deny', 'thanks', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'ticket', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime') # ipredictions = ('greeting', 'nlu_fallback', 'greeting', 'deny', 'deny', 'deny', 'greeting', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'nlu_fallback', 'inform', 'nlu_fallback', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'nlu_fallback', 'starttime', 'nlu_fallback', 'nlu_fallback', 'theater', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'nlu_fallback', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'inform', 'deny', 'nlu_fallback', 'deny', 'nlu_fallback', 'inform', 'theater', 'inform', 'inform', 'nlu_fallback', 'inform', 'inform', 'theater', 'theater', 'ticket', 'theater', 'theater', 'ticket', 'nlu_fallback', 'nlu_fallback', 'nlu_fallback', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'date', 'theater+starttime', 'theater+starttime', 'nlu_fallback', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'greeting', 'greeting', 'nlu_fallback', 'nlu_fallback', 'greeting', 'nlu_fallback', 'ticket', 'inform', 'nlu_fallback', 'inform', 'nlu_fallback', 'inform', 'nlu_fallback', 'nlu_fallback', 'theater', 'theater', 'theater', 'ticket', 'inform', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'date', 'starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'theater+starttime', 'starttime', 'greeting', 'greeting', 'deny', 'nlu_fallback', 'deny', 'thanks', 'inform', 'greeting', 'nlu_fallback', 'inform', 'inform', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'nlu_fallback', 'nlu_fallback', 'moviename', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'nlu_fallback', 'nlu_fallback', 'date', 'date', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'theater+starttime', 'date+starttime', 'date+starttime', 'date+starttime', 'greeting', 'greeting', 'nlu_fallback', 'inform', 'deny', 'nlu_fallback', 'inform', 'inform', 'inform', 'inform', 'nlu_fallback', 'inform', 'inform', 'inform', 'theater', 'theater', 'theater', 'theater', 'theater', 'ticket', 'nlu_fallback', 'theater', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'starttime', 'nlu_fallback', 'starttime', 'theater+starttime', 'theater+starttime', 'theater', 'nlu_fallback', 'date+starttime', 'date+starttime') df = pd.read_csv("nlu\\data\\test_data.csv") sentences = df.Sentence.to_list() itargets = df.intent.to_list() def get_target_entities(): target_entities = [] for index, row in df.iterrows(): extracted_entities = {} try: if type(row.entity_value_1) is not float: extracted_entities[row.entity_name_1] = row.entity_value_1 if type(row.entity_value_2) is not float: extracted_entities[row.entity_name_2] = row.entity_value_2 if type(row.entity_value_3) is not float: extracted_entities[row.entity_name_3] = row.entity_value_3 except ValueError: pass finally: target_entities.append(extracted_entities) return target_entities target_entities = get_target_entities() single_models = [ "stack_models\\pipelines\\config_1.yml\\nlu-20201118-182926.tar.gz", "stack_models\\pipelines\\config_2.yml\\nlu-20201118-183729.tar.gz", "stack_models\\pipelines\\config_3.yml\\nlu-20201119-020428.tar.gz", "stack_models\\pipelines\\config_4.yml\\nlu-20201119-023646.tar.gz", "stack_models\\pipelines\\config_5.yml\\nlu-20201119-030659.tar.gz", "stack_models\\pipelines\\config_7.yml\\nlu-20201119-152018.tar.gz", "stack_models\\pipelines\\config_8.yml\\nlu-20201119-124504.tar.gz", "stack_models\\pipelines\\config_9.yml\\nlu-20201119-130525.tar.gz", ] # ipredictions_intent,ipredictions_entities = test_pipelines(sentences, single_models[2]) ipredictions_intent, ipredictions_entities = test_stack_pipelines( sentences, "results\\stack_reports\\with_entity5.csv", trim_count=1, ) # print(ipredictions_entities) # print(len(ipredictions_intent), len(itargets)) # get_evaluation_metrics(itargets, ipredictions_intent) # targets = [{'theater': 'liberty'}, {'numberofpeople': '4', 'date': 'tomorrow'}, {'moviename': 'infinity war', 'starttime': '4.30 p.m.'}, {'numberofpeople': '3', 'moviename': 'Zootopia'}, {'genre': 'comedy', 'city': 'nyc'}, {'moviename': 'Deadpool ', 'city': 'hamilton'}, {'numberofpeople': '3', 'moviename': 'batman'}, {'moviename': 'zootopis'}, {'moviename': 'batman vs superman'}, {}, {'theater': 'amc pacific place 11'}, {'moviename': "brother's grimsby", 'theater': 'emagine ', 'city': 'Portland'}, {'numberofpeople': '4', 'city': 'chicago'}, {'moviename': 'Foxtrot', 'city': 'seattle'}, {'city': 'nyc'}, {'city': 'san francisco'}, {'moviename': 'batman', 'city': 'miami'}, {'city': 'dallas'}, {}, {'starttime': '10'}, {'genre': 'action', 'date': 'tomorrow'}, {'starttime': 'before 12pm'}, {}, {}, {}, {}, {'video_format': '3d', 'moviename': 'Avengers', 'city': 'atlanta'}, {'city': 'nyc'}, {'moviename': 'DeadPool'}, {'starttime': 'DONT CARE'}, {'starttime': '4.00 pm', 'moviename': 'Antman', 'numberofpeople': '2'}, {}, {'numberofpeople': '3', 'moviename': 'batman'}, {'numberofpeople': '7', 'moviename': 'magnificent', 'starttime': '8.00 pm'}, {}, {}, {}, {}, {'moviename': 'Black swan'}, {}, {}, {'moviename': 'bird box', 'city': 'portland'}, {'moviename': 'quiet place', 'starttime': '12.00 pm', 'theater': 'los angeles'}, {}, {'theater': 'liberty'}, {}, {'starttime': '8.00 pm', 'date': 'tomorrow'}, {'starttime': 'DONT CARE'}, {'moviename': 'Dealpool', 'theater': 'liberty'}, {}, {}, {}, {}, {}, {}, {}, {}, {'genre': 'horror', 'city': 'san francisco'}, {}, {}, {'video_format': '3d'}, {}, {'numberofpeople': '2', 'theater': 'emagine'}, {'date': 'tomorrow'}, {}, {'starttime': '4 p.m.'}, {}, {}, {}, {'moviename': 'avengers'}] # predictions =[{'state': 'liberty', 'theater': 'liberty', 'city': 'liberty', 'distanceconstraints': 'liberty'}, {'numberofpeople': '4 people', 'date': 'tomorrow', 'moviename': '4 people'}, {'moviename': 'infinity war'}, {'numberofpeople': '3', 'moviename': 'zootopia'}, {'genre': 'comedy', 'city': 'nyc'}, {'moviename': 'Deadpool', 'city': 'hamilton'}, {'numberofpeople': '3', 'moviename': 'batman', 'city': 'los angeles', 'state': 'angeles'}, {'moviename': 'zootopis'}, {'numberofpeople': '8', 'moviename': 'superman'}, {}, {'theater_chain': 'amc', 'theater': 'place 11', 'moviename': 'amc pacific', 'city': 'amc pacific', 'date': '11'}, {'moviename': "the brother's grimsby", 'theater': 'emagine', 'city': 'Portland'}, {'numberofpeople': '4 people', 'city': 'chicago', 'moviename': 'people'}, {'moviename': 'Foxtrot', 'city': 'seattle'}, {'city': 'nyc'}, {'city': 'san francisco'}, {'city': 'miami', 'moviename': 'batman', 'video_format': 'batman'}, {'city': 'dallas'}, {}, {'city': 'nyc', 'starttime': '10', 'zip': '10', 'date': '10'}, {'date': 'tomorrow', 'genre': 'action'}, {'starttime': 'before12pm'}, {}, {'critic_rating': 'Good'}, {}, {}, {'video_format': '3d Avengers', 'moviename': 'Avengers', 'city': 'atlanta'}, {'city': 'nyc'}, {'moviename': 'DeadPool'}, {'theater': 'any'}, {'numberofpeople': '2'}, {}, {'numberofpeople': '3', 'moviename': '3'}, {'numberofpeople': 'magnificent', 'moviename': 'magnificent', 'starttime': 'pm'}, {}, {'date': 'me', 'distanceconstraints': 'me'}, {}, {}, {'moviename': 'the'}, {}, {}, {'moviename': 'bird', 'theater': 'box moive', 'city': 'portland'}, {'starttime': '12:00 pm', 'city': 'los angeles', 'closing': 'see', 'theater': 'place', 'distanceconstraints': 'place', 'state': 'angeles'}, {'closing': 'Bye', 'critic_rating': 'nice', 'moviename': 'work'}, {'state': 'liberty', 'theater': 'liberty', 'city': 'liberty'}, {'critic_rating': 'good'}, {'date': 'tomorrow', 'theater': 'pm', 'starttime': 'pm'}, {}, {'moviename': 'liberty', 'theater': 'liberty'}, {}, {}, {}, {}, {}, {}, {'critic_rating': 'Good'}, {}, {'genre': 'horror', 'city': 'san francisco', 'moviename': 'san francisco'}, {'distanceconstraints': 'time'}, {}, {'video_format': '3d'}, {}, {'numberofpeople': '2', 'theater': 'emagine', 'numberofkids': '2'}, {'date': 'tomorrow'}, {}, {'numberofpeople': '4', 'starttime': '4'}, {}, {}, {'genre': 'kids'}, {'moviename': 'avengers'}] # print("len",len(target_entities),len(ipredictions_entities)) dict_comparison = DictComparison( target_entities, ipredictions_entities, out_file_path="results\\stack_entity_reports\\entity_result.txt", )
163.84058
2,519
0.650951
1,167
11,305
6.190231
0.161954
0.129568
0.153239
0.154485
0.589009
0.540421
0.446844
0.40144
0.370432
0.322398
0
0.019314
0.102344
11,305
68
2,520
166.25
0.69255
0.824326
0
0
0
0
0.319838
0.319838
0
0
0
0
0
1
0.021739
false
0.021739
0.130435
0
0.173913
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
684bc947e67c6297809b3d5495d48bf7b4801a78
742
py
Python
tdb/interface.py
KEVINYZY/tdb
df6b34f7a149914126f0f2c70ab74c2bc2e78723
[ "Apache-2.0" ]
1,527
2015-12-13T21:10:42.000Z
2022-02-20T00:11:57.000Z
tdb/interface.py
afcarl/tdb
5e78b5dbecf78b6d28eb2f5b67decf8d1f1eb17d
[ "Apache-2.0" ]
14
2015-12-29T02:54:04.000Z
2018-02-18T07:10:45.000Z
tdb/interface.py
afcarl/tdb
5e78b5dbecf78b6d28eb2f5b67decf8d1f1eb17d
[ "Apache-2.0" ]
184
2015-12-14T18:47:26.000Z
2021-07-09T10:24:43.000Z
""" top-level interface methods so user doesn't need to directly construct a dbsession """ import debug_session # default session _dbsession=None def debug(evals,feed_dict=None,breakpoints=None,break_immediately=False,session=None): """ spawns a new debug session """ global _dbsession _dbsession=debug_session.DebugSession(session) return _dbsession.run(evals,feed_dict,breakpoints,break_immediately) def s(): """ step to the next node in the execution order """ global _dbsession return _dbsession.s() def c(): """ continue """ global _dbsession return _dbsession.c() def get_exe_queue(): global _dbsession return _dbsession.get_exe_queue() def get_value(node): global _dbsession return _dbsession.get_value(node)
19.025641
86
0.769542
101
742
5.415842
0.465347
0.137112
0.153565
0.219378
0.120658
0
0
0
0
0
0
0
0.132075
742
39
87
19.025641
0.849379
0.242588
0
0.277778
0
0
0
0
0
0
0
0
0
1
0.277778
false
0
0.055556
0
0.611111
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
684e83ed2754494b0b9937bd8413948661e593bd
128
py
Python
06 - Decisions/example1.py
gyratory/NPTfP3
7e070e2e7a01cd2b750914719f71476fe1efcf4d
[ "Unlicense" ]
null
null
null
06 - Decisions/example1.py
gyratory/NPTfP3
7e070e2e7a01cd2b750914719f71476fe1efcf4d
[ "Unlicense" ]
null
null
null
06 - Decisions/example1.py
gyratory/NPTfP3
7e070e2e7a01cd2b750914719f71476fe1efcf4d
[ "Unlicense" ]
null
null
null
# This program demonstrates the use of the == operator using numbers print (5 == 6) # Using variables x = 5 y = 8 print(x == y)
18.285714
68
0.671875
22
128
3.909091
0.727273
0
0
0
0
0
0
0
0
0
0
0.04
0.21875
128
6
69
21.333333
0.82
0.640625
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
6853794f53b4ee048349323624ba745ddda47340
304
py
Python
tests/smoke_testing_test.py
univerone/python-wechaty-getting-started
86dac7c2d5a6a182bcb1b642aeb6eea14f996bb0
[ "Apache-2.0" ]
1
2020-07-14T18:41:42.000Z
2020-07-14T18:41:42.000Z
tests/smoke_testing_test.py
univerone/python-wechaty-getting-started
86dac7c2d5a6a182bcb1b642aeb6eea14f996bb0
[ "Apache-2.0" ]
1
2021-12-13T20:43:51.000Z
2021-12-13T20:43:51.000Z
tests/smoke_testing_test.py
univerone/python-wechaty-getting-started
86dac7c2d5a6a182bcb1b642aeb6eea14f996bb0
[ "Apache-2.0" ]
null
null
null
""" Smoke Testing """ # from typing import ( # # Any, # Iterable, # ) from wechaty import ( Wechaty ) def test_smoke_testing() -> None: """ wechaty """ # os.environ['WECHATY_PUPPET_HOSTIE_TOKEN'] = 'test' # bot = Wechaty() assert Wechaty, 'should be imported successfully'
16
56
0.611842
32
304
5.65625
0.6875
0.132597
0
0
0
0
0
0
0
0
0
0
0.243421
304
18
57
16.888889
0.786957
0.450658
0
0
0
0
0.210884
0
0
0
0
0
0.2
1
0.2
true
0
0.4
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
688a8db571892e5b29124a58b055b5adac2fb93f
25,524
py
Python
acapy_client/models/__init__.py
Indicio-tech/acapy-client
0bd47af23308362db749c2671a3e7f8259855897
[ "Apache-2.0" ]
4
2021-08-05T09:20:34.000Z
2021-08-08T19:37:29.000Z
acapy_client/models/__init__.py
Indicio-tech/acapy-client
0bd47af23308362db749c2671a3e7f8259855897
[ "Apache-2.0" ]
null
null
null
acapy_client/models/__init__.py
Indicio-tech/acapy-client
0bd47af23308362db749c2671a3e7f8259855897
[ "Apache-2.0" ]
2
2021-08-12T18:18:45.000Z
2021-08-14T13:22:28.000Z
""" Contains all the data models used in inputs/outputs """ from .action_menu_fetch_result import ActionMenuFetchResult from .action_menu_modules_result import ActionMenuModulesResult from .admin_api_message_tracing import AdminAPIMessageTracing from .admin_config import AdminConfig from .admin_config_config import AdminConfigConfig from .admin_mediation_deny import AdminMediationDeny from .admin_modules import AdminModules from .admin_reset import AdminReset from .admin_shutdown import AdminShutdown from .admin_status import AdminStatus from .admin_status_conductor import AdminStatusConductor from .admin_status_liveliness import AdminStatusLiveliness from .admin_status_readiness import AdminStatusReadiness from .admin_status_timing import AdminStatusTiming from .aml_record import AMLRecord from .aml_record_aml import AMLRecordAml from .attach_decorator import AttachDecorator from .attach_decorator_data import AttachDecoratorData from .attach_decorator_data_1jws import AttachDecoratorData1JWS from .attach_decorator_data_json import AttachDecoratorDataJson from .attach_decorator_data_jws import AttachDecoratorDataJWS from .attach_decorator_data_jws_header import AttachDecoratorDataJWSHeader from .attachment_def import AttachmentDef from .attachment_def_type import AttachmentDefType from .attribute_mime_types_result import AttributeMimeTypesResult from .attribute_mime_types_result_results import AttributeMimeTypesResultResults from .basic_message_module_response import BasicMessageModuleResponse from .claim_format import ClaimFormat from .claim_format_jwt import ClaimFormatJwt from .claim_format_jwt_vc import ClaimFormatJwtVc from .claim_format_jwt_vp import ClaimFormatJwtVp from .claim_format_ldp import ClaimFormatLdp from .claim_format_ldp_vc import ClaimFormatLdpVc from .claim_format_ldp_vp import ClaimFormatLdpVp from .clear_pending_revocations_request import ClearPendingRevocationsRequest from .clear_pending_revocations_request_purge import ClearPendingRevocationsRequestPurge from .conn_record import ConnRecord from .conn_record_accept import ConnRecordAccept from .conn_record_connection_protocol import ConnRecordConnectionProtocol from .conn_record_invitation_mode import ConnRecordInvitationMode from .conn_record_routing_state import ConnRecordRoutingState from .conn_record_their_role import ConnRecordTheirRole from .connection_invitation import ConnectionInvitation from .connection_list import ConnectionList from .connection_metadata import ConnectionMetadata from .connection_metadata_results import ConnectionMetadataResults from .connection_metadata_set_request import ConnectionMetadataSetRequest from .connection_metadata_set_request_metadata import ConnectionMetadataSetRequestMetadata from .connection_module_response import ConnectionModuleResponse from .connection_static_request import ConnectionStaticRequest from .connection_static_result import ConnectionStaticResult from .constraints import Constraints from .constraints_status_active import ConstraintsStatusActive from .constraints_status_revoked import ConstraintsStatusRevoked from .constraints_status_suspended import ConstraintsStatusSuspended from .constraints_subject_is_issuer import ConstraintsSubjectIsIssuer from .create_invitation_request import CreateInvitationRequest from .create_invitation_request_metadata import CreateInvitationRequestMetadata from .create_wallet_request import CreateWalletRequest from .create_wallet_request_key_management_mode import CreateWalletRequestKeyManagementMode from .create_wallet_request_wallet_dispatch_type import CreateWalletRequestWalletDispatchType from .create_wallet_request_wallet_type import CreateWalletRequestWalletType from .create_wallet_response import CreateWalletResponse from .create_wallet_response_key_management_mode import CreateWalletResponseKeyManagementMode from .create_wallet_response_settings import CreateWalletResponseSettings from .create_wallet_token_request import CreateWalletTokenRequest from .create_wallet_token_response import CreateWalletTokenResponse from .cred_attr_spec import CredAttrSpec from .cred_def_value import CredDefValue from .cred_def_value_primary import CredDefValuePrimary from .cred_def_value_revocation import CredDefValueRevocation from .cred_info_list import CredInfoList from .cred_rev_record_result import CredRevRecordResult from .cred_revoked_result import CredRevokedResult from .credential import Credential from .credential_context_item_type_0 import CredentialContextItemType0 from .credential_credential_subject import CredentialCredentialSubject from .credential_definition import CredentialDefinition from .credential_definition_get_result import CredentialDefinitionGetResult from .credential_definition_send_request import CredentialDefinitionSendRequest from .credential_definition_send_result import CredentialDefinitionSendResult from .credential_definition_type import CredentialDefinitionType from .credential_definitions_created_result import CredentialDefinitionsCreatedResult from .credential_issuer_type_0 import CredentialIssuerType0 from .credential_offer import CredentialOffer from .credential_preview import CredentialPreview from .credential_proposal import CredentialProposal from .credential_status_options import CredentialStatusOptions from .date import Date from .did import DID from .did_create import DIDCreate from .did_create_method import DIDCreateMethod from .did_create_options import DIDCreateOptions from .did_create_options_key_type import DIDCreateOptionsKeyType from .did_endpoint import DIDEndpoint from .did_endpoint_with_type import DIDEndpointWithType from .did_endpoint_with_type_endpoint_type import DIDEndpointWithTypeEndpointType from .did_key_type import DIDKeyType from .did_list import DIDList from .did_method import DIDMethod from .did_posture import DIDPosture from .did_result import DIDResult from .didx_request import DIDXRequest from .dif_field import DIFField from .dif_field_predicate import DIFFieldPredicate from .dif_holder import DIFHolder from .dif_holder_directive import DIFHolderDirective from .dif_options import DIFOptions from .dif_pres_spec import DIFPresSpec from .dif_pres_spec_record_ids import DIFPresSpecRecordIds from .dif_pres_spec_reveal_doc import DIFPresSpecRevealDoc from .dif_proof_proposal import DIFProofProposal from .dif_proof_request import DIFProofRequest from .doc import Doc from .doc_credential import DocCredential from .endorser_info import EndorserInfo from .endpoints_result import EndpointsResult from .filter_ import Filter from .filter_const_type_5 import FilterConstType5 from .filter_enum_item import FilterEnumItem from .filter_exclusive_maximum import FilterExclusiveMaximum from .filter_exclusive_minimum import FilterExclusiveMinimum from .filter_maximum import FilterMaximum from .filter_minimum import FilterMinimum from .generated import Generated from .get_connections_connection_protocol import GetConnectionsConnectionProtocol from .get_connections_state import GetConnectionsState from .get_connections_their_role import GetConnectionsTheirRole from .get_did_endpoint_response import GetDIDEndpointResponse from .get_did_verkey_response import GetDIDVerkeyResponse from .get_issue_credential_records_role import GetIssueCredentialRecordsRole from .get_issue_credential_records_state import GetIssueCredentialRecordsState from .get_ledger_did_endpoint_endpoint_type import GetLedgerDidEndpointEndpointType from .get_mediation_keylists_role import GetMediationKeylistsRole from .get_mediation_requests_state import GetMediationRequestsState from .get_nym_role_response import GetNymRoleResponse from .get_nym_role_response_role import GetNymRoleResponseRole from .get_present_proof_20_records_present_proof_role_schema import GetPresentProof20RecordsPresentProofRoleSchema from .get_present_proof_20_records_present_proof_state_schema import GetPresentProof20RecordsPresentProofStateSchema from .get_present_proof_records_role import GetPresentProofRecordsRole from .get_present_proof_records_state import GetPresentProofRecordsState from .get_records_role import GetRecordsRole from .get_records_state import GetRecordsState from .get_revocation_registries_created_state import GetRevocationRegistriesCreatedState from .get_wallet_did_key_type import GetWalletDidKeyType from .get_wallet_did_method import GetWalletDidMethod from .get_wallet_did_posture import GetWalletDidPosture from .holder_module_response import HolderModuleResponse from .indy_attr_value import IndyAttrValue from .indy_cred_abstract import IndyCredAbstract from .indy_cred_info import IndyCredInfo from .indy_cred_info_attrs import IndyCredInfoAttrs from .indy_cred_precis import IndyCredPrecis from .indy_cred_request import IndyCredRequest from .indy_cred_request_blinded_ms import IndyCredRequestBlindedMs from .indy_cred_request_blinded_ms_correctness_proof import IndyCredRequestBlindedMsCorrectnessProof from .indy_credential import IndyCredential from .indy_credential_rev_reg import IndyCredentialRevReg from .indy_credential_signature import IndyCredentialSignature from .indy_credential_signature_correctness_proof import IndyCredentialSignatureCorrectnessProof from .indy_credential_values import IndyCredentialValues from .indy_credential_witness import IndyCredentialWitness from .indy_eq_proof import IndyEQProof from .indy_eq_proof_m import IndyEQProofM from .indy_eq_proof_revealed_attrs import IndyEQProofRevealedAttrs from .indy_ge_proof import IndyGEProof from .indy_ge_proof_pred import IndyGEProofPred from .indy_ge_proof_pred_p_type import IndyGEProofPredPType from .indy_ge_proof_r import IndyGEProofR from .indy_ge_proof_t import IndyGEProofT from .indy_ge_proof_u import IndyGEProofU from .indy_key_correctness_proof import IndyKeyCorrectnessProof from .indy_non_revoc_proof import IndyNonRevocProof from .indy_non_revoc_proof_c_list import IndyNonRevocProofCList from .indy_non_revoc_proof_x_list import IndyNonRevocProofXList from .indy_non_revocation_interval import IndyNonRevocationInterval from .indy_pres_attr_spec import IndyPresAttrSpec from .indy_pres_pred_spec import IndyPresPredSpec from .indy_pres_pred_spec_predicate import IndyPresPredSpecPredicate from .indy_pres_preview import IndyPresPreview from .indy_pres_spec import IndyPresSpec from .indy_pres_spec_requested_attributes import IndyPresSpecRequestedAttributes from .indy_pres_spec_requested_predicates import IndyPresSpecRequestedPredicates from .indy_pres_spec_self_attested_attributes import IndyPresSpecSelfAttestedAttributes from .indy_primary_proof import IndyPrimaryProof from .indy_proof import IndyProof from .indy_proof_identifier import IndyProofIdentifier from .indy_proof_proof import IndyProofProof from .indy_proof_proof_aggregated_proof import IndyProofProofAggregatedProof from .indy_proof_proof_proofs_proof import IndyProofProofProofsProof from .indy_proof_req_attr_spec import IndyProofReqAttrSpec from .indy_proof_req_attr_spec_non_revoked import IndyProofReqAttrSpecNonRevoked from .indy_proof_req_attr_spec_restrictions_item import IndyProofReqAttrSpecRestrictionsItem from .indy_proof_req_pred_spec import IndyProofReqPredSpec from .indy_proof_req_pred_spec_non_revoked import IndyProofReqPredSpecNonRevoked from .indy_proof_req_pred_spec_p_type import IndyProofReqPredSpecPType from .indy_proof_req_pred_spec_restrictions_item import IndyProofReqPredSpecRestrictionsItem from .indy_proof_request import IndyProofRequest from .indy_proof_request_non_revoked import IndyProofRequestNonRevoked from .indy_proof_request_requested_attributes import IndyProofRequestRequestedAttributes from .indy_proof_request_requested_predicates import IndyProofRequestRequestedPredicates from .indy_proof_requested_proof import IndyProofRequestedProof from .indy_proof_requested_proof_predicate import IndyProofRequestedProofPredicate from .indy_proof_requested_proof_predicates import IndyProofRequestedProofPredicates from .indy_proof_requested_proof_revealed_attr import IndyProofRequestedProofRevealedAttr from .indy_proof_requested_proof_revealed_attr_group import IndyProofRequestedProofRevealedAttrGroup from .indy_proof_requested_proof_revealed_attr_group_values import IndyProofRequestedProofRevealedAttrGroupValues from .indy_proof_requested_proof_revealed_attr_groups import IndyProofRequestedProofRevealedAttrGroups from .indy_proof_requested_proof_revealed_attrs import IndyProofRequestedProofRevealedAttrs from .indy_proof_requested_proof_self_attested_attrs import IndyProofRequestedProofSelfAttestedAttrs from .indy_proof_requested_proof_unrevealed_attrs import IndyProofRequestedProofUnrevealedAttrs from .indy_requested_creds_requested_attr import IndyRequestedCredsRequestedAttr from .indy_requested_creds_requested_pred import IndyRequestedCredsRequestedPred from .indy_rev_reg_def import IndyRevRegDef from .indy_rev_reg_def_revoc_def_type import IndyRevRegDefRevocDefType from .indy_rev_reg_def_value import IndyRevRegDefValue from .indy_rev_reg_def_value_issuance_type import IndyRevRegDefValueIssuanceType from .indy_rev_reg_def_value_public_keys import IndyRevRegDefValuePublicKeys from .indy_rev_reg_def_value_public_keys_accum_key import IndyRevRegDefValuePublicKeysAccumKey from .indy_rev_reg_entry import IndyRevRegEntry from .indy_rev_reg_entry_value import IndyRevRegEntryValue from .input_descriptors import InputDescriptors from .input_descriptors_metadata import InputDescriptorsMetadata from .intro_module_response import IntroModuleResponse from .invitation_create_request import InvitationCreateRequest from .invitation_create_request_metadata import InvitationCreateRequestMetadata from .invitation_message import InvitationMessage from .invitation_message_services_item import InvitationMessageServicesItem from .invitation_record import InvitationRecord from .invitation_result import InvitationResult from .issue_credential_module_response import IssueCredentialModuleResponse from .issuer_cred_rev_record import IssuerCredRevRecord from .issuer_rev_reg_record import IssuerRevRegRecord from .issuer_rev_reg_record_revoc_def_type import IssuerRevRegRecordRevocDefType from .keylist import Keylist from .keylist_query import KeylistQuery from .keylist_query_filter import KeylistQueryFilter from .keylist_query_filter_request import KeylistQueryFilterRequest from .keylist_query_filter_request_filter import KeylistQueryFilterRequestFilter from .keylist_query_paginate import KeylistQueryPaginate from .keylist_update import KeylistUpdate from .keylist_update_request import KeylistUpdateRequest from .keylist_update_rule import KeylistUpdateRule from .keylist_update_rule_action import KeylistUpdateRuleAction from .ld_proof_vc_detail import LDProofVCDetail from .ld_proof_vc_detail_options import LDProofVCDetailOptions from .ledger_modules_result import LedgerModulesResult from .linked_data_proof import LinkedDataProof from .mediation_create_request import MediationCreateRequest from .mediation_deny import MediationDeny from .mediation_grant import MediationGrant from .mediation_list import MediationList from .mediation_record import MediationRecord from .menu import Menu from .menu_form import MenuForm from .menu_form_param import MenuFormParam from .menu_json import MenuJson from .menu_option import MenuOption from .multitenant_module_response import MultitenantModuleResponse from .patch_revocation_registry_rev_reg_id_set_state_state import PatchRevocationRegistryRevRegIdSetStateState from .perform_request import PerformRequest from .perform_request_params import PerformRequestParams from .ping_request import PingRequest from .ping_request_response import PingRequestResponse from .post_ledger_register_nym_role import PostLedgerRegisterNymRole from .post_transactions_conn_id_set_endorser_role_transaction_my_job import ( PostTransactionsConnIdSetEndorserRoleTransactionMyJob, ) from .presentation_definition import PresentationDefinition from .presentation_proposal import PresentationProposal from .presentation_request import PresentationRequest from .publish_revocations import PublishRevocations from .publish_revocations_rrid_2_crid import PublishRevocationsRrid2Crid from .query_result import QueryResult from .query_result_results import QueryResultResults from .query_result_results_additional_property import QueryResultResultsAdditionalProperty from .raw_encoded import RawEncoded from .receive_invitation_request import ReceiveInvitationRequest from .register_ledger_nym_response import RegisterLedgerNymResponse from .remove_wallet_request import RemoveWalletRequest from .resolution_result import ResolutionResult from .resolution_result_did_doc import ResolutionResultDidDoc from .resolution_result_metadata import ResolutionResultMetadata from .rev_reg_create_request import RevRegCreateRequest from .rev_reg_issued_result import RevRegIssuedResult from .rev_reg_result import RevRegResult from .rev_reg_update_tails_file_uri import RevRegUpdateTailsFileUri from .rev_regs_created import RevRegsCreated from .revocation_module_response import RevocationModuleResponse from .revoke_request import RevokeRequest from .route_record import RouteRecord from .schema import Schema from .schema_get_result import SchemaGetResult from .schema_input_descriptor import SchemaInputDescriptor from .schema_send_request import SchemaSendRequest from .schema_send_result import SchemaSendResult from .schemas_created_result import SchemasCreatedResult from .schemas_input_descriptor_filter import SchemasInputDescriptorFilter from .send_menu import SendMenu from .send_message import SendMessage from .sign_request import SignRequest from .sign_response import SignResponse from .sign_response_signed_doc import SignResponseSignedDoc from .signature_options import SignatureOptions from .signed_doc import SignedDoc from .submission_requirements import SubmissionRequirements from .submission_requirements_from_nested_item import SubmissionRequirementsFromNestedItem from .submission_requirements_rule import SubmissionRequirementsRule from .taa_accept import TAAAccept from .taa_acceptance import TAAAcceptance from .taa_info import TAAInfo from .taa_record import TAARecord from .taa_result import TAAResult from .transaction_jobs import TransactionJobs from .transaction_jobs_transaction_my_job import TransactionJobsTransactionMyJob from .transaction_jobs_transaction_their_job import TransactionJobsTransactionTheirJob from .transaction_list import TransactionList from .transaction_record import TransactionRecord from .transaction_record_formats_item import TransactionRecordFormatsItem from .transaction_record_messages_attach_item import TransactionRecordMessagesAttachItem from .transaction_record_meta_data import TransactionRecordMetaData from .transaction_record_signature_request_item import TransactionRecordSignatureRequestItem from .transaction_record_signature_response_item import TransactionRecordSignatureResponseItem from .transaction_record_timing import TransactionRecordTiming from .txn_or_credential_definition_send_result import TxnOrCredentialDefinitionSendResult from .txn_or_publish_revocations_result import TxnOrPublishRevocationsResult from .txn_or_rev_reg_result import TxnOrRevRegResult from .txn_or_schema_send_result import TxnOrSchemaSendResult from .update_wallet_request import UpdateWalletRequest from .update_wallet_request_wallet_dispatch_type import UpdateWalletRequestWalletDispatchType from .v10_credential_bound_offer_request import V10CredentialBoundOfferRequest from .v10_credential_conn_free_offer_request import V10CredentialConnFreeOfferRequest from .v10_credential_create import V10CredentialCreate from .v10_credential_exchange import V10CredentialExchange from .v10_credential_exchange_credential_request_metadata import V10CredentialExchangeCredentialRequestMetadata from .v10_credential_exchange_initiator import V10CredentialExchangeInitiator from .v10_credential_exchange_list_result import V10CredentialExchangeListResult from .v10_credential_exchange_role import V10CredentialExchangeRole from .v10_credential_free_offer_request import V10CredentialFreeOfferRequest from .v10_credential_issue_request import V10CredentialIssueRequest from .v10_credential_problem_report_request import V10CredentialProblemReportRequest from .v10_credential_proposal_request_mand import V10CredentialProposalRequestMand from .v10_credential_proposal_request_opt import V10CredentialProposalRequestOpt from .v10_credential_store_request import V10CredentialStoreRequest from .v10_present_proof_module_response import V10PresentProofModuleResponse from .v10_presentation_create_request_request import V10PresentationCreateRequestRequest from .v10_presentation_exchange import V10PresentationExchange from .v10_presentation_exchange_initiator import V10PresentationExchangeInitiator from .v10_presentation_exchange_list import V10PresentationExchangeList from .v10_presentation_exchange_role import V10PresentationExchangeRole from .v10_presentation_exchange_verified import V10PresentationExchangeVerified from .v10_presentation_problem_report_request import V10PresentationProblemReportRequest from .v10_presentation_proposal_request import V10PresentationProposalRequest from .v10_presentation_send_request_request import V10PresentationSendRequestRequest from .v20_cred_attr_spec import V20CredAttrSpec from .v20_cred_bound_offer_request import V20CredBoundOfferRequest from .v20_cred_ex_free import V20CredExFree from .v20_cred_ex_record import V20CredExRecord from .v20_cred_ex_record_by_format import V20CredExRecordByFormat from .v20_cred_ex_record_by_format_cred_issue import V20CredExRecordByFormatCredIssue from .v20_cred_ex_record_by_format_cred_offer import V20CredExRecordByFormatCredOffer from .v20_cred_ex_record_by_format_cred_proposal import V20CredExRecordByFormatCredProposal from .v20_cred_ex_record_by_format_cred_request import V20CredExRecordByFormatCredRequest from .v20_cred_ex_record_detail import V20CredExRecordDetail from .v20_cred_ex_record_indy import V20CredExRecordIndy from .v20_cred_ex_record_indy_cred_request_metadata import V20CredExRecordIndyCredRequestMetadata from .v20_cred_ex_record_initiator import V20CredExRecordInitiator from .v20_cred_ex_record_ld_proof import V20CredExRecordLDProof from .v20_cred_ex_record_list_result import V20CredExRecordListResult from .v20_cred_ex_record_role import V20CredExRecordRole from .v20_cred_ex_record_state import V20CredExRecordState from .v20_cred_filter import V20CredFilter from .v20_cred_filter_indy import V20CredFilterIndy from .v20_cred_filter_ld_proof import V20CredFilterLDProof from .v20_cred_format import V20CredFormat from .v20_cred_issue import V20CredIssue from .v20_cred_issue_problem_report_request import V20CredIssueProblemReportRequest from .v20_cred_issue_request import V20CredIssueRequest from .v20_cred_offer import V20CredOffer from .v20_cred_offer_conn_free_request import V20CredOfferConnFreeRequest from .v20_cred_offer_request import V20CredOfferRequest from .v20_cred_preview import V20CredPreview from .v20_cred_proposal import V20CredProposal from .v20_cred_request import V20CredRequest from .v20_cred_request_free import V20CredRequestFree from .v20_cred_request_request import V20CredRequestRequest from .v20_cred_store_request import V20CredStoreRequest from .v20_issue_cred_schema_core import V20IssueCredSchemaCore from .v20_issue_credential_module_response import V20IssueCredentialModuleResponse from .v20_pres import V20Pres from .v20_pres_create_request_request import V20PresCreateRequestRequest from .v20_pres_ex_record import V20PresExRecord from .v20_pres_ex_record_by_format import V20PresExRecordByFormat from .v20_pres_ex_record_by_format_pres import V20PresExRecordByFormatPres from .v20_pres_ex_record_by_format_pres_proposal import V20PresExRecordByFormatPresProposal from .v20_pres_ex_record_by_format_pres_request import V20PresExRecordByFormatPresRequest from .v20_pres_ex_record_initiator import V20PresExRecordInitiator from .v20_pres_ex_record_list import V20PresExRecordList from .v20_pres_ex_record_role import V20PresExRecordRole from .v20_pres_ex_record_state import V20PresExRecordState from .v20_pres_ex_record_verified import V20PresExRecordVerified from .v20_pres_format import V20PresFormat from .v20_pres_problem_report_request import V20PresProblemReportRequest from .v20_pres_proposal import V20PresProposal from .v20_pres_proposal_by_format import V20PresProposalByFormat from .v20_pres_proposal_request import V20PresProposalRequest from .v20_pres_request import V20PresRequest from .v20_pres_request_by_format import V20PresRequestByFormat from .v20_pres_send_request_request import V20PresSendRequestRequest from .v20_pres_spec_by_format_request import V20PresSpecByFormatRequest from .v20_present_proof_module_response import V20PresentProofModuleResponse from .vc_record import VCRecord from .vc_record_cred_tags import VCRecordCredTags from .vc_record_cred_value import VCRecordCredValue from .vc_record_list import VCRecordList from .verify_request import VerifyRequest from .verify_response import VerifyResponse from .w3c_credentials_list_request import W3CCredentialsListRequest from .w3c_credentials_list_request_tag_query import W3CCredentialsListRequestTagQuery from .wallet_list import WalletList from .wallet_module_response import WalletModuleResponse from .wallet_record import WalletRecord from .wallet_record_key_management_mode import WalletRecordKeyManagementMode from .wallet_record_settings import WalletRecordSettings
59.775176
116
0.916275
2,900
25,524
7.64931
0.236552
0.026326
0.016364
0.008791
0.122977
0.04526
0.026191
0.020241
0
0
0
0.014526
0.0668
25,524
426
117
59.915493
0.916789
0.001998
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.995283
0
0.995283
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
688da068be212d8baf6b052dfec5d791d0790923
1,946
py
Python
backend/backend/users/models.py
Redaloukil/PackageWay
977cf865c067bf6004cc9d82a995cd31be1c4889
[ "MIT" ]
null
null
null
backend/backend/users/models.py
Redaloukil/PackageWay
977cf865c067bf6004cc9d82a995cd31be1c4889
[ "MIT" ]
15
2019-12-28T10:54:22.000Z
2022-03-15T19:17:54.000Z
backend/backend/users/models.py
Redaloukil/PackageWay
977cf865c067bf6004cc9d82a995cd31be1c4889
[ "MIT" ]
1
2020-03-25T00:24:55.000Z
2020-03-25T00:24:55.000Z
import uuid from django.contrib.auth.models import AbstractUser , PermissionsMixin from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from backend.users.managers import UserManager USER_TYPE = ( ("0" , "client"), ("1" , "delivery") ) class User(AbstractUser): username = models.CharField(_("Name of User"), blank=False, max_length=255 , unique=True) first_name = models.CharField(max_length=255 , blank=False) last_name = models.CharField(max_length=255 , blank=False) user_type = models.CharField( choices=USER_TYPE ,max_length=10 ,default="0") is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name' ,'last_name' ,''] class Meta: app_label = 'users' def __str__(self): return self.username def get_short_name(self): return self.username def get_full_name(self): return self.username + " " + self.first_name + " " + self.last_name def save(self, *args, **kwargs): if not self.password: self.password = str(uuid.uuid4()).replace('-', '') super(User, self).save(*args, **kwargs) class Profile(models.Model): # image = models.ImageField(blank=True) user = models.ForeignKey(User , on_delete=models.CASCADE) def __str__(self): return self.user.username class ResetPasswordCode(models.Model): user = models.ForeignKey(User , on_delete=models.CASCADE) code = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) class Meta: default_related_name = 'reset_password_codes' def __str__(self): return self.user.username + " " + self.code
29.484848
93
0.681912
240
1,946
5.3375
0.379167
0.046838
0.054645
0.037471
0.25605
0.227947
0.184231
0.13427
0
0
0
0.010263
0.198869
1,946
65
94
29.938462
0.811418
0.019013
0
0.2
0
0
0.05506
0
0
0
0
0
0
1
0.155556
false
0.088889
0.133333
0.133333
0.8
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
1
1
0
0
3
6896b53da5fb3b9b908e85e87aa4247bcf943a68
88
py
Python
test/login.py
yewei496096569/test007
feea1bf7ab3e31cd53ea1266ac36dfd9bac915c5
[ "MIT" ]
null
null
null
test/login.py
yewei496096569/test007
feea1bf7ab3e31cd53ea1266ac36dfd9bac915c5
[ "MIT" ]
null
null
null
test/login.py
yewei496096569/test007
feea1bf7ab3e31cd53ea1266ac36dfd9bac915c5
[ "MIT" ]
null
null
null
manager_num1 =10 manager_num2 =11 zhangsan_num1 = 22 num3 = 30 pp = 36 ll = 23 nishuia
11
18
0.727273
16
88
3.8125
0.875
0
0
0
0
0
0
0
0
0
0
0.228571
0.204545
88
7
19
12.571429
0.642857
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
689a90603905b5e483233adda90da553637a1f35
1,211
py
Python
atest/testresources/listeners/ListenImports.py
rdagum/robotframework
b7069d505374e9f09a140ed5a9727d2a40716446
[ "ECL-2.0", "Apache-2.0" ]
7,073
2015-01-01T17:19:16.000Z
2022-03-31T22:01:29.000Z
atest/testresources/listeners/ListenImports.py
imust6226/robotframework
08c56fef2ebc64d682c7f99acd77c480d8d0e028
[ "ECL-2.0", "Apache-2.0" ]
2,412
2015-01-02T09:29:05.000Z
2022-03-31T13:10:46.000Z
atest/testresources/listeners/ListenImports.py
3mdeb/robotframework
6006ce0b3d5fc6b45c5eb040dc859acd64bfa846
[ "ECL-2.0", "Apache-2.0" ]
2,298
2015-01-03T02:47:15.000Z
2022-03-31T02:00:16.000Z
import os try: basestring except NameError: basestring = str class ListenImports: ROBOT_LISTENER_API_VERSION = 2 def __init__(self, imports): self.imports = open(imports, 'w') def library_import(self, name, attrs): self._imported("Library", name, attrs) def resource_import(self, name, attrs): self._imported("Resource", name, attrs) def variables_import(self, name, attrs): self._imported("Variables", name, attrs) def _imported(self, import_type, name, attrs): self.imports.write("Imported %s\n\tname: %s\n" % (import_type, name)) for name in sorted(attrs): self.imports.write("\t%s: %s\n" % (name, self._pretty(attrs[name]))) def _pretty(self, entry): if isinstance(entry, list): return '[%s]' % ', '.join(entry) if isinstance(entry, basestring) and os.path.isabs(entry): entry = entry.replace('$py.class', '.py').replace('.pyc', '.py') tokens = entry.split(os.sep) index = -1 if tokens[-1] != '__init__.py' else -2 return '//' + '/'.join(tokens[index:]) return entry def close(self): self.imports.close()
29.536585
80
0.595376
149
1,211
4.691275
0.369128
0.090129
0.074392
0.081545
0.133047
0.133047
0
0
0
0
0
0.00442
0.252684
1,211
40
81
30.275
0.767956
0
0
0
0
0
0.081751
0
0
0
0
0
0
1
0.233333
false
0
0.466667
0
0.866667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
1
0
1
0
0
3
d79f9b158a70ef34d846b0830fe0b7eaab8173e4
6,853
py
Python
packages/byfire/controlpanel/models.py
rusty-eagle/ByFire
1e127c3629793b2c27b173e649488c0b3332ebb1
[ "MIT" ]
null
null
null
packages/byfire/controlpanel/models.py
rusty-eagle/ByFire
1e127c3629793b2c27b173e649488c0b3332ebb1
[ "MIT" ]
null
null
null
packages/byfire/controlpanel/models.py
rusty-eagle/ByFire
1e127c3629793b2c27b173e649488c0b3332ebb1
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. class System(models.Model): hostname = models.CharField(max_length=128,default="firewall") domain = models.CharField(max_length=128,default="lan") apply_iptables = models.BooleanField(default=True) apply_ipaddrs = models.BooleanField(default=False) apply_dnsmasq = models.BooleanField(default=False) timesync = models.BooleanField(default=True) time_server = models.CharField(max_length=128,default="ntp.ubuntu.com") timezone = models.CharField(max_length=75,default='America/Los_Angeles') unattended_upgrades = models.BooleanField(default=False) class Iface(models.Model): name = models.CharField(max_length=20) dhcp4 = models.BooleanField(default=True) ipv4 = models.CharField(max_length=15, blank=True, null=True) ipv4_mask = models.CharField(max_length=15, blank=True, null=True) ipv4_gw = models.CharField(max_length=15, blank=True, null=True) ipv4_bc = models.CharField(max_length=15, blank=True, null=True) dhcp6 = models.BooleanField(default=False) ipv6 = models.CharField(max_length=23, blank=True, null=True) ipv6_mask = models.CharField(max_length=23, blank=True, null=True) ipv6_gw = models.CharField(max_length=23, blank=True, null=True) ipv6_bc = models.CharField(max_length=23, blank=True, null=True) mtu = models.IntegerField(default=1500) class Status(models.TextChoices): UP = 'up', DOWN = 'down' status = models.CharField( max_length=10, choices=Status.choices, default=Status.UP, ) mac = models.CharField(max_length=17) def __str__(self): return self.name class wanlan(models.Model): wanlan = models.CharField(max_length=10) interface = models.ForeignKey(Iface, on_delete=models.CASCADE) class DHCPSubnet(models.Model): # dhcp-range zone_name = models.CharField(max_length=15, default='internal') network = models.CharField(max_length=15, default='192.168.100.0') netmask = models.CharField(max_length=15, default='255.255.255.0') start = models.CharField(max_length=15, default='192.168.100.2') end = models.CharField(max_length=15, default='192.168.100.50') gateway = models.CharField(max_length=15, blank=True, null=True) lease_time = models.IntegerField(default=1) class MinuteHour(models.TextChoices): MIN = 'minute', HOUR = 'hour' min_hour = models.CharField( max_length=6, choices=MinuteHour.choices, default=MinuteHour.HOUR, ) ### Static assign ### https://www.linux.com/topic/networking/dns-and-dhcp-dnsmasq/ class Table(models.TextChoices): FILTER = 'filter', NAT = 'nat', MANGLE = 'mangle', RAW = 'raw' class Chain(models.TextChoices): INPUT = 'INPUT', OUTPUT = 'OUTPUT', FORWARD = 'FORWARD', ROUTING = 'ROUTING', PREROUTING = 'PREROUTING', POSTROUTING = 'POSTROUTING' class IPTablePolicy(models.Model): table = models.CharField( max_length=6, choices=Table.choices, default=Table.FILTER, ) chain = models.CharField( max_length=20, choices=Chain.choices, default=Chain.INPUT, ) class DefaultPolicy(models.TextChoices): ACCEPT = 'ACCEPT', REJECT = 'REJECT', DROP = 'DROP' policy = models.CharField( max_length=6, choices=DefaultPolicy.choices, default=DefaultPolicy.ACCEPT, ) class IPTable(models.Model): active = models.BooleanField(default=True) removable = models.BooleanField(default=True) table = models.CharField( max_length=6, choices=Table.choices, default=Table.FILTER, ) chain = models.CharField( max_length=20, choices=Chain.choices, default=Chain.INPUT, ) class Protocol(models.TextChoices): ALL = 'all', UDP = 'udp', TCP = 'tcp', ICMP = 'icmp', protocol = models.CharField( max_length=10, choices=Protocol.choices, default=Protocol.TCP, ) in_iface = models.ForeignKey( Iface, related_name='iface_ingress', on_delete=models.SET_NULL, blank=True, null=True, ) out_iface = models.ForeignKey( Iface, related_name='iface_egress', on_delete=models.SET_NULL, blank=True, null=True, ) source = models.CharField(max_length=26, null=True, blank=True) sport = models.CharField(max_length=15, null=True, blank=True) destination = models.CharField(max_length=26, null=True, blank=True) port = models.CharField(max_length=15, null=True, blank=True) options = models.CharField(max_length=50, null=True, blank=True) class Action(models.TextChoices): ACCEPT = 'ACCEPT', DROP = 'DROP', REJECT = 'REJECT', FORWARD = 'FORWARD', MASQUERADE = 'MASQUERADE', action = models.CharField( max_length=10, choices=Action.choices, default=Action.DROP, ) class Match(models.TextChoices): STATE = 'state', match = models.CharField( max_length=20, choices=Match.choices, blank=True, null=True, ) state = models.CharField( max_length=128, blank=True, null=True, ) comment = models.CharField( max_length=128, blank=True, null=True, ) class DNS(models.Model): domain_needed = models.BooleanField(default=True) # domain-needed bogus_priv = models.BooleanField(default=True) # bogus-priv no_resolv = models.BooleanField(default=True) # no-resolv expand_hosts = models.BooleanField(default=True) # expand-hosts ##domain = models.BooleanField(default=True) # domain=lan ## System.domain ns_1 = models.CharField(max_length=23, blank=True, null=True) # server=1.1.1.1 ns_2 = models.CharField(max_length=23, blank=True, null=True) # server=1.0.0.1 ns_3 = models.CharField(max_length=23, blank=True, null=True) ## interface=enp6s0 ## wanlan lan interface.name class BlockList(models.Model): active = models.BooleanField(default=True) filename = models.CharField(max_length=512) url = models.CharField(max_length=512) class WireguardInterface(models.Model): name = models.CharField(max_length=32) ## Interface name private_key = models.CharField(max_length=256) public_key = models.CharField(max_length=256) class WireguardPeer(models.Model): interface = WireguardInterface name = models.CharField(max_length=32) ## Peer name public_key = models.CharField(max_length=256) endpoint = models.CharField(max_length=23) allows_ips = models.CharField(max_length=27) persistent_keepalive = models.CharField(max_length=3, default='21')
32.325472
82
0.668029
823
6,853
5.449575
0.218712
0.170569
0.204682
0.27291
0.500334
0.456187
0.361204
0.288517
0.288517
0.147157
0
0.032969
0.21217
6,853
211
83
32.478673
0.79774
0.047279
0
0.277778
0
0
0.042916
0
0
0
0
0
0
1
0.005556
false
0
0.005556
0.005556
0.566667
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
3
d7aa34f1806e52568fab04c4fb28c6a72eef81ee
20,999
py
Python
_build/jupyter_execute/curriculum-notebooks/SocialStudies/BubonicPlague/bubonic-plague-and-SIR-model.py
BryceHaley/curriculum-jbook
d1246799ddfe62b0cf5c389394a18c2904383437
[ "CC-BY-4.0" ]
1
2022-03-18T18:19:40.000Z
2022-03-18T18:19:40.000Z
_build/jupyter_execute/curriculum-notebooks/SocialStudies/BubonicPlague/bubonic-plague-and-SIR-model.py
callysto/curriculum-jbook
ffb685901e266b0ae91d1250bf63e05a87c456d9
[ "CC-BY-4.0" ]
null
null
null
_build/jupyter_execute/curriculum-notebooks/SocialStudies/BubonicPlague/bubonic-plague-and-SIR-model.py
callysto/curriculum-jbook
ffb685901e266b0ae91d1250bf63e05a87c456d9
[ "CC-BY-4.0" ]
null
null
null
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=SocialStudies/BubonicPlague/bubonic-plague-and-SIR-model.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> # Bubonic Plage - SIR Model ### Grade 11 Social Studies We are interested in modelling a bubonic plague outbreak. We part from the assumption that the total population can be subdivided into a set of classes, each of which depends on the state of the infection. The [**SIR Model**](https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology) is the simplest one and, as its name suggests, it divides the population into three classes. **Outcomes:** * Examine and visualize concepts and examples related to the bubonic plague. * Examine the timeline/map of the Black Death. * Visualize mathematical model that shows the recovery, infection, and removal rates. ## The SIR Outbreak Model ### Population Parameters In this model, the total population is divided into three groups: * Susceptible: individuals that can become infected but haven't been yet * Infected: individuals that are infected * Removed: individuals that are either dead or recovered We are looking at the changes, over the course of an outbreak, of the numbers of these individuals, represented by $S$, $I$, and $R$. In other words we want to understand how, as time passes, the number of individuals in each group changes. Having a realistic model might be useful for predicting the long-term outcome of an outbreak and informing public health interventions. If we can predict that the number of removed people will stay low and the number of infected people will quickly go down to zero, then there is no need to intervene and we can let the outbreak end by itself while only providing medical attention to the infected people. Conversely if we predict a large increase of the numbers of infected and removed individuals, then the outbreak needs a quick intervention before it results in a large number of casualties. In a plague outbreak this intervention would, for example, be to make sure there is no contact between infected and susceptible people. We now describe the SIR (Susceptible, Infected, Removed) mathematical model of an outbreak over time (for example every week). We write $S_t, I_t, R_t$ to denote the number of susceptible, infected, and removed individuals at time point $t$. $t=1$ is the first recorded time point, $t=2$ is the second and so on. We call *time unit* the time elapsed between two time points, for example a day or a week. In this model, we assume that the **total population is constant** (so births and deaths are ignored) for the duration of the model simulation. We represent the total population size by $N$, and so at any time point $t$ we have $$N=S_t + I_t + R_t$$ ### Modelling the disease progression We assume that transmission requires contact between an infected individual and a susceptible individual. We also assume that the disease takes a constant amount of time to progress within an infected individual until they are removed (die or recover). We need to define these two processes (infection and removal) and model how they impact the transition from the time $t = (S_t,I_t,R_t)$ to the next state $t + 1 = (S_{t+1},I_{t+1},R_{t+1})$. ![SIR_1](./images/SIR_1.jpg) The occurrences of new infections of is modelled using a parameter $\beta$, that gives the proportion of contacts between susceptible people and infected people, during one time unit, that results in infection. Then we can describe the number of newly infected people as $\dfrac{\beta S_t I_t}{N}$, where the term $S_t I_t$ represents the set of all possible contacts between susceptible and infected individuals. We discuss this term later. The occurrence of removals of infected people is modelled using a parameter denoted by $\gamma$. It is defined to be proportion of infected individuals that die or recover between two time points. If we are given that the duration of an infection is $T$ (i.e. how many time points it takes for an individual between infection and removal), then $\gamma = \dfrac{1}{T}$. ![SIR_2](./images/SIR_2.jpg) Taking into account the rate of contact $\beta$ and rate of removal $\gamma$, then each group population changes within one unit of time as follows $$ \begin{align} S_{t+1} &= S_t - \dfrac{{\beta} S_t I_t}{N}\\ I_{t+1} &= I_t + \dfrac{{\beta} S_t I_t}{N} - \gamma I_t \\ R_{t+1} &= R_t + \gamma I_t\\ N&=S_t + I_t + R_t \end{align} $$ These equations form the SIR model. They allow, from knowing the parameters of the model ($\beta$ and $\gamma$) and the current state ($S_t,I_t,R_t$) of a population to predict the next states of the population for later time points. Such models are critical in our days for monitoring and controlling infectious diseases outbreaks. ##### Technical remarks. First, note that the SIR model does not enforce that the values $S_t,I_t,R_t$ at a given time point are integers. As $\beta$ and $\gamma$ are actually floating numbers, these values are actually most of the time not integers. This is fine as the SIR model is an approximate model and aims mostly at predicting the general dynamics of an outbreak, not the precise values for the number of susceptible, infected, and removed individuals. Next, one can ask how to find the values of the parameters $\beta$ and $\gamma$ that are necessary to have a full SIR model. As discussed above, the parameter $\gamma$ is relatively easy to find from knowing how the disease progress in a patient, as it is mostly the inverse of the average time a patient is sick. The parameter $\beta$ is less easy to obtain. Reading the equations we can see that during a time point, out of the $S_t$ susceptible individuals, the number that get infected is $(\dfrac{{\beta}}{N}) S_t I_t$. As mentioned above, the product $S_t I_t$ can be interpreted as the set of all possible contacts between the $S_t$ susceptible individuals and the $I_t$ infected individuals and is often a large number, much larger than $S_t$ and in the order of $N^2$. The division by $N$ aims to lower this number, mostly to normalize it by the total population, to make sure it is in order of $N$ and not quadratic in $N$. So in order for the number of newly infected individuals during a time unit to be reasonable, $\beta$ is generally a small number between $0$ and $1$. But formally, if we pick a value for $\beta$ that is too large, then the SIR model will predict value for $S_t$ that can be negative, which is inconsistent with the modelled phenomenon. So choosing the value of $\beta$ is the crucial step in modelling an outbreak. # This function takes as input a vector y holding all initial values, # t: the number of time points (e.g. days) # beta: proportion of contacts that result in infections # gamma: proportion of infected that are removed # S1,I1,R1 = initial population sizes def discrete_SIR(S1,I1,R1,t,beta,gamma): # Empy arrays for each class S = [] # susceptible population I = [] # infected population R = [] # removed population N = S1+I1+R1 # the total population # Append initial values S.append(S1) I.append(I1) R.append(R1) # apply SIR model: iterate over the total number of days - 1 for i in range(t-1): S_next = S[i] - (beta/N)*((S[i]*I[i])) S.append(S_next) I_next = I[i] + (beta/N)*((S[i]*I[i])) - gamma*I[i] I.append(I_next) R_next = R[i] + gamma * I[i] R.append(R_next) # return arrays S,I,R whose entries are various values for susceptible, infected, removed return((S,I,R)) ## Modelling an outbreak related to the Great Plague of London The last major epidemic of the bubonic plague in England occurred between 1665 and 1666 ([click here for further reading](https://www.britannica.com/event/Great-Plague-of-London)). This epidemic did not kill as many people as the Black Death (1347 - 1351), however it is remembered as the "Great Plague of London" as it was the last widespread outbreak that affected England. "City records indicate that some 68,596 people died during the epidemic, though the actual number of deaths is suspected to have exceeded 100,000 out of a total population estimated at 460,000. " [Great Plague of London"; Encyclopædia Britannica; Encyclopædia Britannica, inc.; September 08, 2016](https://www.britannica.com/event/Great-Plague-of-London) When the bubonic plague outbreak hit London, people started to leave the city and go to the countryside, hoping to avoid the disease. But as can be expected, some of these people were already infected when they left London, and so carried the disease to start other outbreaks in some nearby villages. This happened in the village of Eyam. When Eyam authorities realized a plague outbreak had started, they took the difficult decision to close the village in order to avoid to spread the disease further. So nobody was allowed to enter or leave the village and people stayed there hoping the outbreak would end by itself without too many casualties; note that from a mathematical point of view, that implies that the assumption that the sum of the numbers of susceptible, infected and removed individuals, the population, is constant. Also the village authorities recorded regularly the number of infected and dead people; these data are described in the table below, for the period from June 19 1665 to October 19 1665, with data being recorded every 2 weeks. Obviously these data are imperfect (some people did not declare they were sick by fear of being ostracized, some people died too fast for the plague to be diagnosed, etc.), but nevertheless, they provide us with interesting data to see if the SIR model is an appropriate model for such a plague outbreak. | Date |Day Number |Susceptible | Infected | |-------||-------------|----------| |June 19 1665|0|254|7| |July 3 1665|14|235|14| |July 19 1665|28|201|22| |Aug 3 1665|42|153|29| |Aug 19 1665|56|121| 21| |Sept 3 1665|70|108|8| |Sept 19 1665|84|121|21| |Oct 3 1665| 98|NA | NA| |Oct 19 1665|112| 83 | 0| The average time an infected individual remains infected by the bubonic plague is 11 days. With the information above, we will be able to get the parameters of the SIR model for this outbreak and observe if indeed what this model predicts generates results corresponding to what happened in reality. ### Question 1: Assuming that on June 19 no individuals had died, i.e. no one was in the Removed class, what is the value of $N$, i.e. the number of individuals in the total population? ### Question 2: We know that the average time an individual remained infected is 11 days. What is the rate of removal ($\gamma$)? ### Question 3: We are now trying something more difficult but more interesting. We introduced a mathematical model for outbreaks, but nothing so far shows that this SIR model is appropriate to model an outbreak such as the Eyam plague outbreak. We want to answer this question now. From questions 1 and 2 above we know the values of $N$ and $\gamma$ (check your answers at the bottom of this notebook). From the data table we also know $S_1,I_1,R_1$, the state of the population at the start of the outbreak. So if we want to apply the SIR model we need to find a value for $\beta$ the parameter, the number susceptible people becoming infected during a time unit. We consider here that a time unit is 1 day; the Eyam outbreak spanned 112 days, so 112 time units, even if data were only recorded every 2 weeks. A standard scientific approach for the problem of finding $\beta$ is to try various values and see if there is one that leads to predicted values for $S_n,I_n,R_n$ that match the observed data. In order to evaluate this match, we focus on the number of infected people, the most important element of an outbreak. The code below allows you to do this: you can choose a value of $\beta$, click on the "Run interact" button and it will show on the same graph a set of 8 blue dots (the observed number of infected people from the data table) and a set of 112 red dots, corresponding to the predicted number of infected individuals for the chosen value of $\beta$. While there are several mathematical ways to define what would be the *best fit*, here we are not getting into this and you are just asked to try to find a value of $\beta$ that generated blue dots being approximately on the graph defined by the red dots. Pay particular attention to the first four blue dots. Note that in this case $0 < \beta < 1$. ##### Warning: The SIR model is a very simple approximation of the dynamics of a true outbreak, so don't expect to find a value of $\beta$ that generates a graph that contains exactly all observed data points (blue dots). In particular note that the data from September 3 and 19 seem to be somewhat of an anomaly as we observe a sharp decrease in the number of infected followed by a surge. This could be due to many reasons, for example poor statistics recording (we are considering a group of people under heavy stress likely more motivated by trying to stay alive than to record accurate vital statistics). So here we are interested in finding a parameter $\beta$ that captures the general dynamics (increase followed by a post-peak decrease) of the outbreak. You can expect to find a reasonable value for $\beta$ but be aware that many values, especially too high, will result in a very poor match between observed data and model predictions. from ipywidgets import interact_manual, interact,widgets import matplotlib.pyplot as plt # set style s = {'description_width': 'initial'} # Set interact manual box widget for beta @interact(answer=widgets.FloatText(value=0.50, description='Enter beta ', disabled=False, style=s, step=0.01 )) # define function to find the appropriate value of beta # this function takes as input a floating value and outputs a plot with the best fit curve def find_beta(answer): # set initial values for SIR model S1,I1,R1 = 254,7,0 # Use original data on Number of infected from table in the notebook ori_data = [7,14,22,29,21,8,21,0] # use days, time data was provided biweekly, we transform to days here ori_days = [1,14,28,42,56,70,84,112] # set number of days as the second to last entry on the ori_days array n = ori_days[len(ori_days)-1]-ori_days[0]+1 # get beta from answer - to be sure transform to float beta = float(answer) # Gamma was obtained from disease gamma = 1/11 # Compute SIR values using our discrete_SIR function (S,I,R) = discrete_SIR(S1,I1,R1,n,beta,gamma) # Figure #fig,ax = plt.subplot(figsize=(10,10)) fig = plt.figure(facecolor='w',figsize=(17,5)) ax = fig.add_subplot(111,facecolor = '#ffffff') # Scatter plot of original number of infected in the course of 112 days plt.scatter(ori_days,ori_data,c="blue", label="Original Data") # Scatter plot of infected obtained from SIR mode, in the course of 112 days plt.scatter(range(n),I,c="red",label="SIR Model Predictions") # Make the plot pretty plt.xlabel('Time (days)') plt.ylabel('Infected Individuals') plt.title('Real Data vs Model') #legend = ax.legend() plt.show() ## Simulating a Disease Outbreak To conclude we will use the widgets below to simulate a disease outbreak using the SIR model. You can choose the values of all the elements of the model (sizes of the compartments of the population at the beginning of the outbreak, parameters $\gamma$ and $\beta$, and duration in time units (days) of the outbreak. The default parameters are the ones from the Eyam plague outbreak. The result is a series of three graphs that shows how the three components of the population change during the outbreak. It allows you to see the impact of changes in the parameters $\gamma$ and $\beta$, such as increasing $\beta$ (making the outbreak progress faster) or reducing $\gamma$ (decreasing the removal rate). You can use this interactive tool to try to fit the SIR model to match the observed data. import matplotlib.pyplot as plt import numpy as np from math import ceil # This function takes as input initial values of susceptible, infected and removed, number of days, beta and gamma # it plots the SIR model with the above conditions def plot_SIR(S1,I1,R1,n,beta,gamma): # Initialize figure fig = plt.figure(facecolor='w',figsize=(17,5)) ax = fig.add_subplot(111,facecolor = '#ffffff') # Compute SIR values for our initial data and parameters (S_f,I_f,R_f) = discrete_SIR(S1,I1,R1,n,beta,gamma) # Set x axis x = [i for i in range(n)] # Scatter plot of evolution of susceptible over the course of x days plt.scatter(x,S_f,c= 'b',label='Susceptible') # Scatter plot of evolution of infected over the course of x days plt.scatter(x,I_f,c='r',label='Infected') # Scatter plot of evolution of removed over the course of x days plt.scatter(x,R_f,c='g',label='Removed') # Make the plot pretty plt.xlabel('Time (days)') plt.ylabel('Number of individuals') plt.title('Simulation of a Disease Outbreak Using the SIR Model') legend = ax.legend() plt.show() # Print messages to aid student understand and interpret what is happening in the plot print("SIMULATION DATA\n") print("Beta: " + str(beta)) print("Gamma: " + str(gamma)) print("\n") print("Initial Conditions:") print("Total number of Susceptible: " + str(ceil(S_f[0]))) print("Total number of Infected: " + str(ceil(I_f[0]))) print("Total number of Removed: " + str(ceil(R_f[0]))) print("\n") print("After " + str(n) + " days:") print("Total number of Susceptible: " + str(ceil(S_f[n-1]))) print("Total number of Infected: " + str(ceil(I_f[n-1])) ) print("Total number of Removed: " + str(ceil(R_f[n-1]))) # Tweaking initial Values from ipywidgets import widgets, interact, interact_manual # Set function above so that the user can set all parameters and manually start simulation s = {'description_width': 'initial'} interact(plot_SIR, S1 = widgets.IntSlider(value=254, min=200, max=1000, step=1, style=s, description="Susceptible Initial", disabled=False, orientation='horizontal', readout=True), I1 = widgets.IntSlider(value=7, min=0, max=500, step=1, style=s, description="Infected Initial", disabled=False, orientation='horizontal', readout=True), R1 = widgets.IntSlider(value=0, min=0, max=500, step=1, style=s, description="Removed Initial", disabled=False, orientation='horizontal', readout=True), n = widgets.IntSlider(value=112, min=0, max=500, step=1, style=s, description="Time (days)", disabled=False, orientation='horizontal', readout=True), beta = widgets.FloatText(value=1.50, description=r'$ \beta$ parameter', disabled=False, style = s, step=0.01), gamma = widgets.FloatText(value=1.50, description= r'$ \gamma$ parameter', disabled=False, style=s, step=0.01) ); ### Answer 1 Since we are assuming the population is constant, and since $S_1 = 254, I_1 = 7, R_1 = 0$, then $S_1 + I_1 + R_1 = 254 + 7 + 0 = 261$. ### Answer 2 We know that, on average, an individual will remain infected for approximately 11 days. This means that one individual moves to the removed class for every 11 days, and the rate of removal is $\gamma = \frac{1}{11} = 0.0909...$. ### Answer 3 The best value is approximately $\beta = 0.14909440503418078$. <h2 align='center'>Conclusion</h2> In this notebook we learned about the SIR discrete model to model an outbreak. We learned that this model is one of the simplest ones and that it separates the total population $N$ (a constant) into three categories: Infected, Susceptible and Removed. We learned about rates of infection and removal and how this affects the number of individuals in each class. We also ran a basic but realistic simulation of a bubonic plague outbreak of the Great Plague of London that took place in the village Eyam in 1665 and learned about the devastating effect this had on the population. [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
67.73871
1,036
0.734225
3,496
20,999
4.380149
0.218249
0.015151
0.009338
0.003135
0.169268
0.130935
0.113564
0.079801
0.055835
0.02364
0
0.024656
0.186866
20,999
310
1,037
67.73871
0.872152
0
0
0.125786
0
0.201258
0.06605
0
0
0
0
0
0
0
null
null
0.006289
0.044025
null
null
0.081761
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
3
d7ac95589e993a30d83cc0beaf0037b078ebf192
322
py
Python
lib/cache.py
shyam-patel-kira/LA-CO-SS
76ace6159b5fcf60063e52809b7dac76ccf4952d
[ "BSD-2-Clause" ]
null
null
null
lib/cache.py
shyam-patel-kira/LA-CO-SS
76ace6159b5fcf60063e52809b7dac76ccf4952d
[ "BSD-2-Clause" ]
null
null
null
lib/cache.py
shyam-patel-kira/LA-CO-SS
76ace6159b5fcf60063e52809b7dac76ccf4952d
[ "BSD-2-Clause" ]
null
null
null
import redis class Cache: def __init__(self, host, port): self.conn = redis.Redis(host=host, port=port) def get(self, key): return self.conn.get(key) def sef(self, key, value): self.conn.set(key, value) def hgetall(self, key): return self.conn.hgetall(key) def hmset(self, key, value): self.conn.hmset
17.888889
47
0.689441
53
322
4.113208
0.339623
0.183486
0.119266
0.155963
0.376147
0
0
0
0
0
0
0
0.164596
322
18
48
17.888889
0.810409
0
0
0
0
0
0
0
0
0
0
0
0
1
0.416667
false
0
0.083333
0.166667
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
d7cc9e6cf54fc41f6a4525f7d3479d0cbe050086
630
py
Python
misc/config_tools/configurator/packages/configurator/src/pages/Config/ConfigForm/CustomWidget/uiSchemaGenerate.py
jackwhich/acrn-hypervisor-1
2ff11c2ef04a2668979b3e363e25f13cf48376ac
[ "BSD-3-Clause" ]
null
null
null
misc/config_tools/configurator/packages/configurator/src/pages/Config/ConfigForm/CustomWidget/uiSchemaGenerate.py
jackwhich/acrn-hypervisor-1
2ff11c2ef04a2668979b3e363e25f13cf48376ac
[ "BSD-3-Clause" ]
null
null
null
misc/config_tools/configurator/packages/configurator/src/pages/Config/ConfigForm/CustomWidget/uiSchemaGenerate.py
jackwhich/acrn-hypervisor-1
2ff11c2ef04a2668979b3e363e25f13cf48376ac
[ "BSD-3-Clause" ]
null
null
null
import json def generate_ui_schema(cur_node_name): def _handle(node_path_list: list): val = node_path_list[0] if val == '0': val = 'items' if len(node_path_list) == 1: return { val: {} } node_path_list = node_path_list[1:] return { val: _handle(node_path_list) } path_list = cur_node_name.split('.') return _handle(path_list) def main(): name = 'cpu_affinity.pcpu.0.pcpu_id' result = generate_ui_schema(name) print(json.dumps(result, indent=' ')) if __name__ == '__main__': main()
20.322581
43
0.55873
79
630
4.012658
0.367089
0.201893
0.227129
0.113565
0.138801
0.138801
0
0
0
0
0
0.011737
0.32381
630
30
44
21
0.732394
0
0
0.090909
1
0
0.069841
0.042857
0
0
0
0
0
1
0.136364
false
0
0.045455
0
0.318182
0.045455
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
d7e901521174445933f4decb6964fa6c2e112df0
70
py
Python
youtube_dl/version.py
daviewales/youtube-dl-1
e2904a0b527255f9525b95a8300e9572f689436d
[ "Unlicense" ]
2
2021-06-08T07:27:52.000Z
2021-08-24T09:32:01.000Z
youtube_dl/version.py
paulchui123/youtube-dl
c4cabf040e1bf37aec69a3ff45594ac6965ba139
[ "Unlicense" ]
null
null
null
youtube_dl/version.py
paulchui123/youtube-dl
c4cabf040e1bf37aec69a3ff45594ac6965ba139
[ "Unlicense" ]
3
2020-11-17T16:53:29.000Z
2021-06-08T07:27:54.000Z
from __future__ import unicode_literals __version__ = '2020.11.21.1'
17.5
39
0.8
10
70
4.7
1
0
0
0
0
0
0
0
0
0
0
0.145161
0.114286
70
3
40
23.333333
0.612903
0
0
0
0
0
0.171429
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
d7eec84789a73e2d186cd23dff95671d7cdcf30d
208
py
Python
twitch_project/youtube_bot/views.py
tejesh95/livecoding
327114d67d613ef7300528d62b5165cd215bc1b4
[ "MIT" ]
null
null
null
twitch_project/youtube_bot/views.py
tejesh95/livecoding
327114d67d613ef7300528d62b5165cd215bc1b4
[ "MIT" ]
null
null
null
twitch_project/youtube_bot/views.py
tejesh95/livecoding
327114d67d613ef7300528d62b5165cd215bc1b4
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.http import HttpResponse # Create your views here. BASE_URL = "https://www.googleapis.com/youtube/v3" YOUTUBE_KEY = "AIzaSyCv3VYLRXJdOk1KhsTMxcDLRfht-7jEzbQ"
26
55
0.8125
26
208
6.423077
0.846154
0.11976
0
0
0
0
0
0
0
0
0
0.02139
0.100962
208
7
56
29.714286
0.871658
0.110577
0
0
0
0
0.415301
0.213115
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
cc0c3022d122c4910775004cb26d29af03affaa7
202
py
Python
maths_plots.py
yiftach21-meet/meet2019y1lab6
55c39e7c2fcbf0cc264e0de79e69eb1a85596f85
[ "MIT" ]
null
null
null
maths_plots.py
yiftach21-meet/meet2019y1lab6
55c39e7c2fcbf0cc264e0de79e69eb1a85596f85
[ "MIT" ]
null
null
null
maths_plots.py
yiftach21-meet/meet2019y1lab6
55c39e7c2fcbf0cc264e0de79e69eb1a85596f85
[ "MIT" ]
null
null
null
result = [] for count in range (1,100): if count % 3 == 0: result.append("Fizz") if count % 5 == 0: result.append("Buzz") else: result.append(count) print(result)
16.833333
29
0.529703
27
202
3.962963
0.592593
0.336449
0.242991
0
0
0
0
0
0
0
0
0.057971
0.316832
202
11
30
18.363636
0.717391
0
0
0
0
0
0.039801
0
0
0
0
0
0
1
0
false
0
0
0
0
0.111111
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
cc146b46813bbc36640398ef72e11d21c099e7bc
57,738
py
Python
Tests/test_python25.py
cwensley/ironpython2
f854444e1e08afc8850cb7c1a739a7dd2d10d32a
[ "Apache-2.0" ]
1,078
2016-07-19T02:48:30.000Z
2022-03-30T21:22:34.000Z
Tests/test_python25.py
cwensley/ironpython2
f854444e1e08afc8850cb7c1a739a7dd2d10d32a
[ "Apache-2.0" ]
576
2017-05-21T12:36:48.000Z
2022-03-30T13:47:03.000Z
Tests/test_python25.py
cwensley/ironpython2
f854444e1e08afc8850cb7c1a739a7dd2d10d32a
[ "Apache-2.0" ]
269
2017-05-21T04:44:47.000Z
2022-03-31T16:18:13.000Z
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import exceptions import sys import unittest from iptest import is_cli, run_test isPython25 = ((sys.version_info[0] == 2) and (sys.version_info[1] >= 5)) or (sys.version_info[0] > 2) m = 0 gblvar = 0 @unittest.skipUnless(isPython25, 'Version of Python is too low, must be 2.5 or above') class Python25Test(unittest.TestCase): def test_raise_exit(self): """test case with RAISE(exit consumes), YIELD, RETURN, BREAK and CONTINUE in WITH""" globals()["m"] = 0 class A: def __enter__(self): globals()["m"] += 99 return 300 def __exit__(self,type,value,traceback): if(type == None and value == None and traceback == None): globals()["m"] += 55 else: globals()["m"] *= 2 return 1 a = A() def foo(): p = 100 for y in [1,2,3,4,5,6,7,8,9]: for x in [10,20,30,40,50,60,70,80,90]: with a as b: p = p + 1 if ( x == 20 ): continue if ( x == 50 and y == 5 ): break if( x != 40 and y != 4) : yield p p = p + 5 p = p + x * 100 p = p + 1 if(x % 3 == 0): raise RuntimeError("we force exception") if(y == 8): globals()["m"] += p return if(x % 3 == 0 and y %3 == 0): raise RuntimeError("we force exception") if ( x == 90 ): continue if ( x == 60 and y == 6 ): break yield b + p p = p + 1 try: k = foo() while(k.next()):pass except StopIteration: self.assertEqual(globals()["m"],427056988) else:self.fail("Expected StopIteration but found None") def test__enter__(self): """testing __enter__""" def just_a_fun(arg): return 300 class B: def __enter__(self): return "Iron", "Python", just_a_fun def __exit__(self, a,b,c): pass mydict = {1: [0,1,2], 2:None } with B() as (mydict[1][0], mydict[2], B.myfun): self.assertEqual((mydict[1],mydict[2],B().myfun()),(["Iron",1,2],"Python",just_a_fun(None)) ) #ensure it is same outside with also self.assertEqual((mydict[1],mydict[2],B().myfun()),(["Iron",1,2],"Python",just_a_fun(None)) ) # more args class C: def __enter__(self,morearg): pass def __exit__(self, a,b,c): pass try: with C() as something: pass except TypeError: pass else :self.fail("Expected TypeError but found None") #enter raises class D: def __enter__(self): raise RuntimeError("we force an error") def __exit__(self, a,b,c): pass try: with D() as something: pass except RuntimeError: pass else :self.fail("Expected RuntimeError but found None") #missing enter class MissingEnter: def __exit__(self,a,b,c): pass try: with MissingEnter(): pass except AttributeError:pass else: self.fail("Expected AttributeError but found None") def test__exit__(self): """Testing __exit__""" globals()["gblvar"] = 0 # more args class E: def __enter__(self): pass def __exit__(self, a,b,c,d,e,f): pass try: with E() as something: pass except TypeError: pass else :self.fail("Expected TypeError but found None") # less args class F: def __enter__(self): pass def __exit__(self): pass try: with F() as something: pass except TypeError: pass else :self.fail("Expected TypeError but found None") #exit raises class H: def __enter__(self): H.var1 = 100 def __exit__(self, a,b,c): H.var2 = 200 raise RuntimeError("we force an error") try: with H(): H.var3 = 300 except RuntimeError: self.assertEqual((H.var1,H.var2,H.var3),(100,200,300)) else :self.fail("Expected RuntimeError but found None") #exit raises on successful / throwing WITH class Myerr1(Exception):pass class Myerr2(Exception):pass class Myerr3(Exception):pass class ExitRaise: def __enter__(self): H.var1 = 100 def __exit__(self, a,b,c): if(a == None and b == None and c == None): raise Myerr1 raise Myerr2 try: with ExitRaise(): 1+2+3 except Myerr1: pass else :self.fail("Expected Myerr1 but found None") try: with ExitRaise(): raise Myerr3 except Myerr2: pass else :self.fail("Expected Myerr2 but found None") #exit propagates exception on name deletion ( covers FLOW CHECK scenario) class PropagateException: def __enter__(self): pass def __exit__(self, a,b,c): return False try: with PropagateException() as PE: del PE print PE except NameError:pass else: self.fail("Expected NameError but found None") try: with PropagateException() as PE: PE.var1 = 100 del PE print PE except AttributeError:pass else: self.fail("Expected AttributeError but found None") #exit consumes exception class ConsumeException: def __enter__(self): pass def __exit__(self, a,b,c): return [1,2,3],{"dsad":"dsd"},"hello" with ConsumeException():1/0 #missing exit class MissingExit: def __enter__(self): pass try: with MissingEnter(): pass except NameError: pass else: self.fail("Expected AttributeError but found None") #With Stmt under other compound statements (NO YIELD) globals()["gblvar"] = 0 #inheritance class cxtmgr: def __exit__(self, a, b, c): globals()["gblvar"] += 10 return False class inherited_cxtmgr(cxtmgr): def __enter__(self): globals()["gblvar"] += 10 return False # Building up most complex TRY-CATCH-FINALLY-RAISE-WITH-CLASS combination with inheritance. #try->(try->(except->(with ->fun ->(try->(with->raise)->Finally(With))))) try: #Try try: #try->try globals()["gblvar"] += 1 1/0 except ZeroDivisionError: #try->(try->except) globals()["gblvar"] += 2 with inherited_cxtmgr() as ic: #try->(try->(except->with(inherited))) globals()["gblvar"] += 3 def fun_in_with(): return "Python is smart" self.assertEqual(fun_in_with(),"Python is smart") #try->(try->(except->(with ->fun))) try: #try->(try->(except->(with ->fun ->try))) globals()["gblvar"] += 4 with inherited_cxtmgr() as inherited_cxtmgr.var: #try->(try->(except->(with ->fun ->(try->with)))) globals()["gblvar"] += 5 raise Myerr1() #try->(try->(except->(with ->fun ->(try->with->raise)))) finally: #try->(try->(except->(with ->fun ->(try->(with->raise)->Finally)))) if not is_cli: #https://github.com/IronLanguages/main/issues/844 self.assertEqual(sys.exc_info()[0], Myerr1) else: self.assertEqual(sys.exc_info()[0], exceptions.ZeroDivisionError) globals()["gblvar"] += 6 class ClassInFinally: def __enter__(self): globals()["gblvar"] += 7 return 200 def __exit__(self,a,b,c): globals()["gblvar"] += 8 return False # it raises with ClassInFinally(): #try->(try->(except->(with ->fun ->(try->(with->raise)->Finally(With))))) globals()["gblvar"] += 9 except Myerr1: self.assertEqual(globals()["gblvar"],85) # With in __enter__ and __exit__ globals()["gblvar"] = 0 class A: def __enter__(self): globals()["gblvar"] += 1 ; return 100 def __exit__(self,a,b,c): globals()["gblvar"] += 2; return 200 class WithInEnterExit: def __enter__(self): with A() as b: globals()["gblvar"] += 3;return A() def __exit__(self,a,b,c): with A() as c: globals()["gblvar"] += 4; return A() self.assertEqual(1,1) with WithInEnterExit() as wie: with wie as wie_wie: globals()["gblvar"] += 100 self.assertEqual(globals()["gblvar"],116) def test_thread_lock(self): import thread temp_lock = thread.allocate_lock() self.assertTrue(hasattr(temp_lock, "__enter__")) self.assertTrue(hasattr(temp_lock, "__exit__")) self.assertTrue(not temp_lock.locked()) with temp_lock: self.assertTrue(temp_lock.locked()) self.assertTrue(not temp_lock.locked()) with thread.allocate_lock(): pass def test_with_file(self): with file('abc.txt', 'w'): pass def test_try_catch_finally(self): # test try-catch-finally syntax globals()["gblvar"] = 1 def setvar() : globals()["gblvar"] += 1 #missing except,else try: setvar() # missing else, finally try:1 / 0 except ZeroDivisionError: setvar() # missing else try: setvar() a =[] a[10] except ZeroDivisionError: assert(False) except IndexError: setvar() finally: setvar() finally: setvar() self.assertEqual(globals()["gblvar"],7) globals()["gblvar"] = 1 class MyErr1(Exception) :pass class MyErr2(Exception) :pass class MyErr3(Exception) :pass class MyErr4(Exception) :pass def TestUnifiedTry(myraise1,myraise2, myraise3,myraise4,myraise5,myraise6,myraise7,myraise8,myraise9): try: yield 1; setvar() yield 2; setvar() try: setvar() if myraise1 == "raiseInTry" :setvar(); raise MyErr1 if myraise1 == "outerTry" :setvar(); raise MyErr2 if myraise1 == "Unhandled" :setvar(); raise MyErr4 setvar() except MyErr1: setvar() if myraise2 == "raiseInExcept": setvar(); raise MyErr2 if myraise2 == "Unhandled": setvar(); raise MyErr4 setvar() except :setvar() # should never be executed else : setvar() if myraise2 == "raiseInElse": setvar(); raise MyErr2 if myraise2 == "Unhandled": setvar(); raise MyErr4 setvar() finally : setvar() if myraise3 == "raiseInFinally": setvar(); raise MyErr3 if myraise3 == "Unhandled": setvar(); raise MyErr4 setvar() yield 1; setvar() yield 2; setvar() except MyErr2: yield 1; setvar() yield 2; setvar() try: setvar() if myraise4 == "raiseInTry" :setvar(); raise MyErr1 if myraise4 == "Unhandled" :setvar(); raise MyErr4 setvar() except MyErr1: setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() except :setvar() # should never be executed else : setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() finally : setvar() if myraise6 == "Unhandled": setvar(); raise MyErr4 setvar() yield 1; setvar() yield 2; setvar() except MyErr3: yield 1; setvar() yield 2; setvar() try: setvar() if myraise4 == "raiseInTry" :setvar(); raise MyErr1 if myraise4 == "Unhandled" :setvar(); raise MyErr4 setvar() except MyErr1: setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() except :setvar() # should never be executed else : setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() finally : setvar() if myraise6 == "Unhandled": setvar(); raise MyErr4 setvar() yield 1; setvar() yield 2; setvar() else : yield 1; setvar() yield 2; setvar() try: setvar() if myraise4 == "raiseInTry" :setvar(); raise MyErr1 if myraise4 == "Unhandled" :setvar(); raise MyErr4 setvar() except MyErr1: setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() except :setvar() # should never be executed else : setvar() if myraise5 == "Unhandled": setvar(); raise MyErr4 setvar() finally : setvar() if myraise6 == "Unhandled": setvar(); raise MyErr4 setvar() yield 1; setvar() yield 2; setvar() finally : #uncomment the following 2 lines once we have the fix for PS:1752 #and accordingly adjust the final expected result value #yield 1; setvar() #yield 2; setvar() try: setvar() if myraise7 == "raiseInTry" :setvar(); raise MyErr1 setvar() if myraise7 == "Unhandled" :setvar(); raise MyErr4 setvar() except MyErr1: setvar() if myraise8 == "Unhandled": setvar(); raise MyErr4 setvar() except :setvar() # should never be executed else : setvar() if myraise8 == "Unhandled": setvar(); raise MyErr4 setvar() finally : setvar() if myraise9 == "Unhandled": setvar(); raise MyErr4 setvar() #uncomment the following 2 lines once we have the fix for PS:1752 #and accordingly adjust the final expected result value #yield 1; setvar() #yield 2; setvar() myraise1 = ["raiseInTry","outerTry","Unhandled","None"] myraise2 = ["raiseInExcept", "raiseInElse","Unhandled","None"] myraise3 = ["raiseInFinally","Unhandled","None"] myraise4 = ["raiseInTry","Unhandled","None"] myraise5 = ["Unhandled","None"] myraise6 = ["Unhandled","None"] myraise7 = ["raiseInTry","Unhandled","None"] myraise8 = ["Unhandled","None"] myraise9 = ["Unhandled","None"] def fun(): for a in myraise1: for b in myraise2: for c in myraise3: for d in myraise4: for e in myraise5: for f in myraise6: for g in myraise7: for h in myraise8: for i in myraise9: k = TestUnifiedTry(a,b,c,d,e,f,g,h,i) while(True): try: k.next() except MyErr4: setvar();break except StopIteration: setvar();break fun() self.assertEqual(globals()["gblvar"],141985) def test_try_catch_finally_on_targets(self): #test try-catch-finally on targets globals()["gblvar"] = 1 def setvar() : globals()["gblvar"] += 1 def TestTargets(ret): x = 0 y = 0 z = 0 setvar() while( z < 6 ) : z += 1 while( y < 8 ) : y += 1 while( x < 20 ) : x += 1 setvar() try: setvar() if not x % 3 : setvar();continue if not x % 4 : setvar();break if not x % 5 : setvar();1 / 0 if not x % 7 and ret == "try" : setvar();return setvar() except: setvar() if not y % 3 : setvar();continue if not y % 4 : setvar();break if not y % 7 and ret == "except" : setvar();return setvar() else: setvar() if not x % 11 : setvar();continue if not x % 13 : setvar();break if not x % 19 and ret == "else" : setvar();return setvar() finally: setvar() #IPy does support continue under finally, just for CPy compatibility we do not test it here #if z % 2 : setvar();continue if not z % 2 : setvar();break if not z % 5 and ret == "finally" : setvar();return setvar() setvar() return ret = ["try","except","else","finally"] for r in ret: TestTargets(r) self.assertEqual(globals()["gblvar"],403) def test_yield_in_finally(self): """test yield in finally""" globals()["gblvar"] = 1 def setvar() : globals()["gblvar"] += 1 def test_yield_finally(): setvar() try: setvar();1/0 except:setvar() else: setvar() finally: setvar();yield 100 setvar();yield 100 setvar() setvar() try: k = test_yield_finally() while(1): next(k) except StopIteration: pass self.assertEqual(globals()["gblvar"],8) def test_string_partition(self): self.assertEqual('http://www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython'.partition('://'), ('http','://','www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython')) self.assertEqual('http://www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython'.partition('stringnotpresent'), ('http://www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython','','')) self.assertEqual('stringisnotpresent'.partition('presentofcoursenot'), ('stringisnotpresent','','')) self.assertEqual(''.partition('stringnotpresent'), ('','','')) self.assertEqual('onlymatchingtext'.partition('onlymatchingtext'), ('','onlymatchingtext','')) self.assertEqual('alotoftextherethatisapartofprefixonlyprefix_nosuffix'.partition('_nosuffix'), ('alotoftextherethatisapartofprefixonlyprefix','_nosuffix','')) self.assertEqual('noprefix_alotoftextherethatisapartofsuffixonlysuffix'.partition('noprefix_'), ('','noprefix_','alotoftextherethatisapartofsuffixonlysuffix')) self.assertEqual('\0'.partition('\0'), ('','\0','')) self.assertEqual('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9'.partition('\00\56\78'), ('\00\ff\67\56\d8\89\33\09\99\ee\20','\00\56\78','\45\77\e9')) self.assertEqual('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9'.partition('\78\45\77\e9'), ('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56','\78\45\77\e9','')) self.assertEqual('\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9'.partition('\ff\67\56\d8\89\33\09\99'), ('','\ff\67\56\d8\89\33\09\99','\ee\20\00\56\78\45\77\e9')) self.assertEqual(u'\ff\67\56\d8\89\33\09\99some random 8-bit text here \ee\20\00\56\78\45\77\e9'.partition('random'), (u'\ff\67\56\d8\89\33\09\99some ','random',' 8-bit text here \ee\20\00\56\78\45\77\e9')) self.assertEqual(u'\ff\67\56\d8\89\33\09\99some random 8-bit text here \ee\20\00\56\78\45\77\e9'.partition(u'\33\09\99some r'), (u'\ff\67\56\d8\89','\33\09\99some r','andom 8-bit text here \ee\20\00\56\78\45\77\e9')) self.assertRaises(ValueError,'sometextheretocauseanexeption'.partition,'') self.assertRaises(ValueError,''.partition,'') self.assertRaises(TypeError,'some\90text\ffhere\78to\88causeanexeption'.partition,None) self.assertRaises(TypeError,''.partition,None) prefix = """ this is some random text and it has lots of text """ sep = """ that is multilined and includes unicode \00 \56 \01 \02 \06 \12\33\67\33\ff \ee also""" suffix = """ \78\ff\43\12\23ok""" str = prefix + sep + suffix self.assertEqual(str.partition(sep),(prefix,sep,suffix)) self.assertEqual(str.partition('nomatch'),(str,'','')) self.assertRaises(TypeError,str.partition,None) self.assertRaises(ValueError,str.partition,'') def test_string_rpartition(self): self.assertEqual('http://www.codeplex.com/WorkItem/List.aspx?Project://Name=IronPython'.rpartition('://'), ('http://www.codeplex.com/WorkItem/List.aspx?Project','://','Name=IronPython')) self.assertEqual('http://www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython'.rpartition('stringnotpresent'), ('', '', 'http://www.codeplex.com/WorkItem/List.aspx?ProjectName=IronPython')) self.assertEqual('stringisnotpresent'.rpartition('presentofcoursenot'), ('','', 'stringisnotpresent')) self.assertEqual(''.rpartition('stringnotpresent'), ('','','')) self.assertEqual('onlymatchingtext'.rpartition('onlymatchingtext'), ('','onlymatchingtext','')) self.assertEqual('alotoftextherethatisapartofprefixonlyprefix_nosuffix'.rpartition('_nosuffix'), ('alotoftextherethatisapartofprefixonlyprefix','_nosuffix','')) self.assertEqual('noprefix_alotoftextherethatisapartofsuffixonlysuffix'.rpartition('noprefix_'), ('','noprefix_','alotoftextherethatisapartofsuffixonlysuffix')) self.assertEqual('\0'.partition('\0'), ('','\0','')) self.assertEqual('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\00\56\78\45\77\e9'.rpartition('\00\56\78'), ('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78','\00\56\78','\45\77\e9')) self.assertEqual('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9\78\45\77\e9'.rpartition('\78\45\77\e9'), ('\00\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9','\78\45\77\e9','')) self.assertEqual('\ff\67\56\d8\89\33\09\99\ee\20\00\56\78\45\77\e9'.rpartition('\ff\67\56\d8\89\33\09\99'), ('','\ff\67\56\d8\89\33\09\99','\ee\20\00\56\78\45\77\e9')) self.assertEqual(u'\ff\67\56\d8\89\33\09\99some random 8-bit text here \ee\20\00\56\78\45\77\e9'.rpartition('random'), (u'\ff\67\56\d8\89\33\09\99some ','random',' 8-bit text here \ee\20\00\56\78\45\77\e9')) self.assertEqual(u'\ff\67\56\d8\89\33\09\99some random 8-bit text here \ee\20\00\56\78\45\77\e9'.rpartition(u'\33\09\99some r'), (u'\ff\67\56\d8\89','\33\09\99some r','andom 8-bit text here \ee\20\00\56\78\45\77\e9')) self.assertRaises(ValueError,'sometextheretocauseanexeption'.rpartition,'') self.assertRaises(ValueError,''.rpartition,'') self.assertRaises(TypeError,'some\90text\ffhere\78to\88causeanexeption'.rpartition,None) self.assertRaises(TypeError,''.rpartition,None) prefix = """ this is some random text and it has lots of text """ sep = """ that is multilined and includes unicode \00 \56 \01 \02 \06 \12\33\67\33\ff \ee also""" suffix = """ \78\ff\43\12\23ok""" str = prefix + sep + suffix self.assertEqual(str.rpartition(sep),(prefix,sep,suffix)) self.assertEqual(str.rpartition('nomatch'),('','', str)) self.assertRaises(TypeError,str.rpartition,None) self.assertRaises(ValueError,str.rpartition,'') def test_string_startswith(self): class A:pass # failure scenarios self.assertRaises(TypeError,'string'.startswith,None) self.assertRaises(TypeError,'string'.startswith,(None,"strin","str")) self.assertRaises(TypeError,'string'.startswith,(None,)) self.assertRaises(TypeError,'string'.startswith,(["this","is","invalid"],"str","stri")) self.assertRaises(TypeError,'string'.startswith,(("string","this is invalid","this is also invalid",),)) self.assertRaises(TypeError,''.startswith,None) self.assertRaises(TypeError,''.startswith,(None,"strin","str")) self.assertRaises(TypeError,''.startswith,(None,)) self.assertRaises(TypeError,''.startswith,(["this","is","invalid"],"str","stri")) self.assertRaises(TypeError,''.startswith,(("string","this is invalid","this is also invalid",),)) # success scenarios self.assertEqual('no matching string'.startswith(("matching","string","here")),False) self.assertEqual('here matching string'.startswith(("matching","string","here")), True) self.assertEqual('here matching string'.startswith(("here", "matching","string","here")), True) self.assertEqual('here matching string'.startswith(("matching","here","string",)), True) self.assertEqual('here matching string'.startswith(("here matching string","here matching string","here matching string",)), True) s = 'here \12 \34 \ff \e5 \45 matching string' m = "here \12 \34 \ff \e5 \45 " m1 = " \12 \34 \ff \e5 \45 " n = "here \12 \34 \ff \e5 \46 " n1 = " \12 \34 \ff \e5 \46 " self.assertEqual(s.startswith((m,None)), True) self.assertEqual(s.startswith((m,123, ["here","good"])), True) self.assertEqual(s.startswith(("nomatch",m,123, ["here","good"])), True) # with start parameter = 0 self.assertEqual(s.startswith((m,None),0), True) self.assertEqual(s.startswith((n,"nomatch"),0), False) self.assertEqual(s.startswith((s,"nomatch"),0), True) self.assertEqual(s.startswith((s + "a","nomatch"),0), False) self.assertRaises(TypeError, s.startswith,(n,None),0) self.assertRaises(TypeError, s.startswith,(None, n),0) self.assertRaises(TypeError, s.startswith,(A, None, m),0) # with start parameter > 0 self.assertEqual(s.startswith((m1,None),4), True) self.assertEqual(s.startswith((m,"nomatch"),4), False) self.assertEqual(s.startswith((n1,"nomatch"),4), False) self.assertEqual(s.startswith((" \12 \34 \fd \e5 \45 ","nomatch"),4), False) self.assertEqual(s.startswith((s," \12 \34 \ff \e5 \45 matching string"),4), True) self.assertEqual(s.startswith((" \12 \34 \ff \e5 \45 matching string" + "a","nomatch"),4), False) self.assertRaises(TypeError, s.startswith,(n1,None),4) self.assertRaises(TypeError, s.startswith,(None, n1),4) self.assertRaises(TypeError, s.startswith,(A, None, m1),4) self.assertEqual(s.startswith(("g",None),len(s) - 1), True) self.assertEqual(s.startswith(("g","nomatch"),len(s)), False) self.assertEqual(s.startswith(("g","nomatch"),len(s) + 400), False) # with start parameter < 0 self.assertEqual(s.startswith(("string",None),-6), True) self.assertEqual(s.startswith(("stro","nomatch"),-6), False) self.assertEqual(s.startswith(("strong","nomatch"),-6), False) self.assertEqual(s.startswith(("stringandmore","nomatch"),-6), False) self.assertEqual(s.startswith(("prefixandstring","nomatch"),-6), False) self.assertRaises(TypeError, s.startswith,("string000",None),-6) self.assertRaises(TypeError, s.startswith,(None, "string"),-6) self.assertRaises(TypeError, s.startswith,(A, None, "string"),-6) self.assertEqual(s.startswith(("here",None),-len(s)), True) self.assertEqual(s.startswith((s,None),-len(s) - 1 ), True) self.assertEqual(s.startswith(("here",None),-len(s) - 400), True) # with start and end parameters # with +ve start , +ve end # end > start self.assertEqual(s.startswith((m1,None),4,len(s)), True) self.assertEqual(s.startswith((m1,None),4,len(s) + 100), True) self.assertEqual(s.startswith((n1,"nomatch"),len(s)), False) self.assertRaises(TypeError, s.startswith,(n1,None),4, len(s)) self.assertRaises(TypeError, s.startswith,(None, n1),4 , len(s) + 100) self.assertRaises(TypeError, s.startswith,(A, None, m1),4, len(s)) # end < start self.assertRaises(TypeError, s.startswith, (m1,None),4,3) self.assertRaises(TypeError, s.startswith, (m1,None),4,2) self.assertRaises(TypeError, s.startswith, (n1,None),4, 3) self.assertRaises(TypeError, s.startswith, (None, n1),4 , 3) self.assertRaises(TypeError, s.startswith, (A, None, m1),4, 0) # end == start self.assertEqual(s.startswith(("",None),4,4), True) self.assertEqual(s.startswith((m1,),4,4), False) self.assertRaises(TypeError, s.startswith,(n1,None),4, 4) self.assertRaises(TypeError, s.startswith,(None, n1),4 , 4) self.assertRaises(TypeError, s.startswith,(A, None, m1),4, 4) # with -ve start , +ve end # end > start self.assertEqual(s.startswith(("string",None),-6, len(s)), True) self.assertEqual(s.startswith(("string",None),-6, len(s) + 100), True) self.assertEqual(s.startswith(("string","nomatch"),-6, len(s) -2), False) self.assertEqual(s.startswith(("stro","nomatch"),-6, len(s)-1), False) self.assertEqual(s.startswith(("strong","nomatch"),-6,len(s)), False) self.assertRaises(TypeError, s.startswith,("string000",None),-6,len(s) + 3) self.assertRaises(TypeError, s.startswith,(None, "string"),-6, len(s)) self.assertRaises(TypeError, s.startswith,(A, None, "string"),-6,len(s)) self.assertEqual(s.startswith(("here",None),-len(s), 5), True) self.assertEqual(s.startswith(("here","nomatch"),-len(s), 2), False) self.assertEqual(s.startswith(("here",None),-len(s) - 1, 4 ), True) self.assertEqual(s.startswith(("here","nomatch"),-len(s) - 1, 2 ), False) # end < start self.assertRaises(TypeError, s.startswith, ("string",None),-6, 10) self.assertRaises(TypeError, s.startswith, ("string000",None),-6,10) self.assertRaises(TypeError, s.startswith, (None, "string"),-6, 10) self.assertRaises(TypeError, s.startswith, (A, None, "string"),-6,10) self.assertEqual(s.startswith(("stro","nomatch"),-6, 10), False) self.assertEqual(s.startswith(("strong","nomatch"),-6,10), False) # end == start self.assertRaises(TypeError,s.startswith, ("string",None),-6, len(s) -6) self.assertEqual(s.startswith(("",None),-6, len(s) -6), True) # with +ve start , -ve end # end > start self.assertEqual(s.startswith((m1,None),4,-5 ), True) self.assertEqual(s.startswith((m1,"nomatch"),4,-(4 + len(m) +1) ), False) self.assertRaises(TypeError, s.startswith,(n1,None),4, -5) self.assertRaises(TypeError, s.startswith,(None, n1),4 , -5) self.assertRaises(TypeError, s.startswith,(A, None, m1),4, -5) # end < start self.assertRaises(TypeError, s.startswith, (m1,None),4,-len(s) + 1) self.assertRaises(TypeError, s.startswith, (n1,None),4, -len(s)) self.assertRaises(TypeError, s.startswith, (None, n1),4 , -len(s)) self.assertRaises(TypeError, s.startswith, (A, None, m1),4, -len(s)) self.assertEqual(s.startswith((m1,),4,-len(s) + 1), False) self.assertEqual(s.startswith((m1,),4,-500), False) # end == start self.assertEqual(s.startswith(("",None),4,-len(s) + 4), True) self.assertEqual(s.startswith((m1,"nomatch"),4,-len(s) + 4), False) self.assertRaises(TypeError, s.startswith,(n1,None),4, -len(s) + 4) self.assertRaises(TypeError, s.startswith,(None, n1),4 , -len(s) + 4) self.assertRaises(TypeError, s.startswith,(A, None, m1),4, -len(s) + 4) # with -ve start , -ve end # end > start self.assertEqual(s.startswith(("stri",None),-6, -2), True) self.assertEqual(s.startswith(("string","nomatch"),-6, -1), False) self.assertEqual(s.startswith(("stro","nomatch"),-6, -1), False) self.assertEqual(s.startswith(("strong","nomatch"),-6,-1), False) self.assertEqual(s.startswith(("stringand","nomatch"),-6,-1), False) self.assertRaises(TypeError, s.startswith,("string000",None),-6, -1) self.assertRaises(TypeError, s.startswith,(None, "string"),-6, -1) self.assertRaises(TypeError, s.startswith,(A, None, "string"),-6,-1) self.assertEqual(s.startswith(("here","nomatch"),-len(s), -5), True) self.assertEqual(s.startswith(("here","nomatch"),-len(s), -len(s) + 2), False) self.assertEqual(s.startswith(("here","nomatch"),-len(s) - 1, -5 ), True) self.assertEqual(s.startswith(("here","nomatch"),-len(s) - 1, -len(s) + 2), False) # end < start self.assertRaises(TypeError, s.startswith, ("string",None),-6, -7) self.assertRaises(TypeError, s.startswith, ("string000",None),-6,-8) self.assertRaises(TypeError, s.startswith, (None, "string"),-6, -8) self.assertRaises(TypeError, s.startswith, (A, None, "string"),-6,-8) self.assertEqual(s.startswith(("stro","nomatch"),-6, -8), False) self.assertEqual(s.startswith(("strong","nomatch"),-6,-8), False) # end == start self.assertEqual(s.startswith(("string","nomatch"),-6, -6), False) self.assertEqual(s.startswith(("",None),-6, -6), True) def test_string_endswith(self): #failue scenarios class A:pass self.assertRaises(TypeError,'string'.endswith,None) self.assertRaises(TypeError,'string'.endswith,(None,"tring","ing")) self.assertRaises(TypeError,'string'.endswith,(None,)) self.assertRaises(TypeError,'string'.endswith,(["this","is","invalid"],"ring","ing")) self.assertRaises(TypeError,'string'.endswith,(("string","this is invalid","this is also invalid",),)) self.assertRaises(TypeError,''.endswith,None) self.assertRaises(TypeError,''.endswith,(None,"tring","ring")) self.assertRaises(TypeError,''.endswith,(None,)) self.assertRaises(TypeError,''.endswith,(["this","is","invalid"],"tring","ring")) self.assertRaises(TypeError,''.endswith,(("string","this is invalid","this is also invalid",),)) #Positive scenarios self.assertEqual('no matching string'.endswith(("matching","no","here")),False) self.assertEqual('here matching string'.endswith(("string", "matching","nomatch")), True) self.assertEqual('here matching string'.endswith(("string", "matching","here","string")), True) self.assertEqual('here matching string'.endswith(("matching","here","string",)), True) self.assertEqual('here matching string'.endswith(("here matching string","here matching string","here matching string",)), True) s = 'here \12 \34 \ff \e5 \45 matching string' m = "\e5 \45 matching string" m1 = "\e5 \45 matching " n = "\e5 \45 matching strinh" n1 = "\e5 \45 matching_" self.assertEqual(s.endswith((m,None)), True) self.assertEqual(s.endswith((m,123, ["string","good"])), True) self.assertEqual(s.endswith(("nomatch",m,123, ["here","string"])), True) #With starts parameter = 0 self.assertEqual(s.endswith((m,None),0), True) self.assertEqual(s.endswith((n,"nomatch"),0), False) self.assertEqual(s.endswith((s,"nomatch"),0), True) self.assertEqual(s.endswith((s + "a","nomatch"),0), False) self.assertRaises(TypeError, s.endswith,(n,None),0) self.assertRaises(TypeError, s.endswith,(None, n),0) self.assertRaises(TypeError, s.endswith,(A, None, m),0) #With starts parameter > 0 self.assertEqual(s.endswith((m,None),4), True) self.assertEqual(s.endswith((m,"nomatch"),4), True) self.assertEqual(s.endswith((n1,"nomatch"),4), False) self.assertEqual(s.endswith((" \12 \34 \fd \e5 \45 ","nomatch"),4), False) self.assertEqual(s.endswith((s," \12 \34 \ff \e5 \45 matching string"),4), True) self.assertEqual(s.endswith((" \12 \34 \ff \e5 \45 matching string" + "a","nomatch"),4), False) self.assertRaises(TypeError, s.endswith,(n1,None),4) self.assertRaises(TypeError, s.endswith,(None, n1),4) self.assertRaises(TypeError, s.endswith,(A, None, m1),4) self.assertEqual(s.endswith(("g",None),len(s) - 1), True) self.assertEqual(s.endswith(("g","nomatch"),len(s)), False) self.assertEqual(s.endswith(("g","nomatch"),len(s) + 400), False) #With starts parameter < 0 self.assertEqual(s.endswith(("string",None),-6), True) self.assertEqual(s.endswith(("ring",None),-6), True) self.assertEqual(s.endswith(("rong","nomatch"),-6), False) self.assertEqual(s.endswith(("strong","nomatch"),-6), False) self.assertEqual(s.endswith(("stringandmore","nomatch"),-6), False) self.assertEqual(s.endswith(("prefixandstring","nomatch"),-6), False) self.assertRaises(TypeError, s.endswith,("string000",None),-6) self.assertRaises(TypeError, s.endswith,(None, "string"),-6) self.assertRaises(TypeError, s.endswith,(A, None, "string"),-6) self.assertEqual(s.endswith(("string",None),-len(s)), True) self.assertEqual(s.endswith((s,None),-len(s) - 1 ), True) self.assertEqual(s.endswith(("string",None),-len(s) - 400), True) #With starts , end parameter # with +ve start , +ve end # end > start self.assertEqual(s.endswith((m1,"nomatch"),4,len(s)), False) self.assertEqual(s.endswith((m1,"nomatch"),4,len(s) - 6), True) self.assertEqual(s.endswith((m1,"nomatch"),4,len(s) - 8), False) self.assertEqual(s.endswith((n1,"nomatch"),4,len(s) - 6), False) self.assertRaises(TypeError, s.endswith,(n1,None),4, len(s)-6) self.assertRaises(TypeError, s.endswith,(None, n1),4 , len(s)-6) self.assertRaises(TypeError, s.endswith,(A, None, m1),4, len(s)-6) # end < start self.assertRaises(TypeError, s.endswith, (m1,None),4,3) self.assertRaises(TypeError, s.endswith, (n1,None),4, 3) self.assertRaises(TypeError, s.endswith, (None, n1),4 , 3) self.assertRaises(TypeError, s.endswith, (A, None, m1),4, 0) # end == start self.assertEqual(s.endswith(("",None),4,4), True) self.assertEqual(s.endswith((m1,),4,4), False) self.assertRaises(TypeError, s.endswith,(n1,None),4, 4) self.assertRaises(TypeError, s.endswith,(None, n1),4 , 4) self.assertRaises(TypeError, s.endswith,(A, None, m1),4, 4) # with -ve start , +ve end # end > start self.assertEqual(s.endswith((m1,None),-30, len(s) -6), True) self.assertEqual(s.endswith((m1,None),-300, len(s) -6 ), True) self.assertEqual(s.endswith((m1,"nomatch"),-5, len(s) -6), False) self.assertEqual(s.endswith(("string",None),-30, len(s) + 6), True) self.assertEqual(s.endswith(("string",None),-300, len(s) + 6 ), True) self.assertEqual(s.endswith(("here",None),-len(s), 4), True) self.assertEqual(s.endswith(("here",None),-300, 4 ), True) self.assertEqual(s.endswith(("hera","nomatch"),-len(s), 4), False) self.assertEqual(s.endswith(("hera","nomatch"),-300, 4 ), False) self.assertRaises(TypeError, s.endswith,("here000",None),-len(s),4) self.assertRaises(TypeError, s.endswith,(None, "here"),-len(s),4) self.assertRaises(TypeError, s.endswith,(A, None, "here"),-len(s),4) # end < start self.assertRaises(TypeError, s.endswith, ("here",None),-len(s) + 4, 2) self.assertRaises(TypeError, s.endswith, ("here000",None),-len(s) + 4, 2) self.assertRaises(TypeError, s.endswith, (None, "he"),-len(s) + 4, 2) self.assertRaises(TypeError, s.endswith, (A, None, "string"),-len(s) + 4, 2) self.assertEqual(s.endswith(("hera","nomatch"),-len(s) + 4, 2), False) # end == start self.assertRaises(TypeError,s.endswith, ("here",None),-6, len(s) -6) self.assertEqual(s.endswith(("",None),-6, len(s) -6), True) # with +ve start , -ve end # end > start self.assertEqual(s.endswith((m1,None),4,-6 ), True) self.assertEqual(s.endswith((m1,"nomatch"),4,-7), False) self.assertRaises(TypeError, s.endswith,(n1,None),4, -6) self.assertRaises(TypeError, s.endswith,(None, n1),4 , -6) self.assertRaises(TypeError, s.endswith,(A, None, m1),4, -6) # end < start self.assertRaises(TypeError, s.endswith, (m1,None),4,-len(s) + 1) self.assertRaises(TypeError, s.endswith, (n1,None),4, -len(s)) self.assertRaises(TypeError, s.endswith, (None, n1),4 , -len(s)) self.assertRaises(TypeError, s.endswith, (A, None, m1),4, -len(s)) self.assertEqual(s.endswith((m1,),4,-len(s) + 1), False) self.assertEqual(s.endswith((m1,),4,-500), False) # end == start self.assertEqual(s.endswith(("",None),4,-len(s) + 4), True) self.assertEqual(s.endswith((m1,"nomatch"),4,-len(s) + 4), False) self.assertRaises(TypeError, s.endswith,(n1,None),4, -len(s) + 4) self.assertRaises(TypeError, s.endswith,(None, n1),4 , -len(s) + 4) self.assertRaises(TypeError, s.endswith,(A, None, m1),4, -len(s) + 4) # with -ve start , -ve end # end > start self.assertEqual(s.endswith(("stri",None),-6, -2), True) self.assertEqual(s.endswith(("string","nomatch"),-6, -1), False) self.assertEqual(s.endswith(("stro","nomatch"),-6, -2), False) self.assertEqual(s.endswith(("stron","nomatch"),-6,-1), False) self.assertEqual(s.endswith(("stringand","nomatch"),-6,-1), False) self.assertRaises(TypeError, s.endswith,("string000",None),-6, -1) self.assertRaises(TypeError, s.endswith,(None, "string"),-6, -1) self.assertRaises(TypeError, s.endswith,(A, None, "string"),-6,-1) self.assertEqual(s.endswith(("here","nomatch"),-len(s), -len(s)+4), True) self.assertEqual(s.endswith(("here","nomatch"),-len(s), -len(s) + 2), False) self.assertEqual(s.endswith(("here","nomatch"),-len(s) - 1, -len(s)+4 ), True) self.assertEqual(s.endswith(("here","nomatch"),-len(s) - 1, -len(s) + 2), False) # end < start self.assertRaises(TypeError, s.endswith, ("here",None),-len(s) + 5, -len(s) + 4) self.assertRaises(TypeError, s.endswith, ("here000",None),-len(s) + 5, -len(s) + 4) self.assertRaises(TypeError, s.endswith, (None, "here"),-len(s) + 5, -len(s) + 4) self.assertRaises(TypeError, s.endswith, (A, None, "here"),-len(s) + 5, -len(s) + 4) self.assertEqual(s.endswith(("hera","nomatch"),-len(s) + 5, -len(s) + 4), False) # end == start self.assertEqual(s.endswith(("here","nomatch"),-6, -6), False) self.assertEqual(s.endswith(("",None),-6, -6), True) def test_any(self): class A: pass a = A() class enum: def __iter__(self): return [1,2,3].__iter__() self.assertEqual(any(enum()),True) # enumerable class self.assertRaises(TypeError,any,a)# non - enumerable class self.assertRaises(TypeError,any,0.000000) # non - enumerable object self.assertEqual(any([0.0000000,0,False]),False)# all False self.assertEqual(any((0,False,a)),True) # True class self.assertEqual(any((0,False,None,"")),False) # None and "" self.assertEqual(any([]),False) # no items in array self.assertEqual(any([None]),False) # only None in array self.assertEqual(any([None,a]),True) # only None and an Object in array self.assertEqual(any({0:0,False:"hi"}),False) # Dict with All False self.assertEqual(any({True:0,False:"hi"}),True) # Dict with onely 1 True self.assertEqual(any({a:"hello",False:"bye"}),True) # Dict with Class class mylist(list): def __iter__(self): return [1,2,0].__iter__() self.assertEqual(any(mylist()),True) class raiser: def __nonzero__(self): raise RuntimeError self.assertEqual(any([None,False,0,1,raiser()]),True) # True before the raiser() self.assertRaises(RuntimeError,any,[None,False,0,0,raiser(),1,2]) # True after the raiser() self.assertRaises(RuntimeError,any,{None:"",0:1000,raiser():True}) # raiser in dict self.assertRaises(TypeError,any) # any without any params self.assertRaises(TypeError,any,(20,30,40),(50,60,70))# any with more params def test_all(self): class A: pass a = A() class enum: def __iter__(self): return [1,2,3].__iter__() self.assertEqual(all(enum()),True) # enumerable class self.assertRaises(TypeError,all,a) # non - enumerable class self.assertRaises(TypeError,all,0.000000) # non - enumerable object self.assertEqual(all([0.0000000,0,False]),False) # all False self.assertEqual(all([True,1.89,"hello",a]),True) # all true array ( bool, double, str, class) self.assertEqual(all((True,1.89,"hello",a)),True) # all true tuple ( bool, double, str, class) self.assertEqual(all((True,"hello",a,None)),False) # one None in Tuple self.assertEqual(all((0,False,None,"")),False) # Tuple with None and "" self.assertEqual(all([]),True) # with empty array self.assertEqual(all([None]),False) # arry with onle None self.assertEqual(all([a,None]),False) # array with None and Class self.assertEqual(all({"hello":"hi",True:0,False:"hi",0:0}),False) # dict with some True, False self.assertEqual(all({True:0,100:"hi","hello":200,a:100}),True) # dict with all True class mylist(list): def __iter__(self): return [1,2,0].__iter__() self.assertEqual(all(mylist()),False) class raiser: def __nonzero__(self): raise RuntimeError self.assertEqual(all([None,False,0,1,raiser()]),False) # array With raiser() after false self.assertEqual(all({None:"",0:1000,raiser():True}),False) # Dict with raiser after falls self.assertRaises(RuntimeError,all,[raiser(),200,None,False,0,1,2])# Array with raiser before False self.assertRaises(RuntimeError,all,{raiser():True,200:"",300:1000})# Dict with raiser before False self.assertRaises(TypeError,all) # no params self.assertRaises(TypeError,all,(20,30,40),(50,60,70)) # extra params def test_max_with_kwarg(self): class A(int): def __len__(self): return 10 a=A() self.assertEqual(max(a,"aaaaaaa",key=len),a) # 2 args + buitin method def userfunc(arg): if(arg == None):return -1 if(type(arg) == bool):return 0 if(type(arg) == int):return 10 if(type(arg) == str):return len(arg) if(type(arg) == list):return len(arg) return 40 self.assertEqual(max(["b","aaaaaaaaaaaaaaaaa",["this",True,"is","Python"],0, a, None],key=userfunc),a)# array + user method self.assertEqual(max(("b","aaa",["this",True,"is","Python"],0, 1.8, True,a, None),key=userfunc),1.8)# Tuple + user method self.assertEqual(max("b","aaa",["this",None,"is","Python"], True,None,key=userfunc),["this",None,"is","Python"])# param list + user method # error scenarios #apply invalid key k try: max("aaaaa","b",k=len) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply non-existing Name try: max([1,2,3,4],key=method) except NameError:pass else: self.fail("Expected TypeError, but found None") #apply non-callable Method method = 100 try: max([1,2,3,4],key=method) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply callable on empty list try: max([],key=len) except ValueError:pass else: self.fail("Expected ValueError, but found None") #apply callable on non-enumerable type try: max(None,key=len) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply Method on non callable class class B:pass try: max((B(),"hi"),key=len) except AttributeError:pass else: self.fail("Expected AttributeError, but found None") def test_min_with_kwarg(self): class A(int): def __len__(self): return 0 a=A() self.assertEqual(min(a,"aaaaaaa",key=len),a) # 2 args + buitin method def userfunc(arg): if(arg == None):return 100 if(type(arg) == bool):return 90 if(type(arg) == int):return 80 if(type(arg) == str):return len(arg) if(type(arg) == list):return len(arg) return 5 self.assertEqual(min(["aaaaaaaaaaaaaaaaa",["this",True,"is","Python","Iron","Python"],0, a, None],key=userfunc),a)# array + user method self.assertEqual(min(("aaaaaaaaaaaaa",["this",True,"is","Python","Iron","Python"],0, 1.8, True,a, None),key=userfunc),1.8)# Tuple + user method self.assertEqual(min("aaaaaaaaaaaaaa",["this",None,"is","Python"], True,None,key=userfunc),["this",None,"is","Python"])# param list + user method # error scenarios #apply invalid key k try: min("aaaaa","b",k=len) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply non-existing Name try: min([1,2,3,4],key=method) except NameError:pass else: self.fail("Expected TypeError, but found None") #apply non-callable Method method = 100; try: min([1,2,3,4],key=method) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply callable on empty list try: min([],key=len) except ValueError:pass else: self.fail("Expected ValueError, but found None") #apply callable on non-enumerable type try: min(None,key=len) except TypeError:pass else: self.fail("Expected TypeError, but found None") #apply Method on non callable class class B:pass try: min((B(),"hi"),key=len) except AttributeError:pass else: self.fail("Expected AttributeError, but found None") def test_missing(self): # dict base class should not have __missing__ self.assertEqual(hasattr(dict, "__missing__"), False) # positive cases class A(dict): def __missing__(self,key): return 100 a = A({1:1, "hi":"bye"}) def fun():pass self.assertEqual(hasattr(A, "__missing__"), True) self.assertEqual( (a["hi"],a[23112],a["das"], a[None],a[fun],getattr(a,"__missing__")("IP")),("bye",100,100,100,100,100)) # negative case try: a[not_a_name] except NameError: pass except: self.fail("Expected NameError, but found", sys.exc_info()) else: self.fail("Expected NameError, but found None") # extra paramaters self.assertRaises(TypeError,a.__missing__,300,400) # less paramaters self.assertRaises(TypeError,a.__missing__) self.assertRaises(TypeError,a.__getitem__,A()) #invalid __missing__ methods A.__missing__ = "dont call me!" self.assertRaises(TypeError,a.__getitem__,300) # set missing to with new function def newmissing(self,key): return key/2 A.__missing__ = newmissing self.assertEqual( a[999], 999/2); self.assertRaises(TypeError,a.__getitem__,"sometext") del A.__missing__ self.assertEqual( a[1], 1); self.assertRaises(KeyError,a.__getitem__,"sometext") # inheritance scenarios #basic inheritance class M(dict): def __missing__(self,key): return 99 class N(M):pass self.assertEqual(N({"hi":"bye"})["none"], 99) class C: def __missing__(self,key): return 100 class D(C,dict):pass self.assertEqual(D({"hi":"bye"})["none"], 100) # inheritance -> override __missing__ class E(dict): def __missing__(self,key): return 100 class F(E,dict): def __missing__(self,key): return 50 self.assertEqual(F({"hi":"bye"})["none"], 50) def test_with(self): # nested with can not have a yield class J: def __enter__(self):pass def __exit__(self,a,b,c):pass try: c = compile( """def nest(): with J(): with J(): yield 100 ""","","exec") except SyntaxError,e: pass def test_importwarning(self): exc_list = [] exc_list.append(ImportWarning()) exc_list.append(ImportWarning("some message")) import exceptions exc_list.append(exceptions.ImportWarning()) exc_list.append(exceptions.ImportWarning("some message")) for exc in exc_list: try: raise exc except exceptions.ImportWarning, e: pass def test_overflowwarning(self): self.assertRaises(AttributeError, lambda: exceptions.OverflowWarning) def test_cp5609(self): from os import remove temp_name = "test_cp5609.txt" with open(temp_name, "w") as f: self.assertTrue(not f.closed) f.write("xyz") self.assertTrue(hasattr(f, "__enter__")) self.assertTrue(hasattr(f, "__exit__")) self.assertTrue(f.closed) with open(temp_name, "r") as f: self.assertTrue(not f.closed) self.assertEqual(f.readlines(), ["xyz"]) self.assertTrue(hasattr(f, "__enter__")) self.assertTrue(hasattr(f, "__exit__")) self.assertTrue(f.closed) remove(temp_name) run_test(__name__)
44.932296
225
0.546988
6,734
57,738
4.62875
0.070092
0.104427
0.102663
0.074238
0.751556
0.705518
0.652615
0.570966
0.485338
0.385467
0
0.047422
0.297309
57,738
1,284
226
44.96729
0.720842
0.072656
0
0.346626
0
0.018405
0.147549
0.029495
0
0
0
0
0.379346
0
null
null
0.066462
0.013292
null
null
0.002045
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
3
cc1a6d5f9d1cf54bd43d2cb96fdc01e27ee80701
219
py
Python
data/data/models/structures/zone/cube.py
maosplx/L2py
5d81b2ea150c0096cfce184706fa226950f7f583
[ "MIT" ]
7
2020-09-01T21:52:37.000Z
2022-02-25T16:00:08.000Z
data/data/models/structures/zone/cube.py
maosplx/L2py
5d81b2ea150c0096cfce184706fa226950f7f583
[ "MIT" ]
4
2021-09-10T22:15:09.000Z
2022-03-25T22:17:43.000Z
data/data/models/structures/zone/cube.py
maosplx/L2py
5d81b2ea150c0096cfce184706fa226950f7f583
[ "MIT" ]
9
2020-09-01T21:53:39.000Z
2022-03-30T12:03:04.000Z
from dataclasses import dataclass, field from data.models.structures.zone.farm import ZoneFarm @dataclass class ZoneCube(ZoneFarm): x1: Int32 x2: Int32 y1: Int32 y2: Int32 z1: Int32 z2: Int32
15.642857
53
0.69863
29
219
5.275862
0.689655
0
0
0
0
0
0
0
0
0
0
0.107143
0.232877
219
13
54
16.846154
0.803571
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.2
0
0.9
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
1
0
0
3
cc20580d46bc82deead369395cb44993fef83514
395
py
Python
test1.py
geoser/azureservices
00f713275e86e195b0dc492a4590c8c503042720
[ "MIT" ]
null
null
null
test1.py
geoser/azureservices
00f713275e86e195b0dc492a4590c8c503042720
[ "MIT" ]
null
null
null
test1.py
geoser/azureservices
00f713275e86e195b0dc492a4590c8c503042720
[ "MIT" ]
null
null
null
import resources import sql.sql_deployment as sd from sql.sql_parameters import SqlParameters from helper import ServiceType s = 'VM' #res = resources.get_all_tks_resource_groups() #params = SqlParameters() #params.administrator_password = "})&B7Tq33n1f" #p = sd.get_parameters(params) #t = sd.get_template() #resources.create_deployment("89aa748b-0621-4ec3-865a-ab0cde103b13", t, p) pass
20.789474
74
0.782278
53
395
5.641509
0.622642
0.040134
0
0
0
0
0
0
0
0
0
0.067989
0.106329
395
19
75
20.789474
0.779037
0.602532
0
0
0
0
0.013158
0
0
0
0
0
0
1
0
false
0.166667
0.666667
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
1
0
0
3
cc273e213e3449521b706a7efec7442857553a6b
317
py
Python
allennlp/nn/parallel/__init__.py
MSLars/allennlp
2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475
[ "Apache-2.0" ]
11,433
2017-06-27T03:08:46.000Z
2022-03-31T18:14:33.000Z
allennlp/nn/parallel/__init__.py
MSLars/allennlp
2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475
[ "Apache-2.0" ]
4,006
2017-06-26T21:45:43.000Z
2022-03-31T02:11:10.000Z
allennlp/nn/parallel/__init__.py
MSLars/allennlp
2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475
[ "Apache-2.0" ]
2,560
2017-06-26T21:16:53.000Z
2022-03-30T07:55:46.000Z
from allennlp.nn.parallel.sharded_module_mixin import ShardedModuleMixin from allennlp.nn.parallel.ddp_accelerator import ( DdpAccelerator, DdpWrappedModel, TorchDdpAccelerator, ) from allennlp.nn.parallel.fairscale_fsdp_accelerator import ( FairScaleFsdpAccelerator, FairScaleFsdpWrappedModel, )
28.818182
72
0.820189
29
317
8.793103
0.62069
0.141176
0.164706
0.258824
0
0
0
0
0
0
0
0
0.123028
317
10
73
31.7
0.917266
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.3
0
0.3
0
1
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
cc29724919d906e40b670e6eac42bbc5877eb350
4,652
py
Python
src/appservice-kube/azext_appservice_kube/tests/latest/test_appservice_kube_scenario.py
haroonf/azure-cli-extensions
61c044d34c224372f186934fa7c9313f1cd3a525
[ "MIT" ]
1
2022-01-25T07:33:18.000Z
2022-01-25T07:33:18.000Z
src/appservice-kube/azext_appservice_kube/tests/latest/test_appservice_kube_scenario.py
haroonf/azure-cli-extensions
61c044d34c224372f186934fa7c9313f1cd3a525
[ "MIT" ]
9
2022-03-25T19:35:49.000Z
2022-03-31T06:09:47.000Z
src/appservice-kube/azext_appservice_kube/tests/latest/test_appservice_kube_scenario.py
haroonf/azure-cli-extensions
61c044d34c224372f186934fa7c9313f1cd3a525
[ "MIT" ]
1
2022-03-10T22:13:02.000Z
2022-03-10T22:13:02.000Z
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os import requests from azure.cli.testsdk.scenario_tests import AllowLargeResponse from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, JMESPathCheck) TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) # TODO class AppserviceKubernetesScenarioTest(ScenarioTest): pass # not lima-specific class WebappBasicE2EKubeTest(ScenarioTest): @ResourceGroupPreparer(location='canadacentral') def test_linux_webapp_quick_create_kube(self, resource_group): webapp_name = self.create_random_name( prefix='webapp-quick-linux', length=24) plan = self.create_random_name(prefix='plan-quick-linux', length=24) self.cmd( 'appservice plan create -g {} -n {} --is-linux'.format(resource_group, plan)) self.cmd('webapp create -g {} -n {} --plan {} -i patle/ruby-hello'.format( resource_group, webapp_name, plan)) r = requests.get( 'http://{}.azurewebsites.net'.format(webapp_name), timeout=240) # verify the web page self.assertTrue('Ruby on Rails in Web Apps on Linux' in str(r.content)) # verify app settings self.cmd('webapp config appsettings list -g {} -n {}'.format(resource_group, webapp_name), checks=[ JMESPathCheck('[0].name', 'WEBSITES_ENABLE_APP_SERVICE_STORAGE'), JMESPathCheck('[0].value', 'false'), ]) self.cmd('webapp update -g {} -n {} --https-only true'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", True)]) self.cmd('webapp update -g {} -n {} --https-only false'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", False)]) @ResourceGroupPreparer(location="westus2") def test_win_webapp_quick_create_kube(self, resource_group): webapp_name = self.create_random_name(prefix='webapp-quick', length=24) plan = self.create_random_name(prefix='plan-quick', length=24) self.cmd('appservice plan create -g {} -n {}'.format(resource_group, plan)) r = self.cmd('webapp create -g {} -n {} --plan {} --deployment-local-git'.format( resource_group, webapp_name, plan)).get_output_in_json() self.assertTrue(r['ftpPublishingUrl'].startswith('ftp://')) self.cmd('webapp config appsettings list -g {} -n {}'.format(resource_group, webapp_name), checks=[ JMESPathCheck('[0].name', 'WEBSITE_NODE_DEFAULT_VERSION'), JMESPathCheck('[0].value', '12.13.0'), ]) self.cmd('webapp update -g {} -n {} --https-only true'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", True)]) self.cmd('webapp update -g {} -n {} --https-only false'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", False)]) @ResourceGroupPreparer(name_prefix="clitest", random_name_length=24, location="westus2") def test_win_webapp_quick_create_runtime_kube(self, resource_group): webapp_name = self.create_random_name(prefix='webapp-quick', length=24) webapp_name_2 = self.create_random_name(prefix='webapp-quick', length=24) plan = self.create_random_name(prefix='plan-quick', length=24) self.cmd('appservice plan create -g {} -n {}'.format(resource_group, plan)) r = self.cmd('webapp create -g {} -n {} --plan {} --deployment-local-git -r "node|14LTS"'.format( resource_group, webapp_name, plan)).get_output_in_json() self.assertTrue(r['ftpPublishingUrl'].startswith('ftp://')) self.cmd('webapp config appsettings list -g {} -n {}'.format(resource_group, webapp_name), checks=[ JMESPathCheck('[0].name', 'WEBSITE_NODE_DEFAULT_VERSION'), JMESPathCheck('[0].value', '~14'), ]) r = self.cmd('webapp create -g {} -n {} --plan {} --deployment-local-git -r "DOTNETCORE|3.1"'.format( resource_group, webapp_name_2, plan)).get_output_in_json() self.assertTrue(r['ftpPublishingUrl'].startswith('ftp://')) self.cmd('webapp update -g {} -n {} --https-only true'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", True)]) self.cmd('webapp update -g {} -n {} --https-only false'.format(resource_group, webapp_name), checks=[JMESPathCheck("httpsOnly", False)])
58.886076
144
0.646389
548
4,652
5.310219
0.239051
0.08488
0.104467
0.12646
0.717869
0.707904
0.696564
0.687973
0.664948
0.652234
0
0.010592
0.167885
4,652
78
145
59.641026
0.741152
0.08577
0
0.431034
0
0.034483
0.289585
0.036993
0
0
0
0.012821
0.068966
1
0.051724
false
0.017241
0.068966
0
0.155172
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
3
0bc7cdeb5c2ce19f4048e618d45a3e5e99b07e64
1,043
py
Python
Semana 3/knapsack/test_pytest_knapsack.py
juandausa/CompetitiveProgrammingCoreSkills
1ef0d902b6c05afba4b44c34ade87c376187fd1d
[ "MIT" ]
null
null
null
Semana 3/knapsack/test_pytest_knapsack.py
juandausa/CompetitiveProgrammingCoreSkills
1ef0d902b6c05afba4b44c34ade87c376187fd1d
[ "MIT" ]
null
null
null
Semana 3/knapsack/test_pytest_knapsack.py
juandausa/CompetitiveProgrammingCoreSkills
1ef0d902b6c05afba4b44c34ade87c376187fd1d
[ "MIT" ]
null
null
null
from item import Item from knapsack import calculate_best_items def test_calculate_for_weight_one(): items = [Item(1, 1), Item(1, 2), Item(1, 9), Item(2, 80000)] assert calculate_best_items(items, 1) == 9 def test_stament_one(): '''3 5 1 3 1 2 1 1 ''' items = [Item(1, 3), Item(1, 2), Item(1, 1)] assert calculate_best_items(items, 5) == 6 def test_stament_two(): ''' 5 10 1 4 2 5 1 2 4 6 8 12 ''' items = [Item(1, 4), Item(2, 5), Item(1, 2), Item(4, 6), Item(8, 12)] assert calculate_best_items(items, 10) == 18 def test_stament_three(): ''' 1 5 8 3 ''' items = [Item(8,3)] assert calculate_best_items(items, 5) == 0 def test_stament_four(): '''4 10 6 30 3 14 4 16 2 9 ''' items = [Item(6, 30), Item(3, 14), Item(4, 16), Item(2, 9)] assert calculate_best_items(items, 10) == 46
20.45098
74
0.489933
157
1,043
3.101911
0.216561
0.082136
0.221766
0.246407
0.355236
0.250513
0
0
0
0
0
0.147014
0.373921
1,043
50
75
20.86
0.598775
0.081496
0
0
0
0
0
0
0
0
0
0
0.294118
1
0.294118
false
0
0.117647
0
0.411765
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0bd123d029df26836a68289fa0be2fba150fc7db
733
py
Python
net/DSSnet/DSSnet_hosts.py
JinLabIIT/DSSnet
3b9c1771eae8e2a1157d36500bce4b6e84e52c4d
[ "Apache-2.0" ]
8
2016-11-28T01:22:17.000Z
2021-06-01T13:25:48.000Z
net/DSSnet/DSSnet_hosts.py
JinLabIIT/DSSnet
3b9c1771eae8e2a1157d36500bce4b6e84e52c4d
[ "Apache-2.0" ]
2
2018-12-18T14:38:32.000Z
2019-02-23T02:35:08.000Z
net/DSSnet/DSSnet_hosts.py
JinLabIIT/DSSnet
3b9c1771eae8e2a1157d36500bce4b6e84e52c4d
[ "Apache-2.0" ]
2
2016-11-28T01:22:19.000Z
2018-03-02T18:32:08.000Z
class DSSnet_hosts: 'class for meta process/IED info' p_id = 0 def __init__(self, msg, IED_id, command, ip, pipe = True): self.properties= msg self.IED_id = IED_id self.process_id= DSSnet_hosts.p_id self.command = command self.ip = ip self.pipe = pipe DSSnet_hosts.p_id +=1 def number_processes(self): return DSSnet_hosts.p_id def get_host_name(self): return self.IED_id def get_ip(self): return self.ip def get_process_command(self): return self.command def display_process(self): return('%s : %s : %s \n' % (self.process_id , self.IED_id, self.properties))
25.275862
84
0.581173
101
733
3.960396
0.29703
0.0625
0.0675
0.105
0
0
0
0
0
0
0
0.004057
0.327422
733
28
85
26.178571
0.807302
0.042292
0
0
0
0
0.062756
0
0
0
0
0
0
1
0.285714
false
0
0
0.238095
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0bdedecd1b7f159ac93edb23afb398f6f3976db3
1,059
py
Python
atrous_conv.py
pit-ray/Anime-Semantic-Segmentation-GAN
8b41b3bd89e6eb6093f0c09f95dd6f89cfdeee1a
[ "MIT" ]
36
2020-02-27T12:56:22.000Z
2022-03-09T20:03:25.000Z
atrous_conv.py
pit-ray/Anime-Semantic-Segmentation-GAN
8b41b3bd89e6eb6093f0c09f95dd6f89cfdeee1a
[ "MIT" ]
3
2020-05-27T15:26:01.000Z
2021-08-22T05:17:37.000Z
atrous_conv.py
pit-ray/Anime-Semantic-Segmentation-GAN
8b41b3bd89e6eb6093f0c09f95dd6f89cfdeee1a
[ "MIT" ]
3
2020-12-14T08:46:13.000Z
2021-06-25T00:33:29.000Z
# coding: utf-8 import chainer.links as L from spectral_norms import SNConv, SNHookConv class AtrousConv(L.DilatedConvolution2D): def __init__(self, in_channels, out_channels, ksize=None, rate=1, initialW=None): super().__init__(in_channels, out_channels, ksize=ksize, stride=1, pad=rate, dilate=rate, initialW=initialW) class AtrousSNConv(SNConv): def __init__(self, in_channels, out_channels, ksize=None, rate=1, initialW=None): super().__init__(in_channels, out_channels, ksize=ksize, stride=1, pad=rate, dilate=rate, initialW=initialW) class AtrousSNHookConv(SNHookConv): def __init__(self, in_channels, out_channels, ksize=None, rate=1, initialW=None): super().__init__(in_channels, out_channels, ksize=ksize, stride=1, pad=rate, dilate=rate, initialW=initialW) def define_atrous_conv(opt): if opt.conv_norm == 'original': return AtrousConv if opt.conv_norm == 'spectral_norm': return AtrousSNConv if opt.conv_norm == 'spectral_norm_hook': return AtrousSNHookConv
35.3
116
0.72899
140
1,059
5.192857
0.3
0.082531
0.10729
0.173315
0.651995
0.651995
0.583219
0.583219
0.583219
0.583219
0
0.008999
0.160529
1,059
29
117
36.517241
0.808774
0.012276
0
0.333333
0
0
0.037356
0
0
0
0
0
0
1
0.222222
false
0
0.111111
0
0.666667
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
0be0fdfc9618146c14baa5d89757dd10208c2d77
191
py
Python
rest/rest_api_project/rest_api_app/database/__init__.py
elastest/elastest-persistence-service
a8678f7582bc0f3574b2f95db0dc92fd8747f723
[ "Apache-2.0" ]
null
null
null
rest/rest_api_project/rest_api_app/database/__init__.py
elastest/elastest-persistence-service
a8678f7582bc0f3574b2f95db0dc92fd8747f723
[ "Apache-2.0" ]
8
2017-08-31T11:06:53.000Z
2018-02-14T14:45:44.000Z
rest/rest_api_project/rest_api_app/database/__init__.py
elastest/elastest-persistence-service
a8678f7582bc0f3574b2f95db0dc92fd8747f723
[ "Apache-2.0" ]
6
2017-07-01T22:35:04.000Z
2020-10-27T08:35:09.000Z
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def reset_database(): from rest_api_app.database.models import Backup, Category # noqa db.drop_all() db.create_all()
19.1
69
0.73822
26
191
5.192308
0.692308
0
0
0
0
0
0
0
0
0
0
0
0.17801
191
9
70
21.222222
0.859873
0.020942
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
0bebb1c488f6b90baec2eda46dfe2614f54533c1
3,130
py
Python
app/utils/wtf_handler/register.py
WMU-Su-ChaShan-21Lab/MagicExWASPortal
35f5ba3f10bb90d99a64d376fff8c322a11b8598
[ "MIT" ]
null
null
null
app/utils/wtf_handler/register.py
WMU-Su-ChaShan-21Lab/MagicExWASPortal
35f5ba3f10bb90d99a64d376fff8c322a11b8598
[ "MIT" ]
null
null
null
app/utils/wtf_handler/register.py
WMU-Su-ChaShan-21Lab/MagicExWASPortal
35f5ba3f10bb90d99a64d376fff8c322a11b8598
[ "MIT" ]
null
null
null
# -*- encoding: utf-8 -*- """ @File Name : register.py @Create Time : 2021/7/15 10:04 @Description : @Version : @License : @Author : diklios @Contact Email : diklios5768@gmail.com @Github : https://github.com/diklios5768 @Blog : @Motto : All our science, measured against reality, is primitive and childlike - and yet it is the most precious thing we have. """ __auth__ = 'diklios' from wtforms import StringField, BooleanField, SubmitField, IntegerField from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError, Regexp from app.models.tcm.user import User from app.utils.wtf_handler.client import ClientForm, ExtraUsernameForm, VerifySecretForm, ExtraVerificationCodeForm from app.viewModels.common.verification import verify_verification_code # 用户名+密码 class RegisterOnlyUsernameForm(VerifySecretForm): account = StringField(validators=[DataRequired(), Length(min=4, max=20)]) def validate_account(self, value): if User.query.filter_by(username=value.data).first(): raise ValidationError('用户名已经被注册') # 邮箱+密码+验证码 class RegisterEmailForm(VerifySecretForm, ExtraVerificationCodeForm): account = StringField(validators=[DataRequired(), Email(message='invalidate email')]) def validate_account(self, value): if User.query.filter_by(email=value.data).first(): raise ValidationError('邮箱已经被注册') def validate_verification_code(self, value): verify_verification_code(account_type='email', account=self.account.data, verification_code=value.data, use='register') # 邮箱+密码+验证码+用户名 class RegisterEmailWithUsernameForm(VerifySecretForm): account = StringField(validators=[DataRequired(), Length(min=4, max=20)]) email = StringField(validators=[DataRequired(), Email(message='invalidate email')]) def validate_account(self, value): if User.query.filter_by(username=value.data).first(): raise ValidationError('用户名已经被注册') def validate_email(self, value): if User.query.filter_by(email=value.data).first(): raise ValidationError('邮箱已经被注册') # todo:手机区号要查询写入,需要再修改 # 手机号+验证码 class RegisterPhoneForm(ClientForm, ExtraVerificationCodeForm): # phone_code= StringField(validators=[DataRequired(), Length(min=1, max=4)]) account = StringField(validators=[DataRequired(), Length(12)]) def validate_account(self, value): if User.query.filter_by(phone=value.data).first(): raise ValidationError('手机号已经被注册') def validate_verification_code(self, value): verify_verification_code(account_type='phone', account=self.account.data, verification_code=value.data, use='register') # 手机号+验证码+密码 class RegisterPhoneWithSecretForm(RegisterPhoneForm, VerifySecretForm): pass # 手机号+验证码+用户名 class RegisterPhoneWithUsernameForm(RegisterPhoneForm, ExtraUsernameForm): pass # 手机号+验证码+密码+用户名 class RegisterPhoneWithSecretWithUsernameForm(RegisterPhoneWithSecretForm, ExtraUsernameForm): pass
35.977011
138
0.71246
329
3,130
6.68693
0.367781
0.050909
0.09
0.034091
0.473636
0.418182
0.418182
0.418182
0.418182
0.418182
0
0.011691
0.180192
3,130
86
139
36.395349
0.845674
0.195847
0
0.5
0
0
0.0412
0
0
0
0
0.011628
0
1
0.166667
false
0.071429
0.119048
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
1
0
0
3
0bec83aa79df35159dadcb97eb70b368843bb1f6
596
py
Python
ltr/helpers/solr_escape.py
tanjie123/hello-ltr
fe1ad1989e1bb17dfc8d1c09931480becf59766e
[ "Apache-2.0" ]
109
2019-04-18T01:24:29.000Z
2022-03-12T17:37:30.000Z
ltr/helpers/solr_escape.py
tanjie123/hello-ltr
fe1ad1989e1bb17dfc8d1c09931480becf59766e
[ "Apache-2.0" ]
63
2019-04-14T01:01:24.000Z
2022-03-03T20:48:41.000Z
ltr/helpers/solr_escape.py
tanjie123/hello-ltr
fe1ad1989e1bb17dfc8d1c09931480becf59766e
[ "Apache-2.0" ]
41
2019-04-22T15:22:41.000Z
2022-02-26T00:03:02.000Z
def esc_kw(kw): """ Take a keyword and escape all the Solr parts we want to escape!""" kw = kw.replace('\\', '\\\\') # be sure to do this first, as we inject \! kw = kw.replace('(', '\(') kw = kw.replace(')', '\)') kw = kw.replace('+', '\+') kw = kw.replace('-', '\-') kw = kw.replace(':', '\:') kw = kw.replace('/', '\/') kw = kw.replace(']', '\]') kw = kw.replace('[', '\[') kw = kw.replace('*', '\*') kw = kw.replace('?', '\?') kw = kw.replace('{', '\{') kw = kw.replace('}', '\}') kw = kw.replace('~', '\~') return kw
28.380952
77
0.422819
70
596
3.585714
0.342857
0.239044
0.613546
0.621514
0.569721
0.569721
0.569721
0.569721
0.569721
0.569721
0
0
0.266779
596
20
78
29.8
0.574371
0.177852
0
0
0
0
0.094737
0
0
0
0
0
0
1
0.0625
false
0
0
0
0.125
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0bed19a92912ccda603e3f470ca48154c417bb59
9,752
py
Python
blackmamba/lib/rope/base/pyscopes.py
oz90210/blackmamba
65c82c8e99028d6fbb57098ce82d0a394df215a0
[ "MIT" ]
463
2015-01-15T08:17:42.000Z
2022-03-28T15:10:20.000Z
blackmamba/lib/rope/base/pyscopes.py
oz90210/blackmamba
65c82c8e99028d6fbb57098ce82d0a394df215a0
[ "MIT" ]
52
2015-01-06T02:43:59.000Z
2022-03-14T11:15:21.000Z
blackmamba/lib/rope/base/pyscopes.py
oz90210/blackmamba
65c82c8e99028d6fbb57098ce82d0a394df215a0
[ "MIT" ]
249
2015-01-07T22:49:49.000Z
2022-03-18T02:32:06.000Z
import rope.base.builtins import rope.base.codeanalyze import rope.base.pynames from rope.base import ast, exceptions, utils class Scope(object): def __init__(self, pycore, pyobject, parent_scope): self.pycore = pycore self.pyobject = pyobject self.parent = parent_scope def get_names(self): """Return the names defined or imported in this scope""" return self.pyobject.get_attributes() def get_defined_names(self): """Return the names defined in this scope""" return self.pyobject._get_structural_attributes() def get_name(self, name): """Return name `PyName` defined in this scope""" if name not in self.get_names(): raise exceptions.NameNotFoundError('name %s not found' % name) return self.get_names()[name] def __getitem__(self, key): """The same as ``get_name(key)``""" return self.get_name(key) def __contains__(self, key): """The same as ``key in self.get_names()``""" return key in self.get_names() @utils.saveit def get_scopes(self): """Return the subscopes of this scope The returned scopes should be sorted by the order they appear. """ return self._create_scopes() def lookup(self, name): if name in self.get_names(): return self.get_names()[name] if self.parent is not None: return self.parent._propagated_lookup(name) return None def get_propagated_names(self): """Return the visible names of this scope Return the names defined in this scope that are visible from scopes containing this scope. This method returns the same dictionary returned by `get_names()` except for `ClassScope` which returns an empty dict. """ return self.get_names() def _propagated_lookup(self, name): if name in self.get_propagated_names(): return self.get_propagated_names()[name] if self.parent is not None: return self.parent._propagated_lookup(name) return None def _create_scopes(self): return [pydefined.get_scope() for pydefined in self.pyobject._get_defined_objects()] def _get_global_scope(self): current = self while current.parent is not None: current = current.parent return current def get_start(self): return self.pyobject.get_ast().lineno def get_body_start(self): body = self.pyobject.get_ast().body if body: return body[0].lineno return self.get_start() def get_end(self): pymodule = self._get_global_scope().pyobject return pymodule.logical_lines.logical_line_in(self.logical_end)[1] @utils.saveit def get_logical_end(self): global_scope = self._get_global_scope() return global_scope._scope_finder.find_scope_end(self) start = property(get_start) end = property(get_end) logical_end = property(get_logical_end) def get_kind(self): pass class GlobalScope(Scope): def __init__(self, pycore, module): super(GlobalScope, self).__init__(pycore, module, None) self.names = module._get_concluded_data() def get_start(self): return 1 def get_kind(self): return 'Module' def get_name(self, name): try: return self.pyobject[name] except exceptions.AttributeNotFoundError: if name in self.builtin_names: return self.builtin_names[name] raise exceptions.NameNotFoundError('name %s not found' % name) def get_names(self): if self.names.get() is None: result = dict(self.builtin_names) result.update(super(GlobalScope, self).get_names()) self.names.set(result) return self.names.get() def get_inner_scope_for_line(self, lineno, indents=None): return self._scope_finder.get_holding_scope(self, lineno, indents) def get_inner_scope_for_offset(self, offset): return self._scope_finder.get_holding_scope_for_offset(self, offset) @property @utils.saveit def _scope_finder(self): return _HoldingScopeFinder(self.pyobject) @property def builtin_names(self): return rope.base.builtins.builtins.get_attributes() class FunctionScope(Scope): def __init__(self, pycore, pyobject, visitor): super(FunctionScope, self).__init__(pycore, pyobject, pyobject.parent.get_scope()) self.names = None self.returned_asts = None self.is_generator = None self.defineds = None self.visitor = visitor def _get_names(self): if self.names is None: self._visit_function() return self.names def _visit_function(self): if self.names is None: new_visitor = self.visitor(self.pycore, self.pyobject) for n in ast.get_child_nodes(self.pyobject.get_ast()): ast.walk(n, new_visitor) self.names = new_visitor.names self.names.update(self.pyobject.get_parameters()) self.returned_asts = new_visitor.returned_asts self.is_generator = new_visitor.generator self.defineds = new_visitor.defineds def _get_returned_asts(self): if self.names is None: self._visit_function() return self.returned_asts def _is_generator(self): if self.is_generator is None: self._get_returned_asts() return self.is_generator def get_names(self): return self._get_names() def _create_scopes(self): if self.defineds is None: self._visit_function() return [pydefined.get_scope() for pydefined in self.defineds] def get_kind(self): return 'Function' def invalidate_data(self): for pyname in self.get_names().values(): if isinstance(pyname, (rope.base.pynames.AssignedName, rope.base.pynames.EvaluatedName)): pyname.invalidate() class ClassScope(Scope): def __init__(self, pycore, pyobject): super(ClassScope, self).__init__(pycore, pyobject, pyobject.parent.get_scope()) def get_kind(self): return 'Class' def get_propagated_names(self): return {} class _HoldingScopeFinder(object): def __init__(self, pymodule): self.pymodule = pymodule def get_indents(self, lineno): return rope.base.codeanalyze.count_line_indents( self.lines.get_line(lineno)) def _get_scope_indents(self, scope): return self.get_indents(scope.get_start()) def get_holding_scope(self, module_scope, lineno, line_indents=None): if line_indents is None: line_indents = self.get_indents(lineno) current_scope = module_scope new_scope = current_scope while new_scope is not None and \ (new_scope.get_kind() == 'Module' or self._get_scope_indents(new_scope) <= line_indents): current_scope = new_scope if current_scope.get_start() == lineno and \ current_scope.get_kind() != 'Module': return current_scope new_scope = None for scope in current_scope.get_scopes(): if scope.get_start() <= lineno: if lineno <= scope.get_end(): new_scope = scope break else: break return current_scope def _is_empty_line(self, lineno): line = self.lines.get_line(lineno) return line.strip() == '' or line.lstrip().startswith('#') def _get_body_indents(self, scope): return self.get_indents(scope.get_body_start()) def get_holding_scope_for_offset(self, scope, offset): return self.get_holding_scope( scope, self.lines.get_line_number(offset)) def find_scope_end(self, scope): if not scope.parent: return self.lines.length() end = scope.pyobject.get_ast().body[-1].lineno scope_start = self.pymodule.logical_lines.logical_line_in(scope.start) if scope_start[1] >= end: # handling one-liners body_indents = self._get_scope_indents(scope) + 4 else: body_indents = self._get_body_indents(scope) for l in self.logical_lines.generate_starts( min(end + 1, self.lines.length()), self.lines.length() + 1): if not self._is_empty_line(l): if self.get_indents(l) < body_indents: return end else: end = l return end @property def lines(self): return self.pymodule.lines @property def code(self): return self.pymodule.source_code @property def logical_lines(self): return self.pymodule.logical_lines class TemporaryScope(Scope): """Currently used for list comprehensions and generator expressions These scopes do not appear in the `get_scopes()` method of their parent scopes. """ def __init__(self, pycore, parent_scope, names): super(TemporaryScope, self).__init__( pycore, parent_scope.pyobject, parent_scope) self.names = names def get_names(self): return self.names def get_defined_names(self): return self.names def _create_scopes(self): return [] def get_kind(self): return 'Temporary'
30.95873
78
0.622949
1,186
9,752
4.865936
0.132378
0.03223
0.020794
0.014729
0.330792
0.22717
0.154912
0.115751
0.059262
0.044013
0
0.001153
0.288659
9,752
314
79
31.057325
0.830763
0.073728
0
0.257778
0
0
0.008407
0
0
0
0
0
0
1
0.24
false
0.004444
0.017778
0.102222
0.537778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
0bf9a60c81b36dd6e2610bd15f4bfb9f0cba5d5e
355
py
Python
tests/kyu_6_tests/test_multiples_of_3_and_5.py
the-zebulan/CodeWars
1eafd1247d60955a5dfb63e4882e8ce86019f43a
[ "MIT" ]
40
2016-03-09T12:26:20.000Z
2022-03-23T08:44:51.000Z
tests/kyu_6_tests/test_multiples_of_3_and_5.py
akalynych/CodeWars
1eafd1247d60955a5dfb63e4882e8ce86019f43a
[ "MIT" ]
null
null
null
tests/kyu_6_tests/test_multiples_of_3_and_5.py
akalynych/CodeWars
1eafd1247d60955a5dfb63e4882e8ce86019f43a
[ "MIT" ]
36
2016-11-07T19:59:58.000Z
2022-03-31T11:18:27.000Z
import unittest from katas.kyu_6.multiples_of_3_and_5 import solution class MultiplesOfThreeAndFiveTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(solution(10), 23) def test_equals_2(self): self.assertEqual(solution(100), 2318) def test_equals_3(self): self.assertEqual(solution(997), 232169)
23.666667
57
0.735211
46
355
5.456522
0.586957
0.083665
0.155378
0.322709
0
0
0
0
0
0
0
0.085034
0.171831
355
14
58
25.357143
0.768707
0
0
0
0
0
0
0
0
0
0
0
0.333333
1
0.333333
false
0
0.222222
0
0.666667
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
04010c1ffae2015355287dfcef8a16ff69fb4ac2
1,587
py
Python
Uncuffed/messages/EncryptedImageMessage.py
WckdAwe/Uncuffed
c86c2ef33c689d7895ff45e9ba6108a9f7831c2d
[ "MIT" ]
2
2021-09-16T09:17:34.000Z
2021-11-18T12:44:34.000Z
Uncuffed/messages/EncryptedImageMessage.py
WckdAwe/Uncuffed
c86c2ef33c689d7895ff45e9ba6108a9f7831c2d
[ "MIT" ]
null
null
null
Uncuffed/messages/EncryptedImageMessage.py
WckdAwe/Uncuffed
c86c2ef33c689d7895ff45e9ba6108a9f7831c2d
[ "MIT" ]
null
null
null
import base64 import binascii import collections from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.PublicKey.RSA import RsaKey from werkzeug.datastructures import FileStorage from .AMessage import EMessageType from .ImageMessage import ImageMessage class EncryptedImageMessage(ImageMessage): def __init__(self, mimetype: str, base64img: str): super().__init__(mimetype=mimetype, base64img=base64img) @property def message_type(self) -> int: return EMessageType.ENCRYPTED_IMAGE def soft_encrypt(self, address: str) -> str: from Uncuffed import rsa_long_encrypt enc = rsa_long_encrypt(binascii.unhexlify(address), self.message.encode('utf-8')) return binascii.hexlify(enc).decode('ascii') # cipher_rsa = PKCS1_OAEP.new( # RSA.import_key(binascii.unhexlify(address)) # ) # enc_session_key = cipher_rsa.encrypt(self.message.encode('utf-8')) # return binascii.hexlify(enc_session_key).decode('ascii') def encrypt(self, address: str): self.message = self.soft_encrypt(address=address) def soft_decrypt(self, key: RsaKey) -> str: from Uncuffed import rsa_long_decrypt dec = rsa_long_decrypt(key, binascii.unhexlify(self.message)).decode('utf-8') return dec # cipher_rsa = PKCS1_OAEP.new(key) # return cipher_rsa.decrypt(binascii.unhexlify(self.message)).decode('utf-8') def decrypt(self, key: RsaKey): self.message = self.soft_decrypt(key)
35.266667
90
0.689351
190
1,587
5.578947
0.273684
0.062264
0.028302
0.039623
0.249057
0.209434
0.156604
0.084906
0.084906
0
0
0.012
0.21235
1,587
44
91
36.068182
0.836
0.195967
0
0
0
0
0.012255
0
0
0
0
0
0
1
0.222222
false
0
0.407407
0.037037
0.777778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
1
0
1
0
0
3
0407a1300fa8f4428454cc994004dcd4acb5d4b4
252
py
Python
order/urls.py
abdukhashimov/django-rest-gsoft
f205e7c1bbb575920bdd43d3ec46a97f6fade90e
[ "MIT" ]
null
null
null
order/urls.py
abdukhashimov/django-rest-gsoft
f205e7c1bbb575920bdd43d3ec46a97f6fade90e
[ "MIT" ]
5
2021-03-18T23:24:36.000Z
2021-09-22T18:31:01.000Z
order/urls.py
abdukhashimov/django-rest-gsoft
f205e7c1bbb575920bdd43d3ec46a97f6fade90e
[ "MIT" ]
null
null
null
from django.urls import path from .views import OrderCreateView, BaseContactCreateView urlpatterns = [ path('order/', OrderCreateView.as_view(), name='order-create'), path('contact/', BaseContactCreateView.as_view(), name='contact-create') ]
28
76
0.746032
27
252
6.888889
0.555556
0.064516
0.107527
0
0
0
0
0
0
0
0
0
0.115079
252
8
77
31.5
0.834081
0
0
0
0
0
0.15873
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
040c04ebd461963b0dc8e7ea26adc6ebc27fe6fc
1,055
py
Python
lib/exabgp/bmp/peer.py
PowerDNS/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
8
2015-01-11T09:57:26.000Z
2019-07-05T05:57:02.000Z
lib/exabgp/bmp/peer.py
Acidburn0zzz/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
1
2018-11-15T22:10:09.000Z
2018-11-15T22:20:31.000Z
lib/exabgp/bmp/peer.py
Acidburn0zzz/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
6
2015-09-11T01:51:06.000Z
2020-03-10T19:16:18.000Z
# encoding: utf-8 """ peer.py Created by Thomas Mangin on 2013-02-26. Copyright (c) 2009-2012 Exa Networks. All rights reserved. """ from struct import unpack from exabgp.protocol.ip import IPv4 from exabgp.protocol.ip import IPv6 # XXX: FIXME: Move this within Peer with the same API as other classes such as Attribute or Message class PeerType (int): _str = { 0 : 'global', 1 : 'L3 VPN', } def __str__ (self): return self._str.get(self,'unknow %d' % self) class PeerFlag (int): _v4v6 = 0b10000000 def ipv4 (self): return not self & self._v4v6 def ipv6 (self): return bool(self & self._v4v6) class Peer (object): def __init__ (self,data): self.type = PeerType(ord(data[2])) self.flag = PeerFlag(ord(data[3])) self.distinguisher = unpack('!L',data[4:8])[0] self.asn = unpack('!L',data[28:32])[0] self.id = IPv4.unpack(data[32:36]) if self.flag.ipv4(): self.peer_address = IPv4.unpack(data[24:28]) if self.flag.ipv6(): self.peer_address = IPv6.unpack(data[12:28]) def validate (self): return self.type in (0,1)
22.934783
99
0.683412
172
1,055
4.104651
0.517442
0.056657
0.050992
0.056657
0.073654
0
0
0
0
0
0
0.077449
0.167773
1,055
45
100
23.444444
0.726651
0.210427
0
0
0
0
0.03034
0
0
0
0
0.022222
0
1
0.185185
false
0
0.111111
0.148148
0.62963
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
1
1
0
0
3
041afc56ff7044824a24398d132a2ca7a118a8d1
62
py
Python
docs/conf.py
opnfv/barometer
52e3a8bc19d86205e81442acfa9512006207c023
[ "Apache-2.0" ]
9
2017-07-18T15:32:44.000Z
2021-05-29T12:25:11.000Z
docs/conf.py
opnfv/barometer
52e3a8bc19d86205e81442acfa9512006207c023
[ "Apache-2.0" ]
2
2018-01-04T23:05:43.000Z
2018-10-16T17:22:35.000Z
docs/conf.py
opnfv/barometer
52e3a8bc19d86205e81442acfa9512006207c023
[ "Apache-2.0" ]
16
2017-07-04T11:42:26.000Z
2021-05-27T10:36:22.000Z
from docs_conf.conf import * extensions = ['reno.sphinxext']
15.5
31
0.741935
8
62
5.625
0.875
0
0
0
0
0
0
0
0
0
0
0
0.129032
62
3
32
20.666667
0.833333
0
0
0
0
0
0.225806
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
04260974fa1259b75735ed1e324eb6c87715c938
90
py
Python
drams/vagrant-settings.py
FAIRDataPipeline/data-registry
656ba8893b39ee2a73e51e79722e0363125ed8f4
[ "BSD-2-Clause" ]
null
null
null
drams/vagrant-settings.py
FAIRDataPipeline/data-registry
656ba8893b39ee2a73e51e79722e0363125ed8f4
[ "BSD-2-Clause" ]
116
2021-06-28T11:11:59.000Z
2022-03-24T09:29:30.000Z
drams/vagrant-settings.py
ScottishCovidResponse/data-registry
92753a7067b409c06bf38cf8c493cea4570fc34f
[ "BSD-2-Clause" ]
1
2022-03-16T10:36:27.000Z
2022-03-16T10:36:27.000Z
from .base_settings import * ALLOWED_HOSTS = ['192.168.20.10', '127.0.0.1', 'localhost']
22.5
59
0.677778
15
90
3.933333
0.933333
0
0
0
0
0
0
0
0
0
0
0.2
0.111111
90
3
60
30
0.5375
0
0
0
0
0
0.344444
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
0427e9fffd77b7eabc23b693b0d11073a1109a2e
206
py
Python
src/backend/command/model/configuration/_utils.py
kairu-ms/aaz-dev-tools
233a70253487ebbc8347bdd1851e07c2a745104f
[ "MIT" ]
null
null
null
src/backend/command/model/configuration/_utils.py
kairu-ms/aaz-dev-tools
233a70253487ebbc8347bdd1851e07c2a745104f
[ "MIT" ]
2
2021-12-21T03:49:53.000Z
2021-12-29T07:32:31.000Z
src/backend/command/model/configuration/_utils.py
kairu-ms/aaz-dev-tools
233a70253487ebbc8347bdd1851e07c2a745104f
[ "MIT" ]
1
2021-11-18T09:07:11.000Z
2021-11-18T09:07:11.000Z
class CMDDiffLevelEnum: BreakingChange = 1 # diff breaking change part Structure = 2 # Associate = 5 # include diff for links All = 10 # including description and help messages
22.888889
57
0.665049
23
206
5.956522
0.956522
0
0
0
0
0
0
0
0
0
0
0.034247
0.291262
206
8
58
25.75
0.90411
0.427184
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
3
042888c821315f9ac9268da7b68e21e264d574b7
452
py
Python
Narcissistic Number/is_narcissistic_number.py
rayvantsahni/Let-us-Math
571ee70452feae0b15f37d46de658b0c0251bd3d
[ "MIT" ]
2
2020-08-06T07:09:38.000Z
2020-09-12T02:32:23.000Z
Narcissistic Number/is_narcissistic_number.py
rayvantsahni/Math-is-Fun
571ee70452feae0b15f37d46de658b0c0251bd3d
[ "MIT" ]
null
null
null
Narcissistic Number/is_narcissistic_number.py
rayvantsahni/Math-is-Fun
571ee70452feae0b15f37d46de658b0c0251bd3d
[ "MIT" ]
1
2021-08-30T14:17:28.000Z
2021-08-30T14:17:28.000Z
def is_narcissistic_number(n): original_number = n number_of_digits = get_number_of_digits(n) sum = 0 while n != 0: sum += (n % 10) ** number_of_digits n //= 10 return original_number == sum def get_number_of_digits(n): return len(str(n)) if __name__ == "__main__": n = int(input("Enter number: ")) print("Is a Narcissistic Number" if is_narcissistic_number(n) else "Is NOT a Narcissistic Number")
22.6
102
0.64823
67
452
4.014925
0.38806
0.267658
0.208178
0.167286
0.133829
0
0
0
0
0
0
0.017442
0.238938
452
19
103
23.789474
0.764535
0
0
0
0
0
0.163717
0
0
0
0
0
0
1
0.153846
false
0
0
0.076923
0.307692
0.076923
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
045bf9ba8d6ff8f294a328699fba58ce94500ed4
438
py
Python
lang/py/cookbook/v2/source/cb2_20_5_exm_1.py
ch1huizong/learning
632267634a9fd84a5f5116de09ff1e2681a6cc85
[ "MIT" ]
null
null
null
lang/py/cookbook/v2/source/cb2_20_5_exm_1.py
ch1huizong/learning
632267634a9fd84a5f5116de09ff1e2681a6cc85
[ "MIT" ]
null
null
null
lang/py/cookbook/v2/source/cb2_20_5_exm_1.py
ch1huizong/learning
632267634a9fd84a5f5116de09ff1e2681a6cc85
[ "MIT" ]
null
null
null
class Rectangle(object): def __init__(self, x, y): self._x = x # don't trigger _setSide prematurely self.y = y # now trigger it, so area gets computed def _setSide(self, attrname, value): setattr(self, attrname, value) self.area = self._x * self._y x = CommonProperty('_x', fset=_setSide, fdel=None) y = CommonProperty('_y', fset=_setSide, fdel=None)
43.8
78
0.584475
55
438
4.418182
0.472727
0.061728
0.139918
0.156379
0
0
0
0
0
0
0
0
0.305936
438
9
79
48.666667
0.799342
0.164384
0
0
0
0
0.011019
0
0
0
0
0
0
1
0.222222
false
0
0
0
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
045ea9d96a207c246b79e7a3f67b9e1f58c41c9a
113
py
Python
Data Scientist Career Path/3. Python Fundamentals/5. Python List/1. Intro to List/5. list append.py
myarist/Codecademy
2ba0f104bc67ab6ef0f8fb869aa12aa02f5f1efb
[ "MIT" ]
23
2021-06-06T15:35:55.000Z
2022-03-21T06:53:42.000Z
Data Scientist Career Path/3. Python Fundamentals/5. Python List/1. Intro to List/5. list append.py
shivaniverma1/Data-Scientist
f82939a411484311171465591455880c8e354750
[ "MIT" ]
null
null
null
Data Scientist Career Path/3. Python Fundamentals/5. Python List/1. Intro to List/5. list append.py
shivaniverma1/Data-Scientist
f82939a411484311171465591455880c8e354750
[ "MIT" ]
9
2021-06-08T01:32:04.000Z
2022-03-18T15:38:09.000Z
orders = ["daisies", "periwinkle"] print(orders) orders.append("tulips") orders.append("roses") print(orders)
12.555556
34
0.707965
13
113
6.153846
0.538462
0.275
0
0
0
0
0
0
0
0
0
0
0.097345
113
9
35
12.555556
0.784314
0
0
0.4
0
0
0.245614
0
0
0
0
0
0
1
0
false
0
0
0
0
0.4
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
f0b2a999cc91b895ea645ef70fdcecb2516bc0f9
259
py
Python
FrEIA/__init__.py
paulhfu/FrEIA
e5694e596503a930395cde843f6523da09b6b6e7
[ "MIT" ]
1
2021-05-14T03:34:36.000Z
2021-05-14T03:34:36.000Z
FrEIA/__init__.py
paulhfu/FrEIA
e5694e596503a930395cde843f6523da09b6b6e7
[ "MIT" ]
null
null
null
FrEIA/__init__.py
paulhfu/FrEIA
e5694e596503a930395cde843f6523da09b6b6e7
[ "MIT" ]
null
null
null
'''Framework for Easily Invertible Architectures. Module to construct invertible networks with pytorch, based on a graph structure of operations.''' from . import framework from . import modules from . import dummy_modules __all__ = ["framework", "modules"]
28.777778
70
0.783784
32
259
6.1875
0.71875
0.151515
0
0
0
0
0
0
0
0
0
0
0.138996
259
8
71
32.375
0.887892
0.548263
0
0
0
0
0.144144
0
0
0
0
0
0
1
0
false
0
0.75
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
f0c4920ddf3d896a46bdc78d877ea09f43153496
115
py
Python
Src/Tests/test_Main.py
mickers13/RiskSniffer
562ef3da9c16f38e0ef34fa5b22f0abaca5e608d
[ "MIT" ]
null
null
null
Src/Tests/test_Main.py
mickers13/RiskSniffer
562ef3da9c16f38e0ef34fa5b22f0abaca5e608d
[ "MIT" ]
null
null
null
Src/Tests/test_Main.py
mickers13/RiskSniffer
562ef3da9c16f38e0ef34fa5b22f0abaca5e608d
[ "MIT" ]
null
null
null
from unittest import TestCase class TestMain(TestCase): def test_load_banned_urls(self): self.fail()
16.428571
36
0.721739
15
115
5.333333
0.866667
0
0
0
0
0
0
0
0
0
0
0
0.2
115
6
37
19.166667
0.869565
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
f0c97a366003419512b3b24c843d24bff2120063
8,827
py
Python
tests/tests.py
Bouke/django-airbrake
28fbbd68c5858054753182d6299b3b200df76377
[ "MIT" ]
3
2015-10-13T05:39:49.000Z
2018-06-19T17:30:41.000Z
tests/tests.py
Bouke/django-airbrake
28fbbd68c5858054753182d6299b3b200df76377
[ "MIT" ]
5
2015-02-12T05:42:19.000Z
2018-05-27T08:31:36.000Z
tests/tests.py
Bouke/django-airbrake
28fbbd68c5858054753182d6299b3b200df76377
[ "MIT" ]
7
2015-02-11T23:40:19.000Z
2019-06-24T20:19:44.000Z
import logging import xml.etree.ElementTree as etree try: from unittest.mock import patch except ImportError: from mock import patch import django from django.conf import settings from django.contrib.sessions.backends.db import SessionStore from django.test import TestCase from django.test.utils import override_settings import airbrake from .urls import ViewException from .utils import xml_compare, xsd_validate DJANGO_RESPONSE = """ <notice version="2.0"> <api-key>MY_API_KEY</api-key> <notifier> <name>django-airbrake</name> <version>%(version)s</version> <url>http://github.com/Bouke/django-airbrake</url> </notifier> <server-environment> <environment-name>test</environment-name> </server-environment> <request> <url>http://testserver/raises/view-exception/?foo=bar</url> <component>tests.urls.raises_view_exception</component> <action>POST</action> <params> <var key='foo2'>bar2</var> </params> <session> <var key='user'>foobunny</var> </session> <cgi-data> <var key='HTTP_COOKIE'>sessionid=%(session)s</var> <var key='DJANGO_SETTINGS_MODULE'>tests.settings</var> <var key='HTTP_USER_AGENT'>Python/3.3</var> <var key='SERVER_NAME'>testserver</var> <var key='REMOTE_ADDR'>127.0.0.1</var> </cgi-data> </request> <error> <class>ViewException</class> <message>Internal Server Error: /raises/view-exception/: Could not find my Django</message> <backtrace> <line file="*" method="*" number="*" /> <line file="*" method="*" number="*" /> <line file="*" method="*" number="*" /> <line file="*" method="*" number="*" /> <line file="*" method="raises_view_exception: raise ViewException('Could not find my Django')" number="*" /> </backtrace> </error> </notice> """ # noqa: E501 DJANGO20_RESPONSE = """ <notice version="2.0"> <api-key>MY_API_KEY</api-key> <notifier> <name>django-airbrake</name> <version>%(version)s</version> <url>http://github.com/Bouke/django-airbrake</url> </notifier> <server-environment> <environment-name>test</environment-name> </server-environment> <request> <url>http://testserver/raises/view-exception/?foo=bar</url> <component>tests.urls.raises_view_exception</component> <action>POST</action> <params> <var key='foo2'>bar2</var> </params> <session> <var key='user'>foobunny</var> </session> <cgi-data> <var key='HTTP_COOKIE'>sessionid=%(session)s</var> <var key='DJANGO_SETTINGS_MODULE'>tests.settings</var> <var key='HTTP_USER_AGENT'>Python/3.3</var> <var key='SERVER_NAME'>testserver</var> <var key='REMOTE_ADDR'>127.0.0.1</var> </cgi-data> </request> <error> <class>ViewException</class> <message>Internal Server Error: /raises/view-exception/: Could not find my Django</message> <backtrace> <line file="*" method="*" number="*" /> <line file="*" method="*" number="*" /> <line file="*" method="*" number="*" /> <line file="*" method="raises_view_exception: raise ViewException('Could not find my Django')" number="*" /> </backtrace> </error> </notice> """ # noqa: E501 @patch('airbrake.handlers.urlopen', autospec=True) class XMLDataTest(TestCase): def setUp(self): self.logger = logging.getLogger('test') def test_exception(self, urlopen): urlopen.return_value.getcode.return_value = 200 try: raise Exception('Could not find my shoes') except Exception as exc: self.logger.exception(exc) self.assertEqual(urlopen.call_count, 1) xml = urlopen.call_args[0][0].data xsd_validate(xml) self.assertTrue(xml_compare(etree.fromstring(""" <notice version="2.0"> <api-key>MY_API_KEY</api-key> <notifier> <name>django-airbrake</name> <version>%(version)s</version> <url>http://github.com/Bouke/django-airbrake</url> </notifier> <server-environment> <environment-name>test</environment-name> </server-environment> <error> <class>Exception</class> <message>Could not find my shoes: Could not find my shoes</message> <backtrace> <line file="*" method="test_exception: raise Exception('Could not find my shoes')" number="*" /> </backtrace> </error> </notice> """ % {'version': airbrake.__version__}), # noqa: E501 etree.fromstring(xml), self.fail)) def test_django_request(self, urlopen): urlopen.return_value.getcode.return_value = 200 session = SessionStore() session['user'] = 'foobunny' session.save() self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key try: self.client.post('/raises/view-exception/?foo=bar', {'foo2': 'bar2'}, HTTP_USER_AGENT='Python/3.3') except ViewException: pass self.assertEqual(urlopen.call_count, 1) xml = urlopen.call_args[0][0].data xsd_validate(xml) # @todo cgi-data has undefined ordering, need to adjust xml validation if django.VERSION > (1, 11): self.assertTrue( xml_compare( etree.fromstring( DJANGO20_RESPONSE % { "version": airbrake.__version__, "session": session.session_key, } ), etree.fromstring(xml), self.fail, ) ) else: self.assertTrue( xml_compare( etree.fromstring( DJANGO_RESPONSE % { "version": airbrake.__version__, "session": session.session_key, } ), etree.fromstring(xml), self.fail, ) ) def test_raises_404(self, urlopen): urlopen.return_value.getcode.return_value = 200 response = self.client.get('/raises/404/') self.assertEqual(response.status_code, 404) # Check 404 is actually thrown self.assertEqual(urlopen.call_count, 1) def test_raises_import_error(self, urlopen): urlopen.return_value.getcode.return_value = 200 try: self.client.get('/raises/import-error/') except ImportError: pass self.assertEqual(urlopen.call_count, 1) xsd_validate(urlopen.call_args[0][0].data) @patch('airbrake.handlers.urlopen', autospec=True) @override_settings(INSTALLED_APPS=['tests'], MIDDLEWARE=()) class NoSessionTest(TestCase): def test_raises_viewexception(self, urlopen): urlopen.return_value.getcode.return_value = 200 try: self.client.get('/raises/view-exception/') except ViewException: pass self.assertEqual(urlopen.call_count, 1) xsd_validate(urlopen.call_args[0][0].data)
35.882114
107
0.488614
797
8,827
5.293601
0.181932
0.01991
0.045034
0.026547
0.742593
0.72055
0.661294
0.63617
0.63617
0.602512
0
0.016129
0.395944
8,827
245
108
36.028571
0.775131
0.014728
0
0.756881
0
0.009174
0.598435
0.163963
0
0
0
0.004082
0.041284
1
0.027523
false
0.013761
0.073395
0
0.110092
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
f0d2d21c4d32cf8fc1d1951b1fc809276b0c04b3
765
py
Python
laboratory/utils.py
urchinpro/L2-forms
37f33386984efbb2d1e92c73d915256247801109
[ "MIT" ]
null
null
null
laboratory/utils.py
urchinpro/L2-forms
37f33386984efbb2d1e92c73d915256247801109
[ "MIT" ]
null
null
null
laboratory/utils.py
urchinpro/L2-forms
37f33386984efbb2d1e92c73d915256247801109
[ "MIT" ]
null
null
null
from datetime import datetime from django.utils import timezone def localtime(d: datetime): return timezone.localtime(d) def strfdatetime(d, format: str): if not d: return "" try: return timezone.localtime(d).strftime(format) except: d = datetime(year=d.year, month=d.month, day=d.day) return d.strftime(format) def strdate(d, short_year=False): return strfdatetime(d, '%d.%m.%' + {True: "y", False: "Y"}[short_year]) def strtime(d): return strfdatetime(d, '%X') def strdatetime(d, short_year=False): return strfdatetime(d, '%d.%m.%' + {True: "y", False: "Y"}[short_year] + ' %X') def tsdatetime(d): return int(timezone.localtime(d).timestamp())
21.25
83
0.605229
100
765
4.59
0.33
0.087146
0.117647
0.104575
0.244009
0.244009
0.244009
0.244009
0.244009
0.244009
0
0
0.243137
765
35
84
21.857143
0.792746
0
0
0
0
0
0.030065
0
0
0
0
0
0
1
0.272727
false
0
0.090909
0.227273
0.727273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
f0eb70d69078901ef0d50db1cfca1a41426e7435
97
py
Python
pys/testing.py
nahian-147/my_codes
9729c56b227d75354ea49982720de94ed1c21909
[ "MIT" ]
null
null
null
pys/testing.py
nahian-147/my_codes
9729c56b227d75354ea49982720de94ed1c21909
[ "MIT" ]
null
null
null
pys/testing.py
nahian-147/my_codes
9729c56b227d75354ea49982720de94ed1c21909
[ "MIT" ]
null
null
null
import subprocess p = int(subprocess.check_output(["./testing","5"]).decode()) print(p*p)
16.166667
61
0.649485
13
97
4.769231
0.769231
0
0
0
0
0
0
0
0
0
0
0.011905
0.134021
97
5
62
19.4
0.72619
0
0
0
0
0
0.108696
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0.333333
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
f0ed5a8b1c879973dba72c63cd3d160334a02226
59
py
Python
src/app/training/__init__.py
serious-notreally/cappa
993a8df35ca6c3b22f3ca811937fd29c07fc71aa
[ "MIT" ]
9
2020-04-05T07:35:55.000Z
2021-08-03T05:50:05.000Z
src/app/training/__init__.py
serious-notreally/cappa
993a8df35ca6c3b22f3ca811937fd29c07fc71aa
[ "MIT" ]
89
2020-01-26T11:50:06.000Z
2022-03-31T07:14:18.000Z
src/app/training/__init__.py
serious-notreally/cappa
993a8df35ca6c3b22f3ca811937fd29c07fc71aa
[ "MIT" ]
13
2020-03-10T14:45:07.000Z
2021-07-31T02:43:40.000Z
default_app_config = "app.training.apps.TrainingAppConfig"
29.5
58
0.847458
7
59
6.857143
0.857143
0
0
0
0
0
0
0
0
0
0
0
0.050847
59
1
59
59
0.857143
0
0
0
0
0
0.59322
0.59322
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
f0f179d2da7b614878cdd822e072f3b5d82b295b
210
py
Python
legacy/ABC_113/B1.py
mo-mo-666/AtCoder
99556f5ed98510850aaa8ab2b845da6a9359f5a5
[ "MIT" ]
null
null
null
legacy/ABC_113/B1.py
mo-mo-666/AtCoder
99556f5ed98510850aaa8ab2b845da6a9359f5a5
[ "MIT" ]
null
null
null
legacy/ABC_113/B1.py
mo-mo-666/AtCoder
99556f5ed98510850aaa8ab2b845da6a9359f5a5
[ "MIT" ]
null
null
null
import numpy as np n = int(input()) t, a = map(int, input().split()) h = list(map(int, input().split())) h = np.array(h) dift = abs((t - h * 0.006) - a) ans = np.argmin(dift) + 1 print(ans)
14
36
0.52381
37
210
2.972973
0.594595
0.218182
0.2
0.290909
0.309091
0
0
0
0
0
0
0.032051
0.257143
210
14
37
15
0.673077
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.125
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0b074cfd360229339b102d842a59b9ebb1b66716
97
py
Python
subjects/InputOutput.py
NightySide/simple
c6e8e0567966f9edd09e0821ea1292ebef7fca59
[ "Unlicense" ]
null
null
null
subjects/InputOutput.py
NightySide/simple
c6e8e0567966f9edd09e0821ea1292ebef7fca59
[ "Unlicense" ]
null
null
null
subjects/InputOutput.py
NightySide/simple
c6e8e0567966f9edd09e0821ea1292ebef7fca59
[ "Unlicense" ]
null
null
null
def disp(*txt, p): print(*txt) ask = lambda p : p.b(input()) functions = {">>":disp,"?":ask}
19.4
31
0.536082
15
97
3.466667
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.175258
97
4
32
24.25
0.65
0
0
0
0
0
0.030928
0
0
0
0
0
0
1
0.25
false
0
0
0
0.25
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0b12739a1ea62c31667e466d9e1170e55b1d0eda
277
py
Python
src/bearzzzbot/routes.py
bear3z/BeARzzzBot
04055d6c85c004c75a8d4a1c904ffadb3d7f7ea3
[ "MIT" ]
3
2022-01-15T00:41:33.000Z
2022-01-18T14:27:32.000Z
src/bearzzzbot/routes.py
bear3z/BeARzzzBot
04055d6c85c004c75a8d4a1c904ffadb3d7f7ea3
[ "MIT" ]
2
2022-01-15T13:41:54.000Z
2022-01-17T08:57:34.000Z
src/bearzzzbot/routes.py
bear3z/BeARzzzBot
04055d6c85c004c75a8d4a1c904ffadb3d7f7ea3
[ "MIT" ]
null
null
null
from fastapi.responses import ORJSONResponse from fastapi.routing import APIRouter from bearzzzbot.drawings.resources import router as drawing_router api_router = APIRouter(default_response_class=ORJSONResponse) api_router.include_router(drawing_router, prefix="/drawing")
27.7
66
0.859206
34
277
6.794118
0.558824
0.095238
0
0
0
0
0
0
0
0
0
0
0.083032
277
9
67
30.777778
0.909449
0
0
0
0
0
0.028881
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
0b12de9f308481c86c2a39cb2b2c781829266bc5
883
py
Python
service-workers/service-worker/resources/bytecheck-worker.py
ayg/web-platform-tests
99893ad85e2fbe917e0f5d1b3dbdadb7233601ee
[ "BSD-3-Clause" ]
4
2020-09-09T15:28:01.000Z
2021-12-01T00:59:56.000Z
service-workers/service-worker/resources/bytecheck-worker.py
063095/web-platform-tests
255d54144a82ce76d8e50a4aa8de284151119f8b
[ "BSD-3-Clause" ]
null
null
null
service-workers/service-worker/resources/bytecheck-worker.py
063095/web-platform-tests
255d54144a82ce76d8e50a4aa8de284151119f8b
[ "BSD-3-Clause" ]
null
null
null
import time def main(request, response): headers = [('Content-Type', 'application/javascript'), ('Cache-Control', 'max-age=0')] main_content_type = '' if 'main' in request.GET: main_content_type = request.GET['main'] main_content = 'default' if main_content_type == 'time': main_content = time.time() imported_request_path = '' if 'path' in request.GET: imported_request_path = request.GET['path'] imported_request_type = '' if 'imported' in request.GET: imported_request_type = request.GET['imported'] imported_request = '' if imported_request_type == 'time': imported_request = '?imported=time'; body = ''' // %s importScripts('%sbytecheck-worker-imported-script.py%s'); ''' % (main_content, imported_request_path, imported_request) return headers, body
26.757576
65
0.636467
100
883
5.38
0.3
0.250929
0.083643
0.074349
0.100372
0
0
0
0
0
0
0.001468
0.228766
883
32
66
27.59375
0.788546
0
0
0
0
0
0.219706
0.089468
0
0
0
0
0
1
0.041667
false
0
0.458333
0
0.541667
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
0b18e0fb8cc72943e657d33841c0dcf003ec4e00
307
py
Python
ProjectEuler.Problem.020.py
jihunroh/ProjectEuler-Python
2fceaf5c3dd61038004b6128c5d9ee7a76142bca
[ "MIT" ]
null
null
null
ProjectEuler.Problem.020.py
jihunroh/ProjectEuler-Python
2fceaf5c3dd61038004b6128c5d9ee7a76142bca
[ "MIT" ]
null
null
null
ProjectEuler.Problem.020.py
jihunroh/ProjectEuler-Python
2fceaf5c3dd61038004b6128c5d9ee7a76142bca
[ "MIT" ]
null
null
null
from ProjectEulerCommons.Base import * Answer( sum([int(digit) for digit in str(factorial(100))]) ) """ ------------------------------------------------ ProjectEuler.Problem.020.py The Answer is: 648 Time Elasped: 0.0049893856048583984sec ------------------------------------------------ """
21.928571
54
0.478827
26
307
5.653846
0.923077
0
0
0
0
0
0
0
0
0
0
0.107807
0.123779
307
13
55
23.615385
0.438662
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.25
0
0.25
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
9be031dbf3561ddbf3d46489b685ac755c9a8296
355
py
Python
kubernetes_typed/client/models/v1_custom_resource_validation.py
nikhiljha/kubernetes-typed
4f4b969aa400c88306f92560e56bda6d19b2a895
[ "Apache-2.0" ]
22
2020-12-10T13:06:02.000Z
2022-02-13T21:58:15.000Z
kubernetes_typed/client/models/v1_custom_resource_validation.py
nikhiljha/kubernetes-typed
4f4b969aa400c88306f92560e56bda6d19b2a895
[ "Apache-2.0" ]
4
2021-03-08T07:06:12.000Z
2022-03-29T23:41:45.000Z
kubernetes_typed/client/models/v1_custom_resource_validation.py
nikhiljha/kubernetes-typed
4f4b969aa400c88306f92560e56bda6d19b2a895
[ "Apache-2.0" ]
2
2021-09-05T19:18:28.000Z
2022-03-14T02:56:17.000Z
# Code generated by `typeddictgen`. DO NOT EDIT. """V1CustomResourceValidationDict generated type.""" from typing import TypedDict from kubernetes_typed.client import V1JSONSchemaPropsDict V1CustomResourceValidationDict = TypedDict( "V1CustomResourceValidationDict", { "openAPIV3Schema": V1JSONSchemaPropsDict, }, total=False, )
25.357143
57
0.766197
27
355
10.037037
0.740741
0
0
0
0
0
0
0
0
0
0
0.02
0.15493
355
13
58
27.307692
0.883333
0.264789
0
0
1
0
0.176471
0.117647
0
0
0
0
0
1
0
false
0
0.222222
0
0.222222
0
1
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
9bec59fceabd51a981ce634c69750cf822c90ea3
139
py
Python
mrp/examples/06_remote/bob.py
colesbury/fairo
9e50a3aa7369c68c80e84d80abd5fcdee8a9277a
[ "MIT" ]
73
2021-09-14T19:24:45.000Z
2022-03-27T06:43:26.000Z
mrp/examples/06_remote/bob.py
colesbury/fairo
9e50a3aa7369c68c80e84d80abd5fcdee8a9277a
[ "MIT" ]
268
2021-09-14T22:40:23.000Z
2022-03-31T23:01:54.000Z
mrp/examples/06_remote/bob.py
colesbury/fairo
9e50a3aa7369c68c80e84d80abd5fcdee8a9277a
[ "MIT" ]
20
2021-09-14T19:24:47.000Z
2022-03-30T19:03:44.000Z
import a0 import signal s = a0.RemoteSubscriber( "localhost", "some/topic", lambda pkt: print(f"Got {pkt.payload}") ) signal.pause()
15.444444
70
0.690647
19
139
5.052632
0.789474
0
0
0
0
0
0
0
0
0
0
0.016949
0.151079
139
8
71
17.375
0.79661
0
0
0
0
0
0.258993
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0.166667
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
9bfaad88945882036d8ec76a5d54772cb9d933b9
418
py
Python
pymysquery/connection_base.py
mkeneqa/pysquery
2007bc7a6d41353360bdc40fccafc96fc94f5678
[ "MIT" ]
null
null
null
pymysquery/connection_base.py
mkeneqa/pysquery
2007bc7a6d41353360bdc40fccafc96fc94f5678
[ "MIT" ]
5
2020-07-16T18:48:50.000Z
2020-12-08T04:17:18.000Z
pymysquery/connection_base.py
mkeneqa/pysquery
2007bc7a6d41353360bdc40fccafc96fc94f5678
[ "MIT" ]
1
2020-12-01T20:22:52.000Z
2020-12-01T20:22:52.000Z
import abc import contextlib class ConnectionBase(metaclass=abc.ABCMeta): @abc.abstractmethod def connect(self): raise NotImplementedError("You should implement this!") @abc.abstractmethod def disconnect(self): raise NotImplementedError("You should implement this!") @contextlib.contextmanager def connection_handler(self): # implement context manager pass
22
63
0.708134
41
418
7.195122
0.585366
0.115254
0.135593
0.210169
0.338983
0.338983
0.338983
0
0
0
0
0
0.217703
418
18
64
23.222222
0.902141
0.059809
0
0.333333
0
0
0.132992
0
0
0
0
0
0
1
0.25
false
0.083333
0.166667
0
0.5
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
3