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
11e4ddcea8efcc0d36f4e566590fab3d51e1736b
556
py
Python
lib/exputils/plotutils/cm.py
yfukai/exputils
aab7bb69d12887f069e6768144dc767ea82e6306
[ "MIT" ]
null
null
null
lib/exputils/plotutils/cm.py
yfukai/exputils
aab7bb69d12887f069e6768144dc767ea82e6306
[ "MIT" ]
null
null
null
lib/exputils/plotutils/cm.py
yfukai/exputils
aab7bb69d12887f069e6768144dc767ea82e6306
[ "MIT" ]
null
null
null
import seaborn as sns metro_color=sns.color_palette(["#9caeb7","#e60012","#622886","#f39700","#00a7db","#bb641d","#009944","#a9cc51","#e85298","#0079c2","#d7c447","#b6007a"]) warm_color=sns.color_palette(["#c83b36","#df6a37","#cca044","#b14dbe","#ae366a","#74246b"]) cold_color=sns.color_palette(["#38279e","#3a66ba","#33a3a5","#71c458","#37a032","#2a865f"]) def get_darker(cmap,r=0.5): return sns.color_palette([[c*r for c in cc] for cc in cmap]) def change_level(cmap,r=0.5): return sns.color_palette([[min(c*r,1.) for c in cc] for cc in cmap])
55.6
152
0.670863
87
556
4.172414
0.563218
0.110193
0.206612
0.165289
0.258953
0.258953
0.258953
0.258953
0
0
0
0.197674
0.071942
556
9
153
61.777778
0.505814
0
0
0
0
0
0.302158
0
0
0
0
0
0
1
0.25
false
0
0.125
0.25
0.625
0
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
1
0
0
0
1
1
0
0
6
ee998f66bec14fdc0585e2020485dfd0b79640b5
37
py
Python
Bronze/Bronze_V/14928.py
masterTyper/baekjoon_solved_ac
b9ce14d9bdaa5b5b06735ad075fb827de9f44b9c
[ "MIT" ]
null
null
null
Bronze/Bronze_V/14928.py
masterTyper/baekjoon_solved_ac
b9ce14d9bdaa5b5b06735ad075fb827de9f44b9c
[ "MIT" ]
null
null
null
Bronze/Bronze_V/14928.py
masterTyper/baekjoon_solved_ac
b9ce14d9bdaa5b5b06735ad075fb827de9f44b9c
[ "MIT" ]
null
null
null
N = int(input()) print(N % 20000303)
12.333333
19
0.621622
6
37
3.833333
0.833333
0
0
0
0
0
0
0
0
0
0
0.258065
0.162162
37
3
19
12.333333
0.483871
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
1
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
6
eef59b6d9871bddf756dcdb0a4f1aed0711c9f83
41
py
Python
photoascii/__init__.py
rosowskimik/photoascii
d03202c773ff4878516c7a9602ae7e274483df8e
[ "MIT" ]
null
null
null
photoascii/__init__.py
rosowskimik/photoascii
d03202c773ff4878516c7a9602ae7e274483df8e
[ "MIT" ]
null
null
null
photoascii/__init__.py
rosowskimik/photoascii
d03202c773ff4878516c7a9602ae7e274483df8e
[ "MIT" ]
null
null
null
from photoascii.app import convert_image
20.5
40
0.878049
6
41
5.833333
1
0
0
0
0
0
0
0
0
0
0
0
0.097561
41
1
41
41
0.945946
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
e118d6cd319e66212dafb1273e972020b467c195
69
py
Python
coordle/__init__.py
JonasTriki/inf368-exercise-3-coordle
d31951244949ab9042d8af168c6a144b7cec6e7e
[ "MIT" ]
1
2020-04-21T13:54:56.000Z
2020-04-21T13:54:56.000Z
coordle/__init__.py
JonasTriki/inf368-exercise-3-coordle
d31951244949ab9042d8af168c6a144b7cec6e7e
[ "MIT" ]
null
null
null
coordle/__init__.py
JonasTriki/inf368-exercise-3-coordle
d31951244949ab9042d8af168c6a144b7cec6e7e
[ "MIT" ]
1
2021-08-09T03:35:39.000Z
2021-08-09T03:35:39.000Z
from . import backend from . import preprocessing from . import utils
23
27
0.797101
9
69
6.111111
0.555556
0.545455
0
0
0
0
0
0
0
0
0
0
0.15942
69
3
28
23
0.948276
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
01340b6f3ef9f9f8945a40c92547405e66b722db
181
py
Python
tests/handlers/conftest.py
alexander-manley/MLServer
42eac4715f208f028a8920c984ab296830d90f08
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
191
2020-06-16T18:07:27.000Z
2022-03-29T05:56:23.000Z
tests/handlers/conftest.py
alexander-manley/MLServer
42eac4715f208f028a8920c984ab296830d90f08
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
347
2020-08-21T02:22:04.000Z
2022-03-31T12:27:26.000Z
tests/handlers/conftest.py
alexander-manley/MLServer
42eac4715f208f028a8920c984ab296830d90f08
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
56
2020-06-22T14:29:25.000Z
2022-03-25T21:58:48.000Z
import pytest from mlserver.handlers.custom import CustomHandler @pytest.fixture def custom_handler() -> CustomHandler: return CustomHandler(rest_path="/my-custom-endpoint")
20.111111
57
0.79558
21
181
6.761905
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.110497
181
8
58
22.625
0.881988
0
0
0
0
0
0.104972
0
0
0
0
0
0
1
0.2
true
0
0.4
0.2
0.8
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
1
1
1
0
0
6
0188c92beb2d85ae0ba114ea5a5188d7e2994578
4,110
py
Python
led.py
djmcg/OrangePI_WIN-Blink-5-LEDs
7f5bb8a1e3b7bcb134ebf79d49b8419d50b50c38
[ "MIT" ]
null
null
null
led.py
djmcg/OrangePI_WIN-Blink-5-LEDs
7f5bb8a1e3b7bcb134ebf79d49b8419d50b50c38
[ "MIT" ]
null
null
null
led.py
djmcg/OrangePI_WIN-Blink-5-LEDs
7f5bb8a1e3b7bcb134ebf79d49b8419d50b50c38
[ "MIT" ]
null
null
null
# OrangePI_WIn Blink 5 LEDs S Stering 5 GPIO for Leds in Python import os import time os.system("echo 37 > /sys/class/gpio/export") os.system("echo 37 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio37/direction") os.system("echo 38 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio38/direction") os.system("echo 39 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio39/direction") os.system("echo 101 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio101/direction") os.system("echo 36 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio36/direction") #variables sl ="sleep 0.5" y = 0.2 z = 0.1 L1_On = "echo 1 > /sys/class/gpio/gpio37/value" L1_Off = "echo 0 > /sys/class/gpio/gpio37/value" L2_On = "echo 1 > /sys/class/gpio/gpio38/value" L2_Off = "echo 0 > /sys/class/gpio/gpio38/value" L3_On = "echo 1 > /sys/class/gpio/gpio39/value" L3_Off = "echo 0 > /sys/class/gpio/gpio39/value" L4_On = "echo 1 > /sys/class/gpio/gpio101/value" L4_Off = "echo 0 > /sys/class/gpio/gpio101/value" L5_On = "echo 1 > /sys/class/gpio/gpio36/value" L5_Off = "echo 0 > /sys/class/gpio/gpio36/value" while True:##blink 5 led with speed (y) timeout = time.time() + 5 # 5 seconds while True: print ("1 prog") os.system(L1_On) os.system(L2_On) os.system(L3_On) os.system(L4_On) os.system(L5_On) time.sleep (y) os.system(L1_Off) os.system(L2_Off) os.system(L3_Off) os.system(L4_Off) os.system(L5_Off) time.sleep (y) if time.time() > timeout: break continue #blink 5 led with speed (z) timeout = time.time() + 5 # 5 seconds while True: print ("2 prog") os.system(L1_On) os.system(L2_On) os.system(L3_On) os.system(L4_On) os.system(L5_On) time.sleep (z) os.system(L1_Off) os.system(L2_Off) os.system(L3_Off) os.system(L4_Off) os.system(L5_Off) time.sleep (z) if time.time() > timeout: break continue #right left blink timeout = time.time() + 5 # 5 seconds while True : print ("3 prog") os.system(L1_On) time.sleep (z) os.system(L1_Off) #os.system(sl) os.system(L2_On) time.sleep (z) os.system(L2_Off) #os.system(sl) os.system(L3_On) time.sleep (z) os.system(L3_Off) #os.system(sl) os.system(L4_On) time.sleep (z) os.system(L4_Off) #os.system(sl) os.system(L5_On) time.sleep (z) os.system(L5_Off) #os.system(sl) os.system(L4_On) time.sleep (z) os.system(L4_Off) #os.system(sl) os.system(L3_On) time.sleep (z) os.system(L3_Off) #os.system(sl) os.system(L2_On) time.sleep (z) os.system(L2_Off) #os.system(sl) if time.time() > timeout: break continue #middle outside timeout = time.time() + 5 # 5 seconds while True: print ("4 prog") os.system(L3_On) time.sleep (y) os.system(L2_On) os.system(L4_On) time.sleep (y) os.system(L5_On) os.system(L1_On) time.sleep (y) os.system(L1_Off) os.system(L2_Off) os.system(L3_Off) os.system(L4_Off) os.system(L5_Off) time.sleep (y) if time.time() > timeout: break continue #left follow timeout = time.time() + 5 # 5 seconds while True: print ("5 prog") os.system(L1_On) time.sleep (z) os.system(L1_Off) #time.sleep (y) os.system(L2_On) time.sleep (z) os.system(L2_Off) #time.sleep (y) os.system(L3_On) time.sleep (z) os.system(L3_Off) #time.sleep (y) os.system(L4_On) time.sleep (z) os.system(L4_Off) #time.sleep (y) os.system(L5_On) time.sleep (z) os.system(L5_Off) #time.sleep(y) if time.time() > timeout: break continue #right follow timeout = time.time() + 5 # 5 seconds while True: print ("6 prog") os.system(L5_On) time.sleep (z) os.system(L5_Off) #time.sleep (y) os.system(L4_On) time.sleep (z) os.system(L4_Off) #time.sleep (y) os.system(L3_On) time.sleep (z) os.system(L3_Off) #time.sleep (y) os.system(L2_On) time.sleep (z) os.system(L2_Off) #time.sleep (y) os.system(L1_On) time.sleep (z) os.system(L1_Off) #time.sleep(y) if time.time() > timeout: break continue
20.969388
63
0.656204
732
4,110
3.579235
0.09153
0.259542
0.096565
0.087023
0.887023
0.830534
0.731679
0.699618
0.699618
0.641603
0
0.047506
0.180535
4,110
195
64
21.076923
0.730404
0.118005
0
0.806452
0
0
0.230084
0.160167
0
0
0
0
0
1
0
false
0
0.012903
0
0.012903
0.03871
0
0
0
null
1
0
0
1
1
1
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
6
6d7373c36be299773c85d85913fdf9900a96db14
48
py
Python
mathevaluator/__init__.py
saimoncse19/bangla-math
74ee68300098641d180f9507806abec3458504e9
[ "MIT" ]
null
null
null
mathevaluator/__init__.py
saimoncse19/bangla-math
74ee68300098641d180f9507806abec3458504e9
[ "MIT" ]
null
null
null
mathevaluator/__init__.py
saimoncse19/bangla-math
74ee68300098641d180f9507806abec3458504e9
[ "MIT" ]
null
null
null
from mathevaluator.benmatheval import Evaluator
24
47
0.895833
5
48
8.6
1
0
0
0
0
0
0
0
0
0
0
0
0.083333
48
1
48
48
0.977273
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
096aaa56f32422fe6fe6af065e38a1d33df7cd7b
32
py
Python
shaner/value/__init__.py
takato86/shaner
e200bfaf27c69aab4a76ab3d589a2bbda4538ca4
[ "MIT" ]
null
null
null
shaner/value/__init__.py
takato86/shaner
e200bfaf27c69aab4a76ab3d589a2bbda4538ca4
[ "MIT" ]
null
null
null
shaner/value/__init__.py
takato86/shaner
e200bfaf27c69aab4a76ab3d589a2bbda4538ca4
[ "MIT" ]
null
null
null
from shaner.value.core import *
16
31
0.78125
5
32
5
1
0
0
0
0
0
0
0
0
0
0
0
0.125
32
1
32
32
0.892857
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
0974041d91c59fc2ae4479a244e1d16c82eb2dae
112
py
Python
chemprop/models/__init__.py
georgelamb19/chempropBayes
88d660398a772705804568b671b3614c636505aa
[ "MIT" ]
16
2020-09-17T16:23:43.000Z
2022-02-23T07:54:34.000Z
chemprop/models/__init__.py
georgelamb19/chempropBayes
88d660398a772705804568b671b3614c636505aa
[ "MIT" ]
null
null
null
chemprop/models/__init__.py
georgelamb19/chempropBayes
88d660398a772705804568b671b3614c636505aa
[ "MIT" ]
2
2021-05-14T14:22:37.000Z
2021-07-06T01:06:13.000Z
from .model import MoleculeModel from .model_bbp import MoleculeModelBBP from .model_dun import MoleculeModelDUN
37.333333
39
0.875
14
112
6.857143
0.571429
0.28125
0
0
0
0
0
0
0
0
0
0
0.098214
112
3
40
37.333333
0.950495
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
099d8451b8f4b99bb9eb12bbb05d3db63753fc93
817
py
Python
interface/get_ids.py
Bhaskers-Blu-Org2/multilabel-clustering-audio
4f2b707095c7e5050c3fffde9638d8d54600cae9
[ "MIT" ]
4
2019-09-21T07:28:40.000Z
2021-03-10T19:59:48.000Z
interface/get_ids.py
microsoft/multilabel-clustering-audio
4f2b707095c7e5050c3fffde9638d8d54600cae9
[ "MIT" ]
null
null
null
interface/get_ids.py
microsoft/multilabel-clustering-audio
4f2b707095c7e5050c3fffde9638d8d54600cae9
[ "MIT" ]
6
2019-11-07T18:51:25.000Z
2021-04-12T20:39:23.000Z
import os import random import sqlite3 as sql from db_tables import ses, Annotation, Recording, RecordingGroup audio_file = random.choice(os.listdir('/Users/anaemendezmendez/Documents/NYU_PHD/Mark/code/docs/media/audio/Train_data/1')) recording_id = ses.query(Recording).filter(Recording.file_name == audio_file).first().id print(recording_id) audio = ses.query(Annotation).filter(Annotation.recording_id == recording_id).first() print(audio) while audio != None: audio_file = random.choice(os.listdir('/Users/anaemendezmendez/Documents/NYU_PHD/Mark/code/docs/media/audio/Train_data/1')) recording_id = ses.query(Recording).filter(Recording.file_name == audio_file).first().id print(recording_id) audio = ses.query(Annotation).filter(Annotation.recording_id == recording_id).first()
35.521739
125
0.76989
113
817
5.39823
0.327434
0.144262
0.04918
0.068852
0.809836
0.809836
0.809836
0.809836
0.809836
0.809836
0
0.004082
0.100367
817
23
126
35.521739
0.82585
0
0
0.571429
0
0.142857
0.203518
0.203518
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0.214286
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
09c899bba49b004c409cc4642b56248a5701c42b
100
py
Python
app/products/models.py
DakobedBard/BaseDjango
27b475505cf109125333e30a0517a21ee982ed91
[ "MIT" ]
null
null
null
app/products/models.py
DakobedBard/BaseDjango
27b475505cf109125333e30a0517a21ee982ed91
[ "MIT" ]
null
null
null
app/products/models.py
DakobedBard/BaseDjango
27b475505cf109125333e30a0517a21ee982ed91
[ "MIT" ]
null
null
null
from django.db import models from django.urls import reverse from upload.models import Document
12.5
34
0.81
15
100
5.4
0.6
0.246914
0
0
0
0
0
0
0
0
0
0
0.16
100
7
35
14.285714
0.964286
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
09f899f665adc116ec1a32f92b6a46ce9f57ee7a
52
py
Python
hello1.py
yugrocks/abcde
7b55ea6a7c0420624634f4d608411d09a294899a
[ "MIT" ]
null
null
null
hello1.py
yugrocks/abcde
7b55ea6a7c0420624634f4d608411d09a294899a
[ "MIT" ]
null
null
null
hello1.py
yugrocks/abcde
7b55ea6a7c0420624634f4d608411d09a294899a
[ "MIT" ]
1
2018-10-16T17:01:10.000Z
2018-10-16T17:01:10.000Z
def hello_world(): print("Hello world hoe r u")
26
32
0.653846
9
52
3.666667
0.777778
0.606061
0
0
0
0
0
0
0
0
0
0
0.211538
52
2
32
26
0.804878
0
0
0
0
0
0.365385
0
0
0
0
0
0
1
0.5
true
0
0
0
0.5
0.5
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
1
1
0
0
0
0
1
0
6
111a7e652b2043457ad4f2a650e2001db0ea25da
46
py
Python
fastanalysis/__init__.py
FastTrackOrg/FastAnalysis
fa8e8c72be034c3eb0fa3f40718134f784445a5c
[ "MIT" ]
2
2021-05-07T17:06:51.000Z
2021-10-12T12:15:28.000Z
fastanalysis/__init__.py
FastTrackOrg/FastAnalysis
fa8e8c72be034c3eb0fa3f40718134f784445a5c
[ "MIT" ]
1
2022-03-12T01:04:18.000Z
2022-03-12T01:04:18.000Z
fastanalysis/__init__.py
FastTrackOrg/FastAnalysis
fa8e8c72be034c3eb0fa3f40718134f784445a5c
[ "MIT" ]
null
null
null
from .load import Load from .plot import Plot
15.333333
22
0.782609
8
46
4.5
0.5
0
0
0
0
0
0
0
0
0
0
0
0.173913
46
2
23
23
0.947368
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
114a7caf2257d42ff28a967b798d69a409e30dd4
41
py
Python
ex111/utilidades/__init__.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
ex111/utilidades/__init__.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
ex111/utilidades/__init__.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
from ex111.utilidades import dado, moeda
20.5
40
0.829268
6
41
5.666667
1
0
0
0
0
0
0
0
0
0
0
0.083333
0.121951
41
1
41
41
0.861111
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
febef73af8783e2a4194db65d3ed889ca6607c68
36
wsgi
Python
application.wsgi
direvus/xkcd936
638a3dd9031f76e9574201fefa7f6ffcc2e40ba0
[ "MIT" ]
null
null
null
application.wsgi
direvus/xkcd936
638a3dd9031f76e9574201fefa7f6ffcc2e40ba0
[ "MIT" ]
null
null
null
application.wsgi
direvus/xkcd936
638a3dd9031f76e9574201fefa7f6ffcc2e40ba0
[ "MIT" ]
null
null
null
from code import app as application
18
35
0.833333
6
36
5
1
0
0
0
0
0
0
0
0
0
0
0
0.166667
36
1
36
36
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
fec868579dd831433486da29fd1806ca4c45eeb5
4,219
py
Python
vsa-projects-master/proj05/proj05.py
LaneSherrill/vsa-projects
f329e65865135f0a56ac396bf1a35e41231d728e
[ "MIT" ]
null
null
null
vsa-projects-master/proj05/proj05.py
LaneSherrill/vsa-projects
f329e65865135f0a56ac396bf1a35e41231d728e
[ "MIT" ]
null
null
null
vsa-projects-master/proj05/proj05.py
LaneSherrill/vsa-projects
f329e65865135f0a56ac396bf1a35e41231d728e
[ "MIT" ]
null
null
null
# Name: Lane Sherrill # Date: June 21, 2017 # proj05: functions and lists # Part I def divisors(num): divider=1 divisornum=0 div=1 divisornum divlist = [] divr2=0 first=0 last=0 for x in range(0, num): divr = num / int(div) div=div+1 if num%divr == 0: if divr!=divr2: divlist.append(int(divr)) divr2 = divr divisornum=divisornum+1 print divlist print divisornum # WHERE DIVLIST IS FIXED return divlist def prime(num): divider = 1 div = 1 divlist = [] divr2 = 0 for x in range(0, num): divr = num / int(div) div = div + 1 if num % divr == 0: if divr != divr2: divlist.append(int(divr)) divr2 = divr if divr2%2==0: divr2=False print " " print num,"is not prime" else: divr2=True print" " print num,"is prime" return divr2 # Part II def intersection(lst1, lst2): """ Takes two lists and returns a list of the elements in common between the lists :param lst1: list, any type :param lst2: list, any type :return: list, any type """ lst12=[lst1+lst2] print lst12 return ["test"] # Part III def find_ab(side1, side2, side3): sides=[] if side1>side2: if side1> side3: a=side2 b=side3 elif side2>side1: if side2> side3: a= side1 b= side3 elif side3>side2: if side3> side1: a=side1 b=side2 """ Takes three side lengths and returns two smallest in a list :param side1: int or float :param side2: int or float :param side3: int or float :return: list of 2 ints or floats """ return [a, b] def find_c(side1, side2, side3): """ Takes three side lengths an returns the largest :param side1: int or float :param side2: int or float :param side3: int or float :return: int or float """ return 0 def square(side): """ Takes a side length and returns the side length squared :param side: int or float :return: int or float """ return 0 def pythagorean(a,b,c): """ Takes three side lengths and returns true if a^2 + b^2 = c^2, otherwise false :param a: int or float :param b: int or float :param c: int or float :return: bool """ return False def is_right(side1, side2, side3): """ Takes three side lengths and returns true if triangle is right :param side1: int or float :param side2: int or float :param side3: int or float :return: bool """ return False # TESTS # Feel free to add your own tests as needed! # print ("Divisors Tests") # #Test 1 # if divisors(1) == [1]: # print("Test 1: PASS") # else: # print("Test 1: FAIL") # # # Test 2 # if divisors(8) == [1,2,4,8]: # print("Test 2: PASS") # else: # print("Test 2: FAIL") # # # Test 3 # if divisors(9) == [1,3,9]: # print("Test 3: PASS\n") # else: # print("Test 3: FAIL\n") # # print("Prime Tests") # # Test 4 # if prime(9): # print("Test 4: FAIL") # else: # print("Test 4: PASS") # # # Test 5 # if prime(7): # print("Test 5: PASS\n") # else: # print("Test 5: FAIL\n") L1 = [] L2 = [3, 4] L3 = [3, "a"] L4 = [5, "b", 10, 7, "a"] L5 = [5, 7, 11] print("Intersection Tests") # Test 6 if intersection(L1, L2) == []: print("Test 6: PASS") else: print("Test 6: FAIL") # Test 7 if intersection(L2, L3) == [3]: print("Test 7: PASS") else: print("Test 7: FAIL") # Test 8 if intersection(L2, L4) == []: print("Test 8: PASS") else: print("Test 8: FAIL") # Test 9 if intersection(L3, L4) == ["a"]: print("Test 9: PASS") else: print("Test 9: FAIL") # Test 10 if intersection(L4, L5) == [5, 7]: print("Test 10: PASS\n") else: print("Test 10: FAIL\n") # print("Is_Right Tests") # # Test 11 # if is_right(5, 3, 4): # print("Test 11: PASS") # else: # print("Test 11: FAIL") # # # Test 12 # if is_right(9, 3, 4): # print("Test 12: FAIL") # else: # print("Test 12: PASS")
4,219
4,219
0.544205
616
4,219
3.717532
0.191558
0.094323
0.065502
0.052402
0.297817
0.274236
0.260699
0.218341
0.186026
0.186026
0
0.063176
0.320929
4,219
1
4,219
4,219
0.736126
0.984594
0
0.404255
0
0
0.079817
0
0
0
0
0
0
0
null
null
0.053191
0
null
null
0.191489
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
6
fedf472168a6d713de90b8b9c153587ba62c0349
3,045
py
Python
MyWork/OldFiles/Beginner/FunctionsWithOutput.py/MultipleReturnValues.py
minefarmer/100-Days-Python
b80b28d299342b490082ac301a0d8b176419f8f9
[ "Unlicense" ]
null
null
null
MyWork/OldFiles/Beginner/FunctionsWithOutput.py/MultipleReturnValues.py
minefarmer/100-Days-Python
b80b28d299342b490082ac301a0d8b176419f8f9
[ "Unlicense" ]
null
null
null
MyWork/OldFiles/Beginner/FunctionsWithOutput.py/MultipleReturnValues.py
minefarmer/100-Days-Python
b80b28d299342b490082ac301a0d8b176419f8f9
[ "Unlicense" ]
null
null
null
# def format_name(f_name, l_name): # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return f"{formated_f_name} {formated_l_name}" # print("This got printed") # print(format_name("RicHARD", "MATSON")) # Richard Matson # def format_name(f_name, l_name): # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return f"{formated_f_name} {formated_l_name}" # print("This got printed") # This was not printed because the return is the end of the function # print(format_name("RicHARD", "MATSON")) # Richard Matson # def format_name(f_name, l_name): # # if f_name == "" or l_name == "": # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return f"{formated_f_name} {formated_l_name}" # print(format_name(input("What is your first name? "), input("What is your last name? "))) # What is your first name? RICH # What is your last name? matson # Rich Matson # def format_name(f_name, l_name): # # if f_name == "" or l_name == "": # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return f"Result: {formated_f_name} {formated_l_name}" # print(format_name(input("What is your first name? "), input("What is your last name? "))) # What is your first name? # What is your last name? # Result: # def format_name(f_name, l_name): # if f_name == "" or l_name == "": # return # This escapes the function if no names are entered and None is the last output # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return f"Result: {formated_f_name} {formated_l_name}" # print(format_name(input("What is your first name? "), input("What is your last name? "))) # What is your first name? # What is your last name? # None def format_name(f_name, l_name): if f_name == "" or l_name == "": return "You didn't provide valid inputs." # Whenno valid inputs are given == this exits the function formated_f_name = f_name.title() formated_l_name = l_name.title() return f"Result: {formated_f_name} {formated_l_name}" print(format_name(input("What is your first name? "), input("What is your last name? "))) # What is your first name? # What is your last name? # You didn't provide valid inputs.
42.887324
125
0.509031
368
3,045
3.961957
0.130435
0.096022
0.109739
0.082305
0.872428
0.860082
0.824417
0.824417
0.824417
0.824417
0
0
0.392447
3,045
70
126
43.5
0.788108
0.609524
0
0
0
0
0.108963
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.428571
0.142857
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
3a36be5f03068287c04887a640a04fd978cf2df6
71
py
Python
paypal/models.py
itbabu/django-oscar-paypal
0004fcb416b73529396c746940d5bf2cf8ded6c2
[ "BSD-3-Clause" ]
1
2019-06-27T13:58:49.000Z
2019-06-27T13:58:49.000Z
paypal/models.py
itbabu/django-oscar-paypal
0004fcb416b73529396c746940d5bf2cf8ded6c2
[ "BSD-3-Clause" ]
null
null
null
paypal/models.py
itbabu/django-oscar-paypal
0004fcb416b73529396c746940d5bf2cf8ded6c2
[ "BSD-3-Clause" ]
null
null
null
from paypal.express.models import * from paypal.payflow.models import *
35.5
35
0.816901
10
71
5.8
0.6
0.344828
0
0
0
0
0
0
0
0
0
0
0.098592
71
2
36
35.5
0.90625
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
3a4aafa5ffce908a63faa011f8b8136a97690dcb
70
py
Python
py_tdlib/constructors/top_chat_category_groups.py
Mr-TelegramBot/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
24
2018-10-05T13:04:30.000Z
2020-05-12T08:45:34.000Z
py_tdlib/constructors/top_chat_category_groups.py
MrMahdi313/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
3
2019-06-26T07:20:20.000Z
2021-05-24T13:06:56.000Z
py_tdlib/constructors/top_chat_category_groups.py
MrMahdi313/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
5
2018-10-05T14:29:28.000Z
2020-08-11T15:04:10.000Z
from ..factory import Type class topChatCategoryGroups(Type): pass
11.666667
34
0.785714
8
70
6.875
0.875
0
0
0
0
0
0
0
0
0
0
0
0.142857
70
5
35
14
0.916667
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.333333
0.333333
0
0.666667
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
1
1
0
1
0
0
6
3a4fe82d2e435f85819aa8534065aa134c556d3e
4,518
py
Python
write_gspread.py
ba-san/DL-CV-tools
ae5895a189fde39abe342ec19eaca2f388504b48
[ "MIT" ]
1
2019-05-22T09:15:40.000Z
2019-05-22T09:15:40.000Z
write_gspread.py
ba-san/DL-CV-tools
ae5895a189fde39abe342ec19eaca2f388504b48
[ "MIT" ]
null
null
null
write_gspread.py
ba-san/DL-CV-tools
ae5895a189fde39abe342ec19eaca2f388504b48
[ "MIT" ]
1
2019-06-19T10:19:55.000Z
2019-06-19T10:19:55.000Z
# https://qiita.com/akabei/items/0eac37cb852ad476c6b9 import os import glob import gspread# https://qiita.com/akabei/items/0eac37cb852ad476c6b9 import os import glob import gspread import pandas as pd from oauth2client.service_account import ServiceAccountCredentials global clear_last clear_last = 1 #def update_gspread(dset_fname, train_acc, test_acc, train_loss, test_loss, epoch, otherparams): def update_gspread(dset_fname, network_name, dataset_directory, train_acc, train_loss, test_acc, test_loss, current_epoch, all_epoch, otherparams=None): global clear_last ### open google spreadsheet ### scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('something.json', scope) gc = gspread.authorize(credentials) final_wks = gc.open('something').worksheet("Final") last_wks = gc.open('something').worksheet("Last") ### updating ### separate_dset_fname = dset_fname.split("_") dataset_name = separate_dset_fname[0] crp_x_length = separate_dset_fname[-8] crp_y_length = separate_dset_fname[-7] x_interval = separate_dset_fname[-6] y_interval = separate_dset_fname[-5] thorn = separate_dset_fname[-4] num_of_class = len(os.listdir(dataset_directory + "/" + dset_fname + "/train/")) resize_x_length = separate_dset_fname[-2] resize_y_length = separate_dset_fname[-1] train_list = glob.glob(dataset_directory + "/" + dset_fname + "/train/*/*.jpg", recursive=True) test_list = glob.glob(dataset_directory + "/" + dset_fname + "/test/*/*.jpg", recursive=True) new_row = [dataset_name, network_name, dataset_directory + "/" + dset_fname, train_loss, test_loss, train_acc, test_acc, len(train_list)+len(test_list), len(train_list), len(test_list), num_of_class, crp_x_length, crp_y_length, resize_x_length, resize_y_length, x_interval, y_interval, thorn, current_epoch] for i in range(len(otherparams)): new_row.append(otherparams[i]) if clear_last ==1: last_wks.resize(3) clear_last = 0 csvcolumns = ['dataset name', 'network name', 'place', 'train_loss', 'test_loss', 'train_acc', 'test_acc', 'total img', 'train img', 'test img', 'num of class', 'x-side', 'y-side', 'x-side', 'y-side', 'x-interval', 'y-interval', 'thorn', 'epoch'] for i in range(len(otherparams)): csvcolumns.append('from nw') df = pd.DataFrame(columns=csvcolumns) df.to_csv('./' + dataset_name + '_' + network_name + '_result.csv') last_wks.append_row(new_row) df = pd.read_csv('./' + dataset_name + '_' + network_name + '_result.csv', index_col=0) series = pd.Series(new_row, index=df.columns) df = df.append(series, ignore_index=True) df.to_csv('./' + dataset_name + '_' + network_name + '_result.csv') if current_epoch == all_epoch-1: final_wks.append_row(new_row) from oauth2client.service_account import ServiceAccountCredentials #def update_gspread(dset_fname, train_acc, test_acc, train_loss, test_loss, epoch, otherparams): def update_gspread(dset_fname, network_name, dataset_directory, train_acc, train_loss, test_acc, test_loss, epoch, otherparams=None): ### open google spreadsheet ### scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('something.json', scope) gc = gspread.authorize(credentials) wks = gc.open('something').sheet1 ### updating ### separate_dset_fname = dset_fname.split("_") dataset_name = separate_dset_fname[0] crp_x_length = separate_dset_fname[-8] crp_y_length = separate_dset_fname[-7] x_interval = separate_dset_fname[-6] y_interval = separate_dset_fname[-5] thorn = separate_dset_fname[-4] num_of_class = len(os.listdir(dataset_directory + "/" + dset_fname + "/train/")) resize_x_length = separate_dset_fname[-2] resize_y_length = separate_dset_fname[-1] train_list = glob.glob(dataset_directory + "/" + dset_fname + "/train/*/*.jpg", recursive=True) test_list = glob.glob(dataset_directory + "/" + dset_fname + "/test/*/*.jpg", recursive=True) new_row = [dataset_name, network_name, dataset_directory + "/" + dset_fname, train_loss, test_loss, train_acc, test_acc, len(train_list)+len(test_list), len(train_list), len(test_list), num_of_class, crp_x_length, crp_y_length, resize_x_length, resize_y_length, x_interval, y_interval, thorn, epoch] for i in range(len(otherparams)): new_row.append(otherparams[i]) wks.append_row(new_row)
37.032787
152
0.738822
640
4,518
4.882813
0.173438
0.09216
0.09792
0.05888
0.86176
0.8208
0.78176
0.77088
0.76064
0.73632
0
0.011866
0.123285
4,518
121
153
37.338843
0.777077
0.080124
0
0.689189
0
0
0.120213
0
0
0
0
0
0
1
0.027027
false
0
0.121622
0
0.148649
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
28c88339f9a769a1aa3359bce195167d474ab705
75
py
Python
src/invoker.py
leftember/poesmartlootfilter
4a912dc408299ca162f60ba79448b1985be25ad2
[ "Apache-2.0" ]
null
null
null
src/invoker.py
leftember/poesmartlootfilter
4a912dc408299ca162f60ba79448b1985be25ad2
[ "Apache-2.0" ]
null
null
null
src/invoker.py
leftember/poesmartlootfilter
4a912dc408299ca162f60ba79448b1985be25ad2
[ "Apache-2.0" ]
null
null
null
import myConfig from myConfig import conf print(conf) print(myConfig.conf)
15
25
0.826667
11
75
5.636364
0.454545
0.290323
0
0
0
0
0
0
0
0
0
0
0.106667
75
4
26
18.75
0.925373
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0.5
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
1
0
1
0
0
1
0
6
28d7a1a3e1d8e35ccbab483b7097603d1b388fd0
97
py
Python
app/workers/search/tasks/__init__.py
d3vzer0/reternal-backend
aeeb613c820759212e7aef9150738a66b2882d50
[ "MIT" ]
6
2019-01-01T23:38:12.000Z
2021-07-27T03:43:11.000Z
app/workers/search/__init__.py
d3vzer0/reternal-backend
aeeb613c820759212e7aef9150738a66b2882d50
[ "MIT" ]
1
2020-08-02T00:21:41.000Z
2020-08-02T00:21:41.000Z
app/workers/search/tasks/__init__.py
d3vzer0/reternal-backend
aeeb613c820759212e7aef9150738a66b2882d50
[ "MIT" ]
1
2021-07-27T03:43:24.000Z
2021-07-27T03:43:24.000Z
from app.workers.search.tasks.logsources import * from app.workers.search.tasks.indices import *
32.333333
49
0.814433
14
97
5.642857
0.571429
0.177215
0.35443
0.506329
0.632911
0
0
0
0
0
0
0
0.082474
97
2
50
48.5
0.88764
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
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
1
0
1
0
0
0
0
6
e90d33ba26bde6d60b4953e07fb8ae962e0acefd
405
py
Python
python_programs/sqrt_test.py
vitchyr/QuixBugs
1fd2c3402e1a2aa3ff9ec22d7ba82c07b59996c2
[ "MIT" ]
null
null
null
python_programs/sqrt_test.py
vitchyr/QuixBugs
1fd2c3402e1a2aa3ff9ec22d7ba82c07b59996c2
[ "MIT" ]
null
null
null
python_programs/sqrt_test.py
vitchyr/QuixBugs
1fd2c3402e1a2aa3ff9ec22d7ba82c07b59996c2
[ "MIT" ]
null
null
null
from .sqrt import sqrt def test_main(): assert sqrt(2, 0.01) == 1.4166666666666665 assert sqrt(3, 0.001) == 1.7321428571428572 assert sqrt(4, 0) == 2.0 assert sqrt(132, 0.01) == 11.489422513833343 assert sqrt(132, 0.1) == 11.489422513833343 assert sqrt(132, 1) == 11.489422513833343 assert sqrt(123124, 0.1) == 350.8902962974845 if __name__ == "__main__": test_main()
23.823529
49
0.651852
59
405
4.305085
0.40678
0.275591
0.153543
0.318898
0.350394
0
0
0
0
0
0
0.425466
0.204938
405
16
50
25.3125
0.363354
0
0
0
0
0
0.019802
0
0
0
0
0
0.636364
1
0.090909
true
0
0.090909
0
0.181818
0
0
0
0
null
1
0
1
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
1
0
0
1
0
0
0
0
0
0
6
3a63d73673c04775898fd737022f1813f344514d
24,998
py
Python
plone-chrigl-debian/src/collective.flattr/collective/flattr/tests/test_flattr_view.py
chrigl/docker-library
5dc9a2c1f0d81aba42190d3ff0e28c1fab2240d1
[ "Apache-2.0" ]
null
null
null
plone-chrigl-debian/src/collective.flattr/collective/flattr/tests/test_flattr_view.py
chrigl/docker-library
5dc9a2c1f0d81aba42190d3ff0e28c1fab2240d1
[ "Apache-2.0" ]
null
null
null
plone-chrigl-debian/src/collective.flattr/collective/flattr/tests/test_flattr_view.py
chrigl/docker-library
5dc9a2c1f0d81aba42190d3ff0e28c1fab2240d1
[ "Apache-2.0" ]
null
null
null
import unittest2 as unittest import urllib2 from AccessControl import Unauthorized from plone.app.testing import TEST_USER_ID from plone.app.testing import setRoles from zope.component import getUtility from plone.registry.interfaces import IRegistry from collective.flattr.interfaces import ICollectiveFlattr from mocker import Mocker from Products.statusmessages.interfaces import IStatusMessage from collective.flattr.tests.mocks import MockOpener from collective.flattr.tests.base import COLLECTIVE_FLATTR_INTEGRATION_TESTING class as_manager(object): def __init__(self, portal): self.portal = portal def __enter__(self): setRoles(self.portal, TEST_USER_ID, ('Manager',)) return self.portal.restrictedTraverse('@@collective_flattr') def __exit__(self, type, value, traceback): setRoles(self.portal, TEST_USER_ID, ('Member',)) class TestFlattrView(unittest.TestCase): layer = COLLECTIVE_FLATTR_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] setRoles(self.portal, TEST_USER_ID, ('Member',)) def test_permissions(self): # only cmf.ManagePortal has access! error = False try: self.portal.restrictedTraverse('@@collective_flattr') except Unauthorized: error = True self.assertTrue(error) def test_access_token_url(self): with as_manager(self.portal) as view: ret = view.access_token_url self.assertEquals(ret, u'https://flattr.com/oauth/token') def test_authorize_url(self): with as_manager(self.portal) as view: ret = view.authorize_url self.assertEquals(ret, u'https://flattr.com/oauth/authorize') def test_registry(self): with as_manager(self.portal) as view: ret = view.registry self.assertEquals(ret.__dict__, getUtility(IRegistry).forInterface(ICollectiveFlattr).\ __dict__) def test_access_token_empty(self): with as_manager(self.portal) as view: ret = view.access_token self.failUnless(ret is None) def test_access_token(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'8843d7f92416211de9ebb963ff4ce28125932878' reg.access_token_type = u'Bearer' with as_manager(self.portal) as view: ret = view.access_token self.assertTrue(isinstance(ret, dict)) self.assertEquals(ret['Authorization'], u'Bearer 8843d7f92416211de9ebb963ff4ce28125932878') def test_consumer_empty(self): with as_manager(self.portal) as view: ret = view.consumer self.failUnless(ret is None) def test_consumer(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.customer_key = u'mycustomer' reg.customer_secret = u'mysecret' with as_manager(self.portal) as view: ret = view.consumer self.assertTrue(isinstance(ret, dict)) self.assertEquals(ret['key'], u'mycustomer') self.assertEquals(ret['secret'], u'mysecret') def test_setAccessToken(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) with as_manager(self.portal) as view: view._setAccessToken(u'a', u'bearer') self.assertEquals(reg.access_token, u'a') self.assertEquals(reg.access_token_type, u'Bearer') view._setAccessToken(u'c', u'bearer') self.assertEquals(reg.access_token, u'c') self.assertEquals(reg.access_token_type, u'Bearer') def test_setAccessToken_no_unicode(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) with as_manager(self.portal) as view: view._setAccessToken('a', 'bearer') self.assertEquals(reg.access_token, u'a') self.assertEquals(reg.access_token_type, u'Bearer') view._setAccessToken('c', 'bearer') self.assertEquals(reg.access_token, u'c') self.assertEquals(reg.access_token_type, u'Bearer') def test_getAccessToken_no_customer(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) with as_manager(self.portal) as view: reg.customer_key = u'customer' ret = view.getAccessToken(1234) self.assertEquals(ret['error'], u'no_customer') self.assertEquals(ret['error_description'], u'no customer_key or customer_secret configured') reg.customer_key = u'' reg.customer_secret = u'secret' self.assertEquals(ret['error'], u'no_customer') self.assertEquals(ret['error_description'], u'no customer_key or customer_secret configured') reg.customer_key = u'' reg.customer_secret = u'' self.assertEquals(ret['error'], u'no_customer') self.assertEquals(ret['error_description'], u'no customer_key or customer_secret configured') def test_getAccessToken_token_configured(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.customer_key = u'customer' reg.customer_secret = u'secret' with as_manager(self.portal) as view: reg.access_token = u'token' reg.access_token_type = u'Bearer' ret = view.getAccessToken(1234) self.assertEquals(ret['error'], u'token_configured') self.assertEquals(ret['error_description'], u'access token already configured') def test_getAccessToken(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.customer_key = u'customer' reg.customer_secret = u'secret' with as_manager(self.portal) as view: mocker = Mocker() obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{"access_token":"NEW_ACCESS_TOKEN","token_type":"bearer"}', verify_data=lambda x: x.get_full_url()==u'https://flattr.com/oauth/token' and x.data=='{"redirect_uri": "http://nohost/plone/collective_flattr", "code": 1234, "grant_type": "authorization_code"}' and x.headers=={'Content-type': 'application/json'})) obj.opener mocker.result(MockOpener('{"error":"invalid_request","error_description":"error desc"}', error=True, verify_data=lambda x: x.get_full_url()==u'https://flattr.com/oauth/token' and x.data=='{"redirect_uri": "http://nohost/plone/collective_flattr", "code": 1234, "grant_type": "authorization_code"}' and x.headers=={'Content-type': 'application/json'} )) with mocker: ret = view.getAccessToken(1234) self.failUnless(u'error' not in ret) self.failUnless(u'error_description' not in ret) self.failUnless(u'access_token' in ret) self.failUnless(u'token_type' in ret) self.assertEquals(ret['access_token'], u'NEW_ACCESS_TOKEN') self.assertEquals(ret['token_type'], u'bearer') # second call get an inner status of != 200 and # will return None ret = view.getAccessToken(1234) self.failUnless(u'error' in ret) self.failUnless(u'error_description' in ret) self.failUnless(u'access_token' not in ret) self.failUnless(u'token_type' not in ret) self.assertEquals(ret['error'], u'invalid_request') self.assertEquals(ret['error_description'], u'error desc') def test_opener(self): from collective.flattr.browser.flattr import Flattr view = Flattr(self.portal, self.layer['request']) ret = view.opener self.assertTrue(isinstance(ret, urllib2.OpenerDirector)) def test_opener_authorization(self): from collective.flattr.browser.flattr import Flattr reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'TOKEN' reg.access_token_type = u'Bearer' view = Flattr(self.portal, self.layer['request']) ret = view.opener self.assertTrue(isinstance(ret, urllib2.OpenerDirector)) self.assertEquals(ret.addheaders, [('Authorization', 'Bearer TOKEN')]) def test_opener_base_auth(self): from collective.flattr.browser.flattr import Flattr reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' reg.access_token_type = u'' reg.customer_key = u'USER' reg.customer_secret = u'PASS' view = Flattr(self.portal, self.layer['request']) ret = view.opener self.assertTrue(isinstance(ret, urllib2.OpenerDirector)) self.assertEquals(ret.addheaders, [('Authorization', 'Basic VVNFUjpQQVNT')]) def test_getLanguages(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[{"id": "de_DE", "text": "German"}, {"id": "en_US", "text": "English"}]')) with mocker: ret = view.getLanguages() self.failUnless(isinstance(ret, list)) self.assertEquals(len(ret), 2) self.assertEquals(ret[0], {'id': u'de_DE', 'text': u'German'}) self.assertEquals(ret[1], {'id': u'en_US', 'text': u'English'}) def test_getLanguages_HTTPError(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[{"id": "de_DE", "text": "German"}, {"id": "en_US", "text": "English"}]', error=True)) with mocker: ret = view.getLanguages() self.failUnless(isinstance(ret, list)) self.assertEquals(len(ret), 0) def test_getCategories(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[{"id": "text", "text": "Text"}, {"id": "images", "text": "Images"}]')) with mocker: ret = view.getCategories() self.failUnless(isinstance(ret, list)) self.assertEquals(len(ret), 2) self.assertEquals(ret[0], {'id': u'text', 'text': u'Text'}) self.assertEquals(ret[1], {'id': u'images', 'text': u'Images'}) def test_getCategories_HTTPError(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[{"id": "text", "text": "Text"}, {"id": "images", "text": "Images"}]', error=True)) with mocker: ret = view.getCategories() self.failUnless(isinstance(ret, list)) self.assertEquals(len(ret), 0) def test_getParams(self): from collective.flattr.browser.flattr import Flattr view = Flattr(self.portal, self.layer['request']) ret = view._getParams(u'Hello') self.assertEquals(ret, 'title=Hello&hidden=False') ret = view._getParams(u'Hello', url=u'http://localhost/', description='desc', category='cat', language='de_DE', tags='a,b', patch='patch', hidden=True) self.assertEquals(ret, 'title=Hello&hidden=True&url=http%3A%2F%2Flocalhost%2F&description=desc&category=cat&language=de_DE&tags=a%2Cb&_method=patch') def test_createThing(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{ "id": 431547, "link": "https://api.flattr.dev/rest/v2/things/431547", "message": "ok", "description": "Thing was created successfully" }', verify_data = lambda x: x.get_data() == 'title=Hello&hidden=True&url=http%3A%2F%2Flocalhost%2F&description=desc&category=cat&language=de_DE&tags=a%2Cb')) with mocker: ret = view.createThing(u'Hello', url=u'http://localhost/', description='desc', category='cat', language='de_DE', tags='a,b', hidden=True) self.assertEquals(ret, {'id': 431547, 'link': u'https://api.flattr.dev/rest/v2/things/431547', 'message': u'ok', 'description': u'Thing was created successfully' }) def test_createThing_wrong_data(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{ "id": 431547, "link": "https://api.flattr.dev/rest/v2/things/431547", "message": "ok", "description": "Thing was created successfully" }', verify_data = lambda x: x.get_data() == 'title=Hello&hidden=True&url=http%3A%2F%2Flocalhost%2F&description=desc&category=cat&language=de_DE&tags=a%2Cb')) with mocker: ret = False try: view.createThing(u'Hello', url=u'http://localhost/', description='desc', category='cat', language='en_DE', tags='a,b', hidden=True) except ValueError: ret = True self.assertTrue(ret) def test_createThing_HTTPError(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{ "id": 431547, "link": "https://api.flattr.dev/rest/v2/things/431547", "message": "ok", "description": "Thing was created successfully" }', verify_data = lambda x: x.get_data() == 'title=Hello&hidden=True&url=http%3A%2F%2Flocalhost%2F&description=desc&category=cat&language=de_DE&tags=a%2Cb', error=True)) with mocker: ret = view.createThing(u'Hello', url=u'http://localhost/', description='desc', category='cat', language='de_DE', tags='a,b', hidden=True) self.assertEquals(ret, {}) def test_updateThing(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{ "message": "ok", "description": "Thing was updated successfully" }', verify_data = lambda x: x.get_full_url().endswith('431547') and x.get_data() == 'title=Hello&hidden=True&description=desc&category=cat&language=de_DE&tags=a%2Cb&_method=patch')) with mocker: ret = view.updateThing(u'Hello', 431547, description='desc', category='cat', language='de_DE', tags='a,b', hidden=True) self.assertEquals(ret, {'message': u'ok', 'description': u'Thing was updated successfully' }) def test_updateThing_HTTPError(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('{ "message": "ok", "description": "Thing was updated successfully" }', verify_data = lambda x: x.get_full_url().endswith('431547') and x.get_data() == 'title=Hello&hidden=True&description=desc&category=cat&language=de_DE&tags=a%2Cb&_method=patch', error=True)) with mocker: ret = view.updateThing(u'Hello', 431547, description='desc', category='cat', language='de_DE', tags='a,b', hidden=True) self.assertEquals(ret, {}) def test_getThing(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) def test_func(x): return 'count=30&page=' in x.get_data() obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[ { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }, { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2} ]', verify_data=test_func)) obj.opener mocker.result(MockOpener('', verify_data=test_func, error=True)) with mocker: ret = view.getThings() self.failUnless(u'data' in ret) self.failUnless(u'next_page' in ret) self.assertFalse(ret['next_page']) self.assertEquals(ret['data'][0], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }) self.assertEquals(ret['data'][1], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2}) def test_getThing_with_next(self): from collective.flattr.browser.flattr import Flattr mocker = Mocker() view = Flattr(self.portal, self.layer['request']) obj = mocker.patch(view) obj.opener mocker.result(MockOpener('[ { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }, { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2} ]', verify_data=lambda x: 'count=30&page=' in x.get_data())) mocker.count(2) # if the same thing is called twice, it is called for the first page # and again for the second page. So there is a result, what means that # there is a next page with mocker: ret = view.getThings() self.failUnless(u'data' in ret) self.failUnless(u'next_page' in ret) self.assertTrue(ret['next_page']) self.assertEquals(ret['data'][0], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }) self.assertEquals(ret['data'][1], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2}) class TestFlattrViewCall(unittest.TestCase): layer = COLLECTIVE_FLATTR_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] setRoles(self.portal, TEST_USER_ID, ('Member',)) def test_call_access_denied(self): with as_manager(self.portal) as view: from collective.flattr.browser.flattr import Flattr view = Flattr(self.portal, self.layer['request']) ret = view() self.layer['request']['error'] = u'access_denied' self.layer['request']['error_description'] = u'error description' ret = view() self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages()[0] self.assertEquals(ret.message, u'access_denied: error description') self.assertEquals(ret.type, u'error') def test_call_invalid_request(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' mocker = Mocker() func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken') func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz') mocker.result({'error': u'invalid_request', 'error_description': u'error desc'}) with as_manager(self.portal) as view: ## need the real class here, not the wrapped one, to get mocker ## working from collective.flattr.browser.flattr import Flattr with mocker: view = Flattr(self.portal, self.layer['request']) self.layer['request']['code'] = u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' ret = view() self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages()[0] self.assertEquals(ret.message, u'invalid_request: error desc') self.assertEquals(ret.type, u'error') def test_call_valid(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' mocker = Mocker() func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken') func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz') mocker.result({'access_token': u'NEW_ACCESS_TOKEN', 'token_type': u'bearer'}) with as_manager(self.portal) as view: ## need the real class here, not the wrapped one, to get mocker ## working from collective.flattr.browser.flattr import Flattr with mocker: self.layer['request']['code'] = u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' view = Flattr(self.portal, self.layer['request']) ret = view() self.assertEquals(reg.access_token, u'NEW_ACCESS_TOKEN') self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages()[0] self.assertEquals(ret.message, u'collective.flattr successfully configured') self.assertEquals(ret.type, u'info') def test_call_no_unicode_and_error(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' with as_manager(self.portal) as view: from collective.flattr.browser.flattr import Flattr self.layer['request']['code'] = 'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' self.layer['request']['error'] = 'test' self.layer['request']['error_description'] = 'test error' view = Flattr(self.portal, self.layer['request']) ret = view() self.assertEquals(reg.access_token, u'') self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages() self.assertEquals(ret[0].message, u'test: test error') self.assertEquals(ret[0].type, u'error') def test_call_no_unicode_and_no_error_desc(self): reg = getUtility(IRegistry).forInterface(ICollectiveFlattr) reg.access_token = u'' mocker = Mocker() func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken') func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz') mocker.result({'access_token': u'NEW_ACCESS_TOKEN', 'token_type': u'bearer', 'error': u'blubber'}) with as_manager(self.portal) as view: from collective.flattr.browser.flattr import Flattr with mocker: self.layer['request']['code'] = 'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz' view = Flattr(self.portal, self.layer['request']) ret = view() self.assertEquals(reg.access_token, u'') self.assertEquals(self.layer['request'].response\ .headers['location'], 'http://nohost/plone') ret = IStatusMessage(self.layer['request'])\ .showStatusMessages() self.assertEquals(ret[0].message, u'undefined: Undefined error while getting access token') self.assertEquals(ret[0].type, u'error')
40.779772
340
0.604808
2,798
24,998
5.297713
0.084703
0.069082
0.056399
0.044998
0.837887
0.799771
0.77373
0.744519
0.725427
0.703164
0
0.015161
0.263861
24,998
612
341
40.846405
0.790349
0.015641
0
0.650862
0
0.036638
0.223609
0.051968
0
0
0
0
0.157328
1
0.084052
false
0.002155
0.068966
0.002155
0.168103
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
3a76f0ddb9df23c789e731e3731e270c625be09e
51
py
Python
aarhus/tests/__init__.py
mikedelong/aarhus
0c0e94fadd65be8428fe3bd2c92928e1b23fc2a1
[ "Apache-2.0" ]
null
null
null
aarhus/tests/__init__.py
mikedelong/aarhus
0c0e94fadd65be8428fe3bd2c92928e1b23fc2a1
[ "Apache-2.0" ]
7
2017-01-13T19:04:57.000Z
2017-01-23T14:10:53.000Z
aarhus/tests/__init__.py
mikedelong/aarhus
0c0e94fadd65be8428fe3bd2c92928e1b23fc2a1
[ "Apache-2.0" ]
null
null
null
import aarhus import aarhus.aarhus.custom_stopwords
25.5
37
0.901961
7
51
6.428571
0.571429
0.533333
0
0
0
0
0
0
0
0
0
0
0.058824
51
2
37
25.5
0.9375
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
3ac298ca5170427e606bd431728846b56aa2c0d6
8,608
py
Python
Lib/db/SqlTableDocs.py
jeamick/ares-visual
3cf5068f874b3f6fe898968b2a7efa86fadca99d
[ "MIT" ]
null
null
null
Lib/db/SqlTableDocs.py
jeamick/ares-visual
3cf5068f874b3f6fe898968b2a7efa86fadca99d
[ "MIT" ]
2
2019-03-27T00:36:09.000Z
2019-04-09T00:39:12.000Z
Lib/db/SqlTableDocs.py
jeamick/ares-visual
3cf5068f874b3f6fe898968b2a7efa86fadca99d
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: Olivier Noguès from app import db import datetime # ------------------------------------------------------------------------------------------------------------------- # SECTION DEDICATED TO THE DOCUMENTATION # class AresDoc(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc' doc_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) src_id = db.Column(db.Integer, nullable=False) dsc = db.Column(db.Text, nullable=False) rubric = db.Column(db.String(120), nullable=False) category = db.Column(db.String(120), nullable=False) module = db.Column(db.String(50), nullable=False) cls = db.Column(db.String(50), nullable=False) fnc = db.Column(db.String(50), nullable=False) type = db.Column(db.String(20), nullable=False) # FUNCTION, CLASS, MODULE section = db.Column(db.String(20), nullable=False) # ARES, REPORTS, CONNECTOR... return_dsc = db.Column(db.Text, nullable=False) name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, dsc, rubric, category, module, cls, fnc, doc_type, section, name, return_dsc, user_name, hostname, mac_address, src_id): self.dsc, self.rubric, self.category, self.module, self.cls = dsc, rubric, category, module, cls self.fnc, self.type, self.section, self.name, self.src_id = fnc, doc_type, section, name, src_id self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type) ) self.return_dsc, self.user_name, self.hostname, self.mac_address = return_dsc, user_name, hostname, mac_address class AresDocView(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_view' vw_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, user_name, hostname, mac_address): self.user_name, self.hostname, self.mac_address = user_name, hostname, mac_address self.hash_id = hashlib.sha224("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') class AresDocComments(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_comments' com_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) com = db.Column(db.Text, nullable=False) status = db.Column(db.Integer, nullable=False) # 1 active, 0 closed user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, com, status, user_name, hostname, mac_address): self.com, self.status, self.user_name, self.hostname, self.mac_address = com, status, user_name, hostname, mac_address self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') class AresDocExamples(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_examples' ex_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) ex = db.Column(db.Text, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, ex, user_name, hostname, mac_address): self.ex, self.user_name, self.hostname, self.mac_address = ex, user_name, hostname, mac_address self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') class AresDocTags(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_static_tags' ex_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) tag = db.Column(db.Text, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, tag, user_name, hostname, mac_address): self.tag, self.user_name, self.hostname, self.mac_address = tag, user_name, hostname, mac_address self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') class AresDocLinks(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_links' link_id = db.Column(db.Integer, primary_key=True, autoincrement=True) hash_id = db.Column(db.NUMERIC, nullable=False) link_name = db.Column(db.Text, nullable=False) link_url = db.Column(db.Text, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, link_name, link_url, user_name, hostname, mac_address): self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') self.link_name, self.link_url = link_name, link_url self.user_name, self.hostname, self.mac_address = user_name, hostname, mac_address self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) class AresDocParams(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_params' param_id = db.Column(db.Integer, primary_key=True, autoincrement=True) arc_id = db.Column(db.Integer, nullable=False) param_type = db.Column(db.Text, nullable=False) hash_id = db.Column(db.NUMERIC, nullable=False) name = db.Column(db.Text, nullable=False) dsc = db.Column(db.Text, nullable=False) duck_type = db.Column(db.Text, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) def __init__(self, module, cls, fnc, doc_type, param_name, param_dsc, param_duck_type, user_name, hostname, mac_address): self.clc_dt = datetime.datetime.today().strftime('%Y-%m-%d') self.user_name, self.hostname, self.mac_address = user_name, hostname, mac_address self.param_name, self.param_dsc, self.param_duck_type = param_name, param_dsc, param_duck_type self.hash_id = AresSiphash.SipHash().hashId("%s_%s_%s_%s" % (module, cls, fnc, doc_type)) class AresDocIO(db.Model): __bind_key__ = 'documentation' __tablename__ = 'doc_io' io_id = db.Column(db.Integer, primary_key=True, autoincrement=True) cod = db.Column(db.Text, nullable=False) dsc = db.Column(db.Text, nullable=False) typ = db.Column(db.Text, nullable=False) user_name = db.Column(db.String(120), nullable=False) hostname = db.Column(db.String(120), nullable=False) mac_address = db.Column(db.Integer, nullable=False) clc_dt = db.Column(db.String(10), nullable=False) lst_mod_dt = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
48.089385
123
0.704693
1,250
8,608
4.62
0.0896
0.108052
0.135065
0.083117
0.88987
0.873593
0.863723
0.716883
0.664935
0.657489
0
0.011388
0.143123
8,608
178
124
48.359551
0.771556
0.0352
0
0.532847
0
0
0.037452
0
0
0
0
0
0
1
0.051095
false
0
0.014599
0
0.810219
0
0
0
0
null
0
0
0
1
1
1
1
0
1
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
6
3ac3fe1d355cc25d94fae2e097d826bdfce1cc81
7,342
py
Python
nima/model/data_generator.py
maindolaamit/nima
3b21396da884216ca66b70cc4a200df6cce695b6
[ "Apache-2.0" ]
null
null
null
nima/model/data_generator.py
maindolaamit/nima
3b21396da884216ca66b70cc4a200df6cce695b6
[ "Apache-2.0" ]
null
null
null
nima/model/data_generator.py
maindolaamit/nima
3b21396da884216ca66b70cc4a200df6cce695b6
[ "Apache-2.0" ]
1
2021-12-27T02:34:40.000Z
2021-12-27T02:34:40.000Z
import os import numpy as np import tensorflow.keras as keras from nima.config import INPUT_SHAPE, CROP_SHAPE, print_msg from nima.utils import image_utils from nima.utils.preprocess import normalize_ratings class TrainDataGenerator(keras.utils.Sequence): def __init__(self, df, img_directory, x_col, y_col, preprocess_input, img_format='jpg', num_classes=10, batch_size=32, input_size=INPUT_SHAPE, crop_size=CROP_SHAPE, shuffle=False, normalize_pixels=False): """ Takes the dataframe and the path to the image directory and generates the batches of augmented data. :param df: Pandas dataframe containing filepaths relative to img_directory :param img_directory: path to directory to read images from :param batch_size: size of batch of data :param x_col: column name in the dataframe to read images from :param y_col: column name in the dataframe that has target data :param preprocess_input: Base CNN model's preprocessing input function :param input_size: dimension that image size get resized to when loaded :param crop_size: dimension that image gets randomly cropped to :param shuffle: weather to shuffle the data """ self.normalize_pixels = normalize_pixels self.img_directory = img_directory self.x_col, self.y_col = x_col, y_col self.batch_size = batch_size self.crop_size, self.input_size = crop_size, input_size self.shuffle = shuffle self.num_classes = num_classes self.model_preprocess_input = preprocess_input self.img_format = img_format # Filter dataframe for valid images only self.df = image_utils.filter_valid_images(df.copy(), img_directory, x_col, img_format) print_msg(f'Found {len(self.df)} valid image filenames belonging to {self.num_classes} classes.', 1) self.on_epoch_end() # set the indexes and shuffle at the start if true def __len__(self): return int(np.ceil(len(self.df) / self.batch_size)) # number of batches per epoch def __getitem__(self, index): """ The index passed into the function will be done by the fit function while training. Note : Take batch samples length not the batch size for initialization otherwise in the last epoch number of rows returned will be more than length of self.indexes and predict will fail in """ # Extract samples from df based on the index passed by fit method batch_indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size] # Reset index to not exceed the batch size batch_samples = self.df.iloc[batch_indexes].copy().reset_index(drop=True) # Initialization for faster processing x = np.empty((len(batch_samples), *self.crop_size)) y = np.empty((len(batch_samples), self.num_classes)) # loop for the images in the sample and modify for i, row in batch_samples.iterrows(): # Load the image and resize img_path = os.path.join(self.img_directory, f'{row[self.x_col]}.{self.img_format}') img = image_utils.load_image(img_path, self.input_size, self.normalize_pixels) if img is not None: # Modify image only for training purpose img = image_utils.random_crop_image(img, self.crop_size) # crop the image # randomly flip image horizontal if np.random.random() > 0.5: img = np.fliplr(img) x[i] = img y[i] = normalize_ratings(row[self.y_col]) # apply base network's preprocessing on the 4D numpy array x = self.model_preprocess_input(x) # return the image and labels return x, y def on_epoch_end(self): """Will be called before and after each epoch""" self.indexes = np.arange(len(self.df)) # Create an index if self.shuffle: # Updates indexes after each epoch np.random.shuffle(self.indexes) class TestDataGenerator(keras.utils.Sequence): def __init__(self, df, img_directory, x_col, y_col, preprocess_input, img_format='jpg', num_classes=10, batch_size=32, input_size=INPUT_SHAPE, normalize_pixels=False): """ Takes the dataframe and the path to the image directory and generates the batches of augmented data. :param df: Pandas dataframe containing filepaths relative to img_directory :param img_directory: path to directory to read images from :param batch_size: size of batch of data :param x_col: column name in the dataframe to read images from :param y_col: column name in the dataframe that has target data :param preprocess_input: Base CNN model's preprocessing input function :param input_size: dimension that image size get resized to when loaded """ self.normalize_pixels = normalize_pixels self.input_size = input_size self.img_directory = img_directory self.x_col, self.y_col = x_col, y_col self.batch_size = batch_size self.num_classes = num_classes self.model_preprocess_input = preprocess_input self.img_format = img_format # Filter dataframe for valid images only self.df = image_utils.filter_valid_images(df.copy(), img_directory, x_col, img_format) print_msg(f'Found {len(self.df)} valid image filenames belonging to {self.num_classes} classes.', 1) self.on_epoch_end() def __len__(self): return int(np.ceil(len(self.df) / self.batch_size)) # number of batches per epoch def __getitem__(self, index): """ The index passed into the function will be done by the fit function while training. Note : Take batch samples length not the batch size for initialization otherwise in the last epoch number of rows returned will be more than length of self.indexes and predict will fail in """ # Extract samples from df based on the index passed by fit method batch_indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size] # Reset index to not exceed the batch size batch_samples = self.df.iloc[batch_indexes].copy().reset_index(drop=True) # Initialization for faster processing x = np.empty((len(batch_samples), *self.input_size)) y = np.empty((len(batch_samples), self.num_classes)) # loop for the images in the sample and modify for i, row in batch_samples.iterrows(): # Load the image and resize img_path = os.path.join(self.img_directory, f'{row[self.x_col]}.{self.img_format}') img = image_utils.load_image(img_path, self.input_size, self.normalize_pixels) if img is not None: x[i] = img if self.y_col is not None: y[i] = normalize_ratings(row[self.y_col]) # apply base network's preprocessing on the 4D numpy array x = self.model_preprocess_input(x) # return the image and labels return x, y def on_epoch_end(self): """Will be called before and after each epoch""" self.indexes = np.arange(len(self.df)) # Create an index
50.287671
108
0.671071
1,052
7,342
4.507605
0.165399
0.034163
0.021932
0.013496
0.852805
0.852805
0.837621
0.837621
0.837621
0.837621
0
0.00293
0.256333
7,342
145
109
50.634483
0.865568
0.376328
0
0.684211
0
0
0.056384
0.016309
0
0
0
0
0
1
0.105263
false
0
0.078947
0.026316
0.263158
0.039474
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
3ac7851c48043839516e619b1db9986a143b8705
38
py
Python
s3shutil/__init__.py
18ijq3l793/s3shutil
bae21c349fc6add0e4cd39eecb621b0f5da34ed6
[ "MIT" ]
null
null
null
s3shutil/__init__.py
18ijq3l793/s3shutil
bae21c349fc6add0e4cd39eecb621b0f5da34ed6
[ "MIT" ]
null
null
null
s3shutil/__init__.py
18ijq3l793/s3shutil
bae21c349fc6add0e4cd39eecb621b0f5da34ed6
[ "MIT" ]
null
null
null
from s3shutil.s3shutil import copytree
38
38
0.894737
5
38
6.8
0.8
0
0
0
0
0
0
0
0
0
0
0.057143
0.078947
38
1
38
38
0.914286
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
3adda3581d6176782cc1893b4d7008c1cf60d8bc
9,934
py
Python
src/eduid_common/config/tests/test_etcd_parser.py
SUNET/eduid-common
d666aec7e47e6b0ccb575d621bb6e9f40bcea4e4
[ "BSD-3-Clause" ]
1
2016-04-14T13:45:10.000Z
2016-04-14T13:45:10.000Z
src/eduid_common/config/tests/test_etcd_parser.py
SUNET/eduid-common
d666aec7e47e6b0ccb575d621bb6e9f40bcea4e4
[ "BSD-3-Clause" ]
16
2017-03-10T11:47:59.000Z
2020-03-19T13:51:01.000Z
src/eduid_common/config/tests/test_etcd_parser.py
SUNET/eduid-common
d666aec7e47e6b0ccb575d621bb6e9f40bcea4e4
[ "BSD-3-Clause" ]
3
2016-11-21T11:39:49.000Z
2019-09-18T12:32:02.000Z
# -*- coding: utf-8 -*- from __future__ import absolute_import import unittest from mock import patch from nacl import encoding, secret from eduid_common.config.parsers import decorators from eduid_common.config.parsers.etcd import EtcdConfigParser from eduid_common.config.testing import EtcdTemporaryInstance __author__ = 'lundberg' class TestEtcdParser(unittest.TestCase): def setUp(self): self.etcd_instance = EtcdTemporaryInstance.get_instance(max_retry_seconds=20) self.ns = '/test/' # All these tests expect to start with an empty namespace self.etcd_instance.clear(self.ns) self.parser = EtcdConfigParser(namespace=self.ns, host=self.etcd_instance.host, port=self.etcd_instance.port) def test_write(self): config = { 'test': { 'my_bool': True, 'my_string': 'A value', 'my_list': ['One', 'Two', 3], 'my_dict': {'A': 'B'}, 'var_ignore_me': 'Do not mind me', } } self.parser.write_configuration(config) self.assertEqual(self.parser.get('my_bool'), True) self.assertEqual(self.parser.get('my_string'), 'A value') self.assertEqual(self.parser.get('my_list'), ['One', 'Two', 3]) self.assertEqual(self.parser.get('my_dict'), {'A': 'B'}) self.assertEqual(self.parser.get('var_ignore_me'), 'Do not mind me') def test_read(self): config = { 'test': { 'my_bool': True, 'my_string': 'A value', 'my_list': ['One', 'Two', 3], 'my_dict': {'A': 'B'}, 'var_ignore_me': 'Do not mind me', } } test_key = {'my_bool': True, 'my_string': 'A value', 'my_list': ['One', 'Two', 3], 'my_dict': {'A': 'B'}} self.parser.write_configuration(config) read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual(test_key, read_config) def test_read_uc(self): config = { 'test': {'MY_BOOL': True, 'MY_STRING': 'A value', 'MY_LIST': ['One', 'Two', 3], 'MY_DICT': {'A': 'B'}} } self.parser.write_configuration(config) read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual(config['test'], read_config) def test_set_get(self): self.parser.set('my_set_key', 'a nice value') self.assertEqual(self.parser.get('my_set_key'), 'a nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': 'a nice value'}, read_config) @patch('eduid_common.config.parsers.decorators.read_secret_key') def test_decrypt(self, mock_read_secret_key): mock_read_secret_key.return_value = bytes(b'A' * secret.SecretBox.KEY_SIZE) box = secret.SecretBox(decorators.read_secret_key('test')) secret_value = [ { 'key_name': 'test', 'value': bytes(box.encrypt(b'a nice value', encoder=encoding.URLSafeBase64Encoder)).decode('ascii'), } ] self.parser.set('my_set_key_encrypted', secret_value) self.parser.set('my_other_set_key', 'another nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({u'my_set_key': u'a nice value', u'my_other_set_key': u'another nice value'}, read_config) self.assertIsInstance(read_config['my_set_key'], str) @patch('eduid_common.config.parsers.decorators.read_secret_key') def test_decrypt_non_ascii(self, mock_read_secret_key): mock_read_secret_key.return_value = bytes(b'A' * secret.SecretBox.KEY_SIZE) box = secret.SecretBox(decorators.read_secret_key('test')) the_value = 'a nåjs väljö' the_value = bytes(the_value, 'utf-8') secret_value = [ { 'key_name': 'test', 'value': bytes(box.encrypt(the_value, encoder=encoding.URLSafeBase64Encoder)).decode('ascii'), } ] self.parser.set('my_set_key_encrypted', secret_value) self.parser.set('my_other_set_key', 'another nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({u'my_set_key': 'a nåjs väljö', u'my_other_set_key': 'another nice value'}, read_config) self.assertIsInstance(read_config['my_set_key'], str) @patch('eduid_common.config.parsers.decorators.read_secret_key') def test_decrypt_multi_key(self, mock_read_secret_key): mock_read_secret_key.return_value = bytes(b'A' * secret.SecretBox.KEY_SIZE) box = secret.SecretBox(decorators.read_secret_key('test')) box2 = secret.SecretBox(bytes(b'B' * secret.SecretBox.KEY_SIZE)) secret_value = [ { 'key_name': 'not_test', 'value': bytes(box2.encrypt(b'a nice value', encoder=encoding.URLSafeBase64Encoder)).decode('ascii'), }, { 'key_name': 'test', 'value': bytes(box.encrypt(b'a nice value', encoder=encoding.URLSafeBase64Encoder)).decode('ascii'), }, ] self.parser.set('MY_SET_KEY_encrypted', secret_value) self.parser.set('MY_OTHER_SET_KEY', 'another nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'MY_SET_KEY': 'a nice value', 'MY_OTHER_SET_KEY': 'another nice value'}, read_config) def test_interpolate(self): self.parser.set('my_set_key', '${my_value}') self.parser.set('my_value', 'a nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': 'a nice value', 'my_value': 'a nice value'}, read_config) def test_interpolate_upper(self): self.parser.set('my_set_key', '${MY_VALUE}') self.parser.set('my_value', 'a nice value') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': 'a nice value', 'my_value': 'a nice value'}, read_config) def test_interpolate_variable_key(self): self.parser.set('my_set_key', '${var_my_value}') self.parser.set('var_my_value', 'a nice value') self.assertEqual('a nice value', self.parser.get('var_my_value')) read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': 'a nice value'}, read_config) def test_interpolate_variable_key_upper(self): self.parser.set('my_set_key', '${VAR_MY_VALUE}') self.parser.set('var_my_value', 'a nice value') self.assertEqual('a nice value', self.parser.get('var_my_value')) read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': 'a nice value'}, read_config) def test_interpolate_missing_key(self): self.parser.set('my_set_key', '${my_value}') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': '${my_value}'}, read_config) def test_interpolate_missing_key_upper(self): self.parser.set('my_set_key', '${MY_VALUE}') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual({'my_set_key': '${MY_VALUE}'}, read_config) def test_interpolate_complex_dict(self): self.parser.set('my_set_key', '${my_value}') self.parser.set('my_value', 'a nice value') self.parser.set('a_list', ['test', '${my_value}', {'a_dict_in_a_list': '${my_value}'}]) self.parser.set( 'another_dict', {'string_in_sub_dict': '${my_value}', 'a_dict_in_a_dict': {'another_key': '${my_value}'}} ) read_config = self.parser.read_configuration(self.parser.ns) expected = { 'my_set_key': 'a nice value', 'my_value': 'a nice value', 'a_list': ['test', 'a nice value', {'a_dict_in_a_list': 'a nice value'},], 'another_dict': {'string_in_sub_dict': 'a nice value', 'a_dict_in_a_dict': {'another_key': 'a nice value'}}, } self.assertEqual(expected, read_config) def test_interpolate_complex_dict_upper(self): self.parser.set('my_set_key', '${MY_VALUE}') self.parser.set('my_value', 'a nice value') self.parser.set('a_list', ['test', '${MY_VALUE}', {'a_dict_in_a_list': '${MY_VALUE}'}]) self.parser.set( 'another_dict', {'string_in_sub_dict': '${MY_VALUE}', 'a_dict_in_a_dict': {'another_key': '${MY_VALUE}'}} ) read_config = self.parser.read_configuration(self.parser.ns) expected = { 'my_set_key': 'a nice value', 'my_value': 'a nice value', 'a_list': ['test', 'a nice value', {'a_dict_in_a_list': 'a nice value'},], 'another_dict': {'string_in_sub_dict': 'a nice value', 'a_dict_in_a_dict': {'another_key': 'a nice value'}}, } self.assertEqual(expected, read_config) @patch('eduid_common.config.parsers.decorators.read_secret_key') def test_decrypt_interpolate(self, mock_read_secret_key): mock_read_secret_key.return_value = bytes(b'A' * secret.SecretBox.KEY_SIZE) box = secret.SecretBox(decorators.read_secret_key('test')) secret_value = [ { 'key_name': 'test', 'value': bytes(box.encrypt(b'a secret value', encoder=encoding.URLSafeBase64Encoder)).decode('ascii'), } ] self.parser.set('my_secret_encrypted', secret_value) self.parser.set('my_other_set_key', '${my_secret} is set here') read_config = self.parser.read_configuration(self.parser.ns) self.assertEqual( {u'my_secret': u'a secret value', u'my_other_set_key': u'a secret value is set here'}, read_config )
40.546939
120
0.628951
1,302
9,934
4.50384
0.086022
0.117667
0.057981
0.053718
0.859141
0.831173
0.814973
0.778649
0.774386
0.75955
0
0.002733
0.226596
9,934
244
121
40.713115
0.76051
0.007751
0
0.513661
0
0
0.24518
0.02192
0
0
0
0
0.136612
1
0.092896
false
0
0.038251
0
0.136612
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
3aea0c58ce5d9751de8059460a90685c6ce119f5
6
py
Python
python/ql/test/library-tests/PointsTo/new/code/package/module2.py
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
8,844
2019-05-31T15:47:12.000Z
2022-03-31T18:33:51.000Z
python/ql/test/library-tests/PointsTo/new/code/package/module2.py
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
2,970
2020-04-28T17:24:18.000Z
2022-03-31T22:40:46.000Z
python/ql/test/library-tests/PointsTo/new/code/package/module2.py
ScriptBox99/github-codeql
2ecf0d3264db8fb4904b2056964da469372a235c
[ "MIT" ]
794
2020-04-29T00:28:25.000Z
2022-03-30T08:21:46.000Z
x = 0
3
5
0.333333
2
6
1
1
0
0
0
0
0
0
0
0
0
0
0.333333
0.5
6
1
6
6
0.333333
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
1
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
aaf89eaa60bcde710dfb2028808ef8c41fad3d5b
37
py
Python
2017-04-06 - Pythonic Code Through 5 Examples/0_lightning_refersher/other.py
skolbin-ssi/WintellectWebinars
63612580c7c2f7d0c6dca930abba5696b2f40286
[ "Apache-2.0" ]
8
2019-01-24T19:22:29.000Z
2019-06-11T17:00:56.000Z
2017-04-06 - Pythonic Code Through 5 Examples/0_lightning_refersher/other.py
skolbin-ssi/WintellectWebinars
63612580c7c2f7d0c6dca930abba5696b2f40286
[ "Apache-2.0" ]
28
2021-03-10T08:24:07.000Z
2022-03-02T07:26:39.000Z
2017-04-06 - Pythonic Code Through 5 Examples/0_lightning_refersher/other.py
skolbin-ssi/WintellectWebinars
63612580c7c2f7d0c6dca930abba5696b2f40286
[ "Apache-2.0" ]
2
2018-01-23T11:24:44.000Z
2019-06-06T18:27:32.000Z
import game print(game.get_guess())
9.25
23
0.756757
6
37
4.5
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.108108
37
4
23
9.25
0.818182
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0.5
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
1
0
1
0
0
1
0
6
c915c0c1738f34da8f2b7f0b68b6945f836b2a8e
45
py
Python
record_kit/__init__.py
actcwlf/record-kit
6e204790f630991a9065effa333fa99af3a5c130
[ "MIT" ]
null
null
null
record_kit/__init__.py
actcwlf/record-kit
6e204790f630991a9065effa333fa99af3a5c130
[ "MIT" ]
null
null
null
record_kit/__init__.py
actcwlf/record-kit
6e204790f630991a9065effa333fa99af3a5c130
[ "MIT" ]
null
null
null
from .recorder import * from .parser import *
22.5
23
0.755556
6
45
5.666667
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.155556
45
2
24
22.5
0.894737
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
c9193f8b0462f9aa0b2bf050ad3ca60760a47738
29
py
Python
exercicios/lista1/exercicio2.py
lagcrs/algoritmos
5ee860c71db8ac2ef8bbe6cc87726938b1ca9c72
[ "Apache-2.0" ]
null
null
null
exercicios/lista1/exercicio2.py
lagcrs/algoritmos
5ee860c71db8ac2ef8bbe6cc87726938b1ca9c72
[ "Apache-2.0" ]
null
null
null
exercicios/lista1/exercicio2.py
lagcrs/algoritmos
5ee860c71db8ac2ef8bbe6cc87726938b1ca9c72
[ "Apache-2.0" ]
null
null
null
print('Meu nome e Larissa')
14.5
27
0.689655
5
29
4
1
0
0
0
0
0
0
0
0
0
0
0
0.172414
29
2
27
14.5
0.833333
0
0
0
0
0
0.642857
0
0
0
0
0
0
1
0
true
0
0
0
0
1
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
1
0
null
0
0
0
0
0
0
1
0
0
0
0
1
0
6
c954bc72ad92bc4c5bb2ff34535a99d3c57101a9
231
py
Python
UNP/__init__.py
lizard1998myx/UNP
4b6c77f081863bee654d38e9e938e8e7c581593e
[ "Apache-2.0" ]
null
null
null
UNP/__init__.py
lizard1998myx/UNP
4b6c77f081863bee654d38e9e938e8e7c581593e
[ "Apache-2.0" ]
null
null
null
UNP/__init__.py
lizard1998myx/UNP
4b6c77f081863bee654d38e9e938e8e7c581593e
[ "Apache-2.0" ]
null
null
null
from UNP.Interface import Interface from UNP.Application import Loginer def activate(): Interface().keyboard() def activate_shortcut(): Loginer().active() def activate_passive(): Loginer().passive()
15.4
36
0.675325
24
231
6.416667
0.5
0.214286
0
0
0
0
0
0
0
0
0
0
0.212121
231
14
37
16.5
0.846154
0
0
0
0
0
0
0
0
0
0
0
0
1
0.375
true
0.25
0.25
0
0.625
0
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
1
1
0
0
1
0
0
6
c9813d58a4d5780a09abf3a8bf110713740b228b
173,442
py
Python
src/ea/sutadapters/GUI/selenium_rc.py
ExtensiveAutomation/extensiveautomation-plugin-gui
390d29d8c3e96dc817173358a8161767451dba97
[ "MIT" ]
null
null
null
src/ea/sutadapters/GUI/selenium_rc.py
ExtensiveAutomation/extensiveautomation-plugin-gui
390d29d8c3e96dc817173358a8161767451dba97
[ "MIT" ]
null
null
null
src/ea/sutadapters/GUI/selenium_rc.py
ExtensiveAutomation/extensiveautomation-plugin-gui
390d29d8c3e96dc817173358a8161767451dba97
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding=utf-8 -*- # ------------------------------------------------------------------- # MIT License # # Copyright (c) 2010-2021 Denis MACHARD # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ------------------------------------------------------------------- import sys import base64 import threading import time from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.remote.errorhandler import ErrorHandler from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException from selenium import webdriver # unicode = str with python3 if sys.version_info > (3,): unicode = str try: xrange except NameError: # support python3 xrange = range from ea.testexecutorlib import TestValidatorsLib as TestValidators from ea.testexecutorlib import TestTemplatesLib as TestTemplates from ea.testexecutorlib import TestOperatorsLib as TestOperators from ea.testexecutorlib import TestAdapterLib as TestAdapterLib from ea.testexecutorlib import TestExecutorLib as TestExecutor from ea.sutadapters.GUI import templates __NAME__="""Selenium""" ACTION_SCREENSHOT = "SCREENSHOT" ACTION_OK = "OK" ACTION_FAILED = "FAILED" ACTION_TIMEOUT = "TIMEOUT" SELENIUM_FIREFOX = DesiredCapabilities.FIREFOX SELENIUM_INTERNETEXPLORER = DesiredCapabilities.INTERNETEXPLORER SELENIUM_CHROME = DesiredCapabilities.CHROME SELENIUM_OPERA = DesiredCapabilities.OPERA SELENIUM_EDGE= DesiredCapabilities.EDGE SELENIUM_KEY_NULL = Keys.NULL SELENIUM_KEY_CANCEL = Keys.CANCEL SELENIUM_KEY_HELP = Keys.HELP SELENIUM_KEY_BACKSPACE = Keys.BACKSPACE SELENIUM_KEY_TAB = Keys.TAB SELENIUM_KEY_CLEAR = Keys.CLEAR SELENIUM_KEY_RETURN = Keys.RETURN SELENIUM_KEY_ENTER = Keys.ENTER SELENIUM_KEY_SHIFT = Keys.SHIFT SELENIUM_KEY_CONTROL = Keys.CONTROL SELENIUM_KEY_ALT = Keys.ALT SELENIUM_KEY_PAUSE = Keys.PAUSE SELENIUM_KEY_ESCAPE = Keys.ESCAPE SELENIUM_KEY_SPACE = Keys.SPACE SELENIUM_KEY_PAGE_UP = Keys.PAGE_UP SELENIUM_KEY_PAGE_DOWN = Keys.PAGE_DOWN SELENIUM_KEY_END = Keys.END SELENIUM_KEY_HOME = Keys.HOME SELENIUM_KEY_LEFT = Keys.LEFT SELENIUM_KEY_UP = Keys.UP SELENIUM_KEY_RIGHT = Keys.RIGHT SELENIUM_KEY_DOWN = Keys.DOWN ISELENIUM_KEY_INSERT = Keys.INSERT SELENIUM_KEY_DELETE = Keys.DELETE SELENIUM_KEY_SEMICOLON = Keys.SEMICOLON SELENIUM_KEY_EQUALS = Keys.EQUALS SELENIUM_KEY_NUMPAD0 = Keys.NUMPAD0 SELENIUM_KEY_NUMPAD1 = Keys.NUMPAD1 SELENIUM_KEY_NUMPAD2 = Keys.NUMPAD2 SELENIUM_KEY_NUMPAD3 = Keys.NUMPAD3 SELENIUM_KEY_NUMPAD4 = Keys.NUMPAD4 SELENIUM_KEY_NUMPAD5 = Keys.NUMPAD5 SELENIUM_KEY_NUMPAD6 = Keys.NUMPAD6 SELENIUM_KEY_NUMPAD7 = Keys.NUMPAD7 SELENIUM_KEY_NUMPAD8 = Keys.NUMPAD8 SELENIUM_KEY_NUMPAD9 = Keys.NUMPAD9 SELENIUM_KEY_MULTIPLY = Keys.MULTIPLY SELENIUM_KEY_ADD = Keys.ADD SELENIUM_KEY_SEPARATOR = Keys.SEPARATOR SELENIUM_KEY_SUBTRACT = Keys.SUBTRACT SELENIUM_KEY_DECIMAL = Keys.DECIMAL SELENIUM_KEY_DIVIDE = Keys.DIVIDE SELENIUM_KEY_F1 = Keys.F1 SELENIUM_KEY_F2 = Keys.F2 SELENIUM_KEY_F3 = Keys.F3 SELENIUM_KEY_F4 = Keys.F4 SELENIUM_KEY_F5 = Keys.F5 SELENIUM_KEY_F6 = Keys.F6 SELENIUM_KEY_F7 = Keys.F7 SELENIUM_KEY_F8 = Keys.F8 SELENIUM_KEY_F9 = Keys.F9 SELENIUM_KEY_F10 = Keys.F10 SELENIUM_KEY_F11 = Keys.F11 SELENIUM_KEY_F12 = Keys.F12 SELENIUM_KEY_META = Keys.META SELENIUM_KEY_COMMAND = Keys.COMMAND AGENT_INITIALIZED = "AGENT_INITIALIZED" AGENT_TYPE_EXPECTED='seleniumserver' class NotReady(Exception): pass class Selenium(TestAdapterLib.Adapter): def __init__(self, parent, agent, name=None, debug=False, verbose=True, shared=False, navigId=None, waitUntil=True): """ Selenium adapter @param parent: parent testcase @type parent: testcase @param agent: agent to use, selenium type expected @type agent: string @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param navigId: navigator id (default=None) @type navigId: string/none @param waitUntil: use the wait until mode (default=True) @type waitUntil: boolean @param debug: active debug mode (default=False) @type debug: boolean @param verbose: False to disable verbose mode (default=True) @type verbose: boolean @param shared: shared adapter (default=False) @type shared: boolean """ if isinstance(agent, str): agent = {"name": agent, "type": AGENT_TYPE_EXPECTED } TestAdapterLib.Adapter.__init__(self, name = __NAME__, parent = parent, debug=debug, realname=name, shared=shared, showEvts=verbose, showSentEvts=verbose, showRecvEvts=verbose, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.parent = parent self.cfg = {} self.cfg['agent-support'] = True self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.cfg['wait-until'] = waitUntil self.TIMER_ALIVE_AGT = TestAdapterLib.Timer(parent=self, duration=20, name="keepalive-agent", callback=self.aliveAgent, logEvent=False, enabled=True) self.__checkConfig() self.cmdId = 0 self.isStarted = False self.__mutexCmdId__ = threading.RLock() self.capabilities = {} self.navigId = navigId self.errorHandler = ErrorHandler() # load navig id from storage self.sessionName = None self.navigId = TestExecutor.Cache().get(name="%s-navig-id-default" % AGENT_TYPE_EXPECTED ) # initialize the agent with no data self.prepareAgent(data={'shared': shared}) if self.agentIsReady(timeout=30) is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "agent response timeout" ) self.TIMER_ALIVE_AGT.start() def __checkConfig(self): """ Private function """ self.debug("config: %s" % self.cfg) self.warning('using agent %s' % self.cfg['agent']['name']) def onReset(self): """ Called automaticly on reset adapter """ # stop timer self.TIMER_ALIVE_AGT.stop() # cleanup remote agent self.resetAgent() def receivedNotifyFromAgent(self, data): """ Function to reimplement """ self.debug( "response: %s" % data) if 'cmd' in data: if data['cmd'] == AGENT_INITIALIZED: tpl = TestTemplates.TemplateMessage() layer = TestTemplates.TemplateLayer('AGENT') layer.addKey("ready", True) layer.addKey(name='name', data=self.cfg['agent']['name'] ) layer.addKey(name='type', data=self.cfg['agent']['type'] ) tpl.addLayer(layer= layer) self.logRecvEvent( shortEvt = "Agent Is Ready" , tplEvt = tpl ) else: try: commandId = data['command-id'] commandName = data['command-name'] commandValue = data['command-value'] response = self.parseResponse(commandValue) responseResult = ACTION_FAILED responseState = None layerValue = TestTemplates.TemplateLayer(name='') if 'state' in response: layerValue.addKey(name='state', data="%s" % response ['state'] ) if 'status' in response: if response['status'] == 0: responseResult = ACTION_OK # timeout if response['status'] == 1000: responseResult = ACTION_TIMEOUT tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) return # error if response['status'] != 0: layerValue.addKey(name='value', data="%s" % response['value'] ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) tpl.addRaw("%s" % response['value']) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) return if response['value'] is not None: if isinstance(response["value"], dict): if 'state' in response['value']: responseState = response['value']['state'] if commandName == Command.NEW_SESSION: if 'sessionId' not in response: self.error("error on selenium agent: %s" % response['value']) else: # save the session id in the cache self.navigId = response['sessionId'] TestExecutor.Cache().set(name="%s-navig-id-%s" % (AGENT_TYPE_EXPECTED, self.sessionName ), data=self.navigId) self.capabilities = response['value'] self.debug("capabilities: %s" % self.capabilities) self.isStarted = True layerValue.addKey(name='navig-id', data="%s" % self.navigId ) capsTpl= TestTemplates.TemplateLayer(name='') capsTpl.addMore(self.capabilities) layerValue.addKey(name='capabilities', data=capsTpl ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.SCREENSHOT: screenshot = base64.b64decode(response['value'].encode('ascii')) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult , img=screenshot, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.GET_ELEMENT_SIZE: if 'height' in response['value']: layerValue.addKey(name='height', data=response['value'] ['height'] ) if 'width' in response['value']: layerValue.addKey(name='width', data=response['value'] ['width'] ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState ) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.GET_ELEMENT_LOCATION: if 'x' in response['value']: layerValue.addKey(name='x', data=response['value'] ['x'] ) if 'y' in response['value']: layerValue.addKey(name='y', data=response['value'] ['y'] ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState ) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.FIND_ELEMENT: if 'ELEMENT' in response['value']: layerValue.addKey(name='element-id', data=response['value'] ['ELEMENT'] ) if 'element-6066-11e4-a52e-4f735466cecf' in response['value']: layerValue.addKey(name='element-id', data=response['value'] ['element-6066-11e4-a52e-4f735466cecf'] ) if 'screen' in response['value']: screenshot = base64.b64decode(response['value'] ['screen'].encode('ascii')) layerValue.addKey(name='screenshot', data=screenshot) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState ) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.QUIT: self.isStarted = False tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, state=responseState ) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.GET_ELEMENT_TEXT: layerValue.addKey(name='value', data= response['value'].encode('utf8') ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) elif commandName == Command.GET_WINDOW_HANDLES: layerHandles = TestTemplates.TemplateLayer(name='') for i in xrange(len(response ['value'] )): layerHandles.addKey(name='%s' % i, data="%s" % response ['value'] [i]) layerValue.addKey(name='handles', data=layerHandles) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) else: layerValue.addKey(name='value', data="%s" % response['value'] ) tpl = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=responseResult, value=layerValue, state=responseState) ) self.logRecvEvent( shortEvt = "%s [result=%s]" % (commandName, responseResult), tplEvt = tpl ) except Exception as e: self.error('received notify: %s' % e) def receivedErrorFromAgent(self, data): """ Function to reimplement """ self.debug( data ) self.error( data ) def receivedDataFromAgent(self, data): """ Function to reimplement """ self.debug( 'data received from agent' ) # log event tpl = self.encapsule( layer_gui=templates.gui( action=data['command-name'], actionId=data['command-id'], description=ACTION_SCREENSHOT, length=str(len(data['data'])), img=data['data'] ) ) tpl.addRaw( data['data'] ) self.logRecvEvent( shortEvt = ACTION_SCREENSHOT, tplEvt = tpl ) def sendNotifyToAgent(self, data): """ Send notify to agent """ self.parent.sendNotifyToAgent(adapterId=self.getAdapterId(), agentName=self.cfg['agent-name'], agentData=data) def prepareAgent(self, data): """ prepare agent """ self.parent.sendReadyToAgent(adapterId=self.getAdapterId(), agentName=self.cfg['agent-name'], agentData=data) def initAgent(self, data): """ Init agent """ self.parent.sendInitToAgent(adapterId=self.getAdapterId(), agentName=self.cfg['agent-name'], agentData=data) def resetAgent(self): """ Reset agent """ self.parent.sendResetToAgent(adapterId=self.getAdapterId(), agentName=self.cfg['agent-name'], agentData='') def aliveAgent(self): """ Keep alive agent """ self.parent.sendAliveToAgent(adapterId=self.getAdapterId(), agentName=self.cfg['agent-name'], agentData='') self.TIMER_ALIVE_AGT.restart() def getCommandId(self): """ """ self.__mutexCmdId__.acquire() self.cmdId += 1 ret = self.cmdId self.__mutexCmdId__.release() return ret def encapsule(self, layer_gui): """ Encapsule layer in template message """ layer_agent= TestTemplates.TemplateLayer('AGENT') layer_agent.addKey(name='name', data=self.cfg['agent']['name'] ) layer_agent.addKey(name='type', data=self.cfg['agent']['type'] ) tpl = TestTemplates.TemplateMessage() tpl.addLayer(layer=layer_agent) tpl.addLayer(layer=layer_gui) return tpl def parseResponse(self, response): """ Parse response """ if response: return response return {'success': 0, 'value': None, 'sessionId': self.navigId} def _wrap_value(self, value): """ Wrap value """ if isinstance(value, dict): converted = {} for key, val in value.items(): converted[key] = self._wrap_value(val) return converted elif isinstance(value, WebElement): return {'ELEMENT': value.id} elif isinstance(value, list): return list(self._wrap_value(item) for item in value) else: return value def create_web_element(self, element_id): """ Creates a web element with the specified element_id. """ return WebElement(self, element_id) def _unwrap_value(self, value): """ Unwrap value """ if isinstance(value, dict) and 'ELEMENT' in value: return self.create_web_element(value['ELEMENT']) elif isinstance(value, list): return list(self._unwrap_value(item) for item in value) else: return value def prepareParams(self, params=None): """ Prepare parameters """ if self.navigId is not None: if not params: params = {'sessionId': self.navigId} elif 'sessionId' not in params: params['sessionId'] = self.navigId params = self._wrap_value(params) return params def executeCommand(self, command, params=None, more={}): """ """ if command != Command.NEW_SESSION and self.navigId is None: #raise NotReady("No nagivation id defined!") raise TestAdapterLib.AdapterException(TestAdapterLib.caller(), "No nagivation id defined!" ) # prepare agent request cmdId = self.getCommandId() agentData = { 'command-id': cmdId, 'command-name': command } agentData['command-params'] = self.prepareParams(params=params) agentData['command-capabilities'] = self.capabilities # add additionnal keys agentData.update(more) # send command to agent self.debug( "request: %s" % agentData) self.sendNotifyToAgent(data=agentData) # log event layerParams = TestTemplates.TemplateLayer(name='') for k,v in agentData['command-params'].items(): layerParams.addKey("%s" % k, "%s" % v) tpl = self.encapsule(layer_gui=templates.gui(action=command, actionId=cmdId, parameters=layerParams)) self.logSentEvent( shortEvt = command, tplEvt = tpl ) return cmdId def setNavigId(self, navigId): """ Set navigation Id manually @param navigId: navagator id @type navigId: string """ self.navigId = navigId def agentIsReady(self, timeout=1.0): """ Waits to receive "agent ready" event until the end of the timeout @param timeout: time max to wait to receive event in second (default=1s) @type timeout: float @return: an event matching with the template or None otherwise @rtype: templatemessage """ tpl = TestTemplates.TemplateMessage() layer = TestTemplates.TemplateLayer('AGENT') layer.addKey("ready", True) layer.addKey(name='name', data=self.cfg['agent']['name'] ) layer.addKey(name='type', data=self.cfg['agent']['type'] ) tpl.addLayer(layer= layer) evt = self.received( expected = tpl, timeout = timeout ) return evt # do functions def doSwitchToSession(self, sessionName): """ Switch to the session according to the name provided @param sessionName: session name @type sessionName: string """ self.navigId = TestExecutor.Cache().get(name="%s-navig-id-%s" % (AGENT_TYPE_EXPECTED, sessionName) ) if self.navigId is None: raise Exception("the session (%s) does not exists!" % sessionName ) return True def doOpen(self, targetUrl, timeout=30.0, withFirefox=True, withIe=False, withChrome=False, withOpera=False, withEdge=False, useMarionette=True, browserProfile=None, sessionName="default" ): """ Open firefox and load url passed as argument @param targetUrl: url to load @type targetUrl: string @param timeout: time max to wait to open the browser and load url in second (default=30s) @type timeout: float @param withFirefox: open firefox (default=True) @type withFirefox: boolean @param withIe: open internet explorer (default=False) @type withIe: boolean @param withChrome: open chrome (default=False) @type withChrome: boolean @param withOpera: open opera (default=False) @type withOpera: boolean @param withEdge: open edge (default=False) @type withEdge: boolean @param useMarionette: use marionette for gecko support (default=True) @type useMarionette: boolean @param browserProfile: browser profile (default=None) @type browserProfile: none/object @param sessionName: session name (default=default) @type sessionName: string @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if withFirefox: cap = SELENIUM_FIREFOX cap['marionette'] = useMarionette cap['acceptInsecureCerts'] = True elif withIe: cap = SELENIUM_INTERNETEXPLORER elif withChrome: cap = SELENIUM_CHROME elif withOpera: cap = SELENIUM_OPERA elif withEdge: cap = SELENIUM_EDGE else: cap = SELENIUM_FIREFOX cmdId = self.openNavig( desiredCapabilities=cap, browserProfile=browserProfile, sessionName=sessionName) if self.isNavigStarted(timeout=timeout, commandId=cmdId) is None: ret = False else: if not( targetUrl.startswith("http://") or targetUrl.startswith("https://") ): raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "target url not start with http(s):// (%s)" % type(targetUrl) ) cmdId = self.loadUrl(url=targetUrl) if self.isUrlLoaded(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doClose(self, timeout=30.0): """ Close the browser @param timeout: time max to wait to close window in second (default=30s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.quitNavig() if self.isNavigStopped(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doCloseWindow(self, timeout=30.0): """ Close the current window @param timeout: time max to wait to close window in second (default=30s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.closeWindow() if self.isWindowClosed(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doSwitchToWindow(self, windowName, timeout=30.0): """ Switch to the provided window @param windowName: windows name @type windowName: string @param timeout: time max to wait to close window in second (default=30s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getAllWindowHandles() rsp = self.hasWindowHandles(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') listHandles = elementVall.get('handles').getItems() matched = False for (i,h) in listHandles: cmdId = self.switchToWindow( windowName=h ) rsp = self.isWindowsSwitched(timeout=timeout, commandId=cmdId) if rsp is None: ret = False; break; cmdId = self.getTitle( ) rsp = self.hasWindowTitle(timeout=timeout, commandId=cmdId) if rsp is None: ret = False; break; elementVall = rsp.get('GUI', 'value') title = elementVall.get('value') while not len(title): time.sleep(0.5) cmdId = self.getTitle( ) rsp = self.hasWindowTitle(timeout=timeout, commandId=cmdId) if rsp is None: ret = False; break; elementVall = rsp.get('GUI', 'value') title = elementVall.get('value') if windowName in title: matched = True break if not matched: ret = False return ret def doGetPageTitle(self, timeout=10.0): """ Return the title of the current page @param timeout: time max to wait to get page title in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getTitle() rsp = self.hasWindowTitle(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') ret = elementVall.get('value') # title of the window return ret def doFindTextPageTitle(self, expectedText, timeout=10.0): """ Find the text provided as argument in the title of the current page @param expectedText: text to find @type expectedText: string/operators @param timeout: time max to wait to get page title in second (default=10s) @type timeout: float @return: True if text found, False otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getTitle() rsp = self.hasWindowTitle(timeout=timeout, commandId=cmdId, expectedText=expectedText) if rsp is None: ret = False return ret def doGetPageUrl(self, timeout=10.0): """ Return the url of the current page @param timeout: time max to wait to get page url in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getUrl() rsp = self.hasUrl(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') ret = elementVall.get('value') # url of the window return ret def doFindTextPageUrl(self, expectedText, timeout=10.0): """ Find the text provided as argument in the url of the current page @param expectedText: text to find @type expectedText: string/operators @param timeout: time max to wait to get page url in second (default=10s) @type timeout: float @return: True if text found, False otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getUrl() rsp = self.hasUrl(timeout=timeout, commandId=cmdId, expectedText=expectedText) if rsp is None: ret = False return True def doGetPageSource(self, timeout=10.0): """ Return the code source of the current page @param timeout: time max to wait to get source code in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getPageSource() rsp = self.hasSource(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') ret = elementVall.get('value') # code source of the window return ret def doFindTextPageSource(self, expectedText, timeout=10.0): """ Find the text provided as argument in the code source of the current page @param expectedText: text to find @type expectedText: string/operators @param timeout: time max to wait to get source code in second (default=10s) @type timeout: float @return: True if text found, False otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getPageSource() rsp = self.hasSource(timeout=timeout, commandId=cmdId, expectedText=expectedText) if rsp is None: ret = False return True def doWaitElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Wait element until the end of the timeout @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout} if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location, more=more) rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret def doWaitVisibleElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Wait element to be visible until the end of the timeout @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout} if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location, more=more) rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout, "wait-until-value": True} cmdId = self.displayedElement(elementId=elementId, more= more) rsp = self.isElementDisplayed(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret def doWaitNotVisibleElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Wait element to be not visible until the end of the timeout @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout} if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location, more=more) rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout, "wait-until-value": False} cmdId = self.displayedElement(elementId=elementId, more= more) rsp = self.isElementDisplayed(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret def doWaitClickElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Wait element until the end of the timeout and click on it @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout} if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location, more=more) rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.clickElement(elementId=elementId) if self.isElementClicked(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doWaitVisibleClickElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Wait element to be visible until the end of the timeout and click on it @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout} if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret # locate the element cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location, more=more) rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') if elementId is None: self.error("element id is missing in response") # checking if visible more = {} if self.cfg['wait-until']: more = {"wait-until": True, "wait-until-timeout": timeout, "wait-until-value": True} cmdId = self.displayedElement(elementId=elementId, more= more) rsp = self.isElementDisplayed(timeout=timeout+10, commandId=cmdId) if rsp is None: ret = False return ret # finally click on it cmdId = self.clickElement(elementId=elementId) if self.isElementClicked(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doGetText(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Get the text of the element @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to get the text of the element in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.getTextElement(elementId=elementId) rsp = self.hasTextElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') ret = elementVall.get('value') return ret def doFindText(self, expectedText, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Find the text provided as argument in the element @param expectedText: text to find @type expectedText: string/operators @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to get the text of the element in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) if expectedText is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "expectedText argument cannot be equal to none" ) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.getTextElement(elementId=elementId) rsp = self.hasTextElement(timeout=timeout, commandId=cmdId, expectedText=expectedText) if rsp is None: ret = False return True return ret def doClickElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Click on element @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to click on element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.clickElement(elementId=elementId) if self.isElementClicked(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doDoubleClickElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Double Click on element @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to click on element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.hoverElement(elementId=elementId) if self.hasMouseMoved(timeout=timeout, commandId=cmdId) is None: ret = False else: cmdId = self.doubleClick() if self.isDoubleClicked(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doRightClickElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Right Click on element @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to click on element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.hoverElement(elementId=elementId) if self.hasMouseMoved(timeout=timeout, commandId=cmdId) is None: ret = False else: cmdId = self.rightClick() if self.isClicked(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doHoverElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Hover mouse on element @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to hover on element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.hoverElement(elementId=elementId) if self.hasMouseMoved(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doTypeText(self, text, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Find element and type text on it @param text: text to type @type text: string @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to type text in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) if text is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "text argument cannot be equal to none" ) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.typeTextElement(elementId=elementId, text=str(text) ) if self.hasTextEntered(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doCheckLocationElement(self, x, y, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Check the location of the element @param x: x position @type x: integer @param y: y position @type y: integer @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to type text in second (default=10s) @type timeout: float @return: True if the size if OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) if x is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "x argument cannot be equal to none") if y is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "y argument cannot be equal to none" ) ret = False if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.locationElement(elementId=elementId) rsp2 = self.isElementLocation(timeout=timeout, commandId=cmdId) if rsp2 is None: ret = False else: elementVall = rsp2.get('GUI', 'value') elementX = elementVall.get('x') elementY = elementVall.get('y') if int(x) == int(elementX) and int(y) == int(elementY): ret = True return ret def doCheckSizeElement(self, width, height, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Check the size of the element @param width: width element @type width: integer @param height: heigth element @type height: integer @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to type text in second (default=10s) @type timeout: float @return: True if the size if OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) if width is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "width argument cannot be equal to none" ) if height is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "height argument cannot be equal to none" ) ret = False if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.sizeElement(elementId=elementId) rsp2 = self.isElementSize(timeout=timeout, commandId=cmdId) if rsp2 is None: ret = False else: elementVall = rsp2.get('GUI', 'value') elementWidth = elementVall.get('width') elementHeight = elementVall.get('height') if int(width) == int(elementWidth) and int(height) == int(elementHeight): ret = True return ret def doTypeKey(self, key, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None, repeat=0): """ Find element and type a key on it @param key: SutAdapters.GUI.SELENIUM_KEY_NULL | SutAdapters.GUI.SELENIUM_KEY_CANCEL | SutAdapters.GUI.SELENIUM_KEY_HELP | SutAdapters.GUI.SELENIUM_KEY_BACKSPACE | SutAdapters.GUI.SELENIUM_KEY_TAB | SutAdapters.GUI.SELENIUM_KEY_CLEAR | SutAdapters.GUI.SELENIUM_KEY_RETURN | SutAdapters.GUI.SELENIUM_KEY_ENTER | SutAdapters.GUI.SELENIUM_KEY_SHIFT | SutAdapters.GUI.SELENIUM_KEY_CONTROL | SutAdapters.GUI.SELENIUM_KEY_ALT | SutAdapters.GUI.SELENIUM_KEY_PAUSE | SutAdapters.GUI.SELENIUM_KEY_ESCAPE | SutAdapters.GUI.SELENIUM_KEY_SPACE | SutAdapters.GUI.SELENIUM_KEY_PAGE_UP | SutAdapters.GUI.SELENIUM_KEY_PAGE_DOWN | SutAdapters.GUI.SELENIUM_KEY_END | SutAdapters.GUI.SELENIUM_KEY_HOME | SutAdapters.GUI.SELENIUM_KEY_LEFT | SutAdapters.GUI.SELENIUM_KEY_UP | SutAdapters.GUI.SELENIUM_KEY_RIGHT | SutAdapters.GUI.SELENIUM_KEY_DOWN | SutAdapters.GUI.SELENIUM_KEY_INSERT | SutAdapters.GUI.SELENIUM_KEY_DELETE | SutAdapters.GUI.SELENIUM_KEY_SEMICOLON | SutAdapters.GUI.SELENIUM_KEY_EQUALS | SutAdapters.GUI.SELENIUM_KEY_NUMPAD0 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD1 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD2 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD3 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD4 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD5 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD6 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD7 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD8 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD9 | SutAdapters.GUI.SELENIUM_KEY_MULTIPLY | SutAdapters.GUI.SELENIUM_KEY_ADD | SutAdapters.GUI.SELENIUM_KEY_SEPARATOR | SutAdapters.GUI.SELENIUM_KEY_SUBTRACT | SutAdapters.GUI.SELENIUM_KEY_DECIMAL | SutAdapters.GUI.SELENIUM_KEY_DIVIDE | SutAdapters.GUI.SELENIUM_KEY_F1 | SutAdapters.GUI.SELENIUM_KEY_F2 | SutAdapters.GUI.SELENIUM_KEY_F3 | SutAdapters.GUI.SELENIUM_KEY_F4 | SutAdapters.GUI.SELENIUM_KEY_F5 | SutAdapters.GUI.SELENIUM_KEY_F6 | SutAdapters.GUI.SELENIUM_KEY_F7 | SutAdapters.GUI.SELENIUM_KEY_F8 | SutAdapters.GUI.SELENIUM_KEY_F9 | SutAdapters.GUI.SELENIUM_KEY_F10 | SutAdapters.GUI.SELENIUM_KEY_F11 | SutAdapters.GUI.SELENIUM_KEY_F12 | SutAdapters.GUI.SELENIUM_KEY_META | SutAdapters.GUI.SELENIUM_KEY_COMMAND @type key: strconstant @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to type key in second (default=10s) @type timeout: float @param repeat: number to key to type (default=0) @type repeat: integer @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') for r in xrange(repeat + 1): cmdId = self.typeKeyElement(elementId=elementId, key=key) if self.hasTextEntered(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doMaximizeWindow(self, timeout=10.0, windowHandle='current'): """ Do maximize window @param timeout: time max to wait to maxime window in second (default=10s) @type timeout: float @param windowHandle: window handle (default=current) @type windowHandle: string @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.maximizeWindow( windowHandle=windowHandle) if self.isMaximized(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doRefreshPage(self, timeout=10.0): """ Do refresh page @param timeout: time max to wait to refresh page in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.refreshPage() if self.isRefreshed(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doGoBack(self, timeout=10.0): """ Do go back @param timeout: time max to wait to go back in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.navigBack() if self.isGoBack(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doGoForward(self, timeout=10.0): """ Do go forward @param timeout: time max to wait to go forward in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.navigForward() if self.isGoForward(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doDismissAlert(self, timeout=10.0): """ Do dismiss alert @param timeout: time max to wait to dismiss alert in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.dismissAlert() if self.isAlertDismissed(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doAcceptAlert(self, timeout=10.0): """ Do accept alert @param timeout: time max to wait to accept alert in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.acceptAlert() if self.isAlertAccepted(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doGetTextAlert(self, timeout=10.0): """ Do get text alert @param timeout: time max to wait to get text alert in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getTextAlert() rsp = self.hasTextAlert(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') ret = elementVall.get('value') return ret def doAuthenticateAlert(self, username, password, timeout=10.0): """ Do authenticate alert (basic http for example) @param username: username @type username: string @param password: password @type password: string @param timeout: time max to wait to authenticate alert in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.authenticateDialog(username=username, password=password) if self.isAlertAuthenticated(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doSwitchToFrame(self, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None, timeout=10.0): """ Do switch to frame Example by css selector: iframe[src='tab.jsp'] @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.switchToFrame(reference={'ELEMENT': str(elementId) }) if self.isFrameSwitched(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doSwitchToNextWindow(self, timeout=10.0): """ Do switch to the next windows @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.getCurrentWindowHandle() rsp = self.hasWindowHandle(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') currentHandle = elementVall.get('value') cmdId = self.getAllWindowHandles() rsp = self.hasWindowHandles(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') listHandles = elementVall.get('handles').getItems() z = 0 for h in sorted(listHandles): if h == currentHandle: break z += 1 z += 1 nextHandle = listHandles[z] cmdId = self.switchToWindow( windowName=nextHandle ) rsp = self.isWindowsSwitched(timeout=timeout, commandId=cmdId) if rsp is None: ret = False return ret def doClearTextElement(self, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Do clear the text if it's a text entry element. @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to get the text of the element in second (default=10s) @type timeout: float @return: False on action KO, the text otherwise @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) rsp = self.hasElement(timeout=timeout, commandId=cmdId) if rsp is None: ret = False else: elementVall = rsp.get('GUI', 'value') elementId = elementVall.get('element-id') cmdId = self.clearTextElement(elementId=elementId) if self.isElementCleared(timeout=timeout, commandId=cmdId) is None: ret = False return ret def doSelectByValue(self, text, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Select item in a list/combo by the value attribute @param text: text expected for the value @type text: string @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) selectElement = self.hasElement(timeout=timeout, commandId=cmdId) if selectElement is None: ret = False else: selectValue= selectElement.get('GUI', 'value') selectId = selectValue.get('element-id') css = "option[value =%s]" % self._escapeString(text) cmdId = self.findChildElements(elementId=selectId, cssSelector=css) optionsSelect = self.hasChildElements(timeout=timeout, commandId=cmdId) if optionsSelect is None: ret = False else: optionsValue = optionsSelect.get('GUI', 'value') optionsIds = eval( optionsValue.get('value') ) if not len(optionsIds): ret = False else: for opId in optionsIds: cmdId = self.clickElement(elementId=opId['ELEMENT']) elementClicked = self.isElementClicked(timeout=timeout, commandId=cmdId) if elementClicked is None: ret = False else: ret = True return ret def doSelectByText(self, text, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Select item in a list/combo by the text @param text: text expected @type text: string @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) selectElement = self.hasElement(timeout=timeout, commandId=cmdId) if selectElement is None: ret = False else: selectValue= selectElement.get('GUI', 'value') selectId = selectValue.get('element-id') xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) cmdId = self.findChildElements(elementId=selectId, xpath=xpath) optionsSelect = self.hasChildElements(timeout=timeout, commandId=cmdId) if optionsSelect is None: ret = False else: optionsValue = optionsSelect.get('GUI', 'value') optionsIds = eval( optionsValue.get('value') ) if not len(optionsIds): ret = False else: for opId in optionsIds: cmdId = self.clickElement(elementId=opId['ELEMENT']) elementClicked = self.isElementClicked(timeout=timeout, commandId=cmdId) if elementClicked is None: ret = False else: ret = True return ret def doRunJsElement(self, js, timeout=10.0, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Run javascript on element @param js: javascript code @type js: string @param name: search element by name @type name: string/none @param tagName: search element by tag name @type tagName: string/none @param className: search element by class name @type className: string/none @param id: search element by identifier @type id: string/none @param xpath: search element by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: search element by link text @type linkText: string/none @param partialLinkText: search element by partial link text @type partialLinkText: string/none @param cssSelector: search element by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True if not self.cfg['wait-until']: cmdId = self.implicitlyWait(timeout=timeout) if self.isWait(timeout=timeout, commandId=cmdId) is None: ret = False return ret cmdId = self.findElement(name=name, tagName=tagName, className=className, id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector, location=location) selectElement = self.hasElement(timeout=timeout, commandId=cmdId) if selectElement is None: ret = False else: elementValue= selectElement.get('GUI', 'value') elementId = elementValue.get('element-id') cmdId = self.runJavascriptElement(js=js, elementId=elementId) rsp = self.isScriptExecuted(timeout=timeout, commandId=cmdId) if rsp is None: ret = False return True return ret def _escapeString(self, value): """ internal function to escape string """ if '"' in value and "'" in value: substrings = value.split("\"") result = ["concat("] for substring in substrings: result.append("\"%s\"" % substring) result.append(", '\"', ") result = result[0:-1] if value.endswith('"'): result.append(", '\"'") return "".join(result) + ")" if '"' in value: return "'%s'" % value return "\"%s\"" % value def doSwitchToDefaultWindow(self, timeout=10.0): """ Do switch to default window @param timeout: time max to wait to switch to element in second (default=10s) @type timeout: float @return: True on action OK, False otherwise @rtype: boolean """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) ret = True cmdId = self.switchToDefaultFrame() if self.isFrameSwitched(timeout=timeout, commandId=cmdId) is None: ret = False return ret # function to make actions def getFirefoxProfile(self, profileDirectory=None): """ Return a firefox profile @param profileDirectory: Directory of profile that you want to use. (default=None) @type profileDirectory: string @return: firefox profile instance @rtype: object """ fp = webdriver.FirefoxProfile(profile_directory=profileDirectory) return fp def openNavig(self, desiredCapabilities, browserProfile=None, useMarionette=None, sessionName="default"): """ Start browser @return: internal command id @rtype: string """ self.navigId = None self.sessionName = sessionName if browserProfile: desiredCapabilities['firefox_profile'] = browserProfile.encoded if useMarionette is not None: # True to use gecko driver, support firefox >= 48 desiredCapabilities['marionette'] = useMarionette # send command to agent cmdId = self.executeCommand(Command.NEW_SESSION, { 'desiredCapabilities': desiredCapabilities,}) return cmdId def quitNavig(self): """ Stop browser @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.QUIT) return cmdId def closeWindow(self): """ Closes the current window. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.CLOSE) return cmdId def loadUrl(self, url): """ Loads a web page in the current browser session. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET, {'url': url}) return cmdId def getTitle(self): """ Gets the title of the current page. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_TITLE) return cmdId def getUrl(self): """ Gets the URL of the current page. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_CURRENT_URL) return cmdId def getPageSource(self): """ Gets the source of the current page. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_PAGE_SOURCE) return cmdId def implicitlyWait(self, timeout=10.0): """ Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. @param timeout: time max to wait to receive navig stopped event in second (default=10s) @type timeout: float @return: internal command id @rtype: string """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) cmdId = self.executeCommand(Command.IMPLICIT_WAIT, {'ms': float(timeout) * 1000}) return cmdId # function for windows def maximizeWindow(self, windowHandle='current'): """ Maximizes the current window that webdriver is using @param windowHandle: window handle (default=current) @type windowHandle: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.MAXIMIZE_WINDOW, {"windowHandle": windowHandle}) return cmdId def setWindowSize(self, width, height, windowHandle='current'): """ Sets the width and height of the current window. @param width: width position @type width: integer @param height: height position @type height: integer @param windowHandle: window handle (default=current) @type windowHandle: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SET_WINDOW_SIZE, {'width': int(width), 'height': int(height), "windowHandle": windowHandle}) return cmdId def getWindowSize(self, windowHandle='current'): """ Gets the width and height of the current window. @param windowHandle: window handle (default=current) @type windowHandle: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_WINDOW_SIZE, {"windowHandle": windowHandle}) return cmdId def getWindowPosition(self, windowHandle='current'): """ Gets the x,y position of the current window. @param windowHandle: window handle (default=current) @type windowHandle: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_WINDOW_POSITION, {"windowHandle": windowHandle}) return cmdId def setWindowPosition(self, x, y , windowHandle='current'): """ Sets the x,y position of the current window. @param x: x position @type x: integer @param y: y position @type y: integer @param windowHandle: window handle @type windowHandle: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SET_WINDOW_POSITION, {'x': int(x), 'y': int(y),"windowHandle": windowHandle}) return cmdId def getCurrentWindowHandle(self): """ Gets the handle of the current window. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_CURRENT_WINDOW_HANDLE) return cmdId def getAllWindowHandles(self): """ Get the handles of all windows within the current session. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_WINDOW_HANDLES) return cmdId def switchToWindow(self, windowName): """ Switches focus to the specified window by name or handle @param windowName: window name @type windowName: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SWITCH_TO_WINDOW, {'name': windowName}) return cmdId def switchToFrame(self, reference): """ Switches focus to the specified window by frame or index @param reference: frame reference (by index, name, or id) @type reference: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SWITCH_TO_FRAME, {'id': reference}) return cmdId def switchToDefaultFrame(self): """ Switch focus to the default frame. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SWITCH_TO_FRAME, {'id': None}) return cmdId # functions for alert def dismissAlert(self): """ Dismiss alert @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.DISMISS_ALERT) return cmdId def acceptAlert(self): """ Accept alert @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.ACCEPT_ALERT) return cmdId def getTextAlert(self): """ Get the text of the alert @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ALERT_TEXT) return cmdId def authenticateDialog(self, username, password): """ Authenticate with username and password (Basic HTTP Auth for example) @param username: username @type username: string @param password: password @type password: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SET_ALERT_CREDENTIALS, {'username':username, 'password':password}) return cmdId # function for navigation def navigBack(self): """ Goes one step backward in the browser history. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GO_BACK) return cmdId def navigForward(self): """ Goes one step forward in the browser history. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GO_FORWARD) return cmdId def refreshPage(self): """ Refreshes the current page. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.REFRESH) return cmdId # function for interact with element def findElement(self, elementId=None, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None, more={}): """ Find element @param elementId: element id @type elementId: string/none @param name: by name @type name: string/none @param tagName: by tag name @type tagName: string/none @param className: by class name @type className: string/none @param id: by identifier @type id: string/none @param xpath: by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: by link text @type linkText: string/none @param partialLinkText: by partial link text @type partialLinkText: string/none @param cssSelector: by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @return: internal command id @rtype: string """ by = None if name is not None: by = By.NAME value = name if id is not None: by = By.ID value = id if xpath is not None: by = By.XPATH value = xpath if linkText is not None: by = By.LINK_TEXT value = linkText if partialLinkText is not None: by = By.PARTIAL_LINK_TEXT value = partialLinkText if tagName is not None: by = By.TAG_NAME value = tagName if className is not None: by = By.CLASS_NAME value = className if cssSelector is not None: by = By.CSS_SELECTOR value = cssSelector if by is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "please to specify how to find the element" ) if location is not None: by = By.XPATH value = location params = {'using': by, 'value': value} if elementId is not None: params['id'] = elementId cmdId = self.executeCommand(Command.FIND_ELEMENT, params, more=more) return cmdId def findElements(self, elementId=None, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Find elements @param elementId: by element id @type elementId: string/none @param name: by name @type name: string/none @param tagName: by tag name @type tagName: string/none @param className: by class name @type className: string/none @param id: by identifier @type id: string/none @param xpath: by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: by link text @type linkText: string/none @param partialLinkText: by partial link text @type partialLinkText: string/none @param cssSelector: by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @return: internal command id @rtype: string """ by = None if name is not None: by = By.NAME value = name if id is not None: by = By.ID value = id if xpath is not None: by = By.XPATH value = xpath if linkText is not None: by = By.LINK_TEXT value = linkText if partialLinkText is not None: by = By.PARTIAL_LINK_TEXT value = partialLinkText if tagName is not None: by = By.TAG_NAME value = tagName if className is not None: by = By.CLASS_NAME value = className if cssSelector is not None: by = By.CSS_SELECTOR value = cssSelector if location is not None: by = By.XPATH value = location if by is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "please to specify how to find the element" ) params = {'using': by, 'value': value} if elementId is not None: params['id'] = elementId cmdId = self.executeCommand(Command.FIND_ELEMENTS, params) return cmdId def findChildElement(self, elementId, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Find child element @param elementId: parent element id @type elementId: string/none @param name: by name @type name: string/none @param tagName: by tag name @type tagName: string/none @param className: by class name @type className: string/none @param id: by identifier @type id: string/none @param xpath: by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: by link text @type linkText: string/none @param partialLinkText: by partial link text @type partialLinkText: string/none @param cssSelector: by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @return: internal command id @rtype: string """ by = None if name is not None: by = By.NAME value = name if id is not None: by = By.ID value = id if xpath is not None: by = By.XPATH value = xpath if linkText is not None: by = By.LINK_TEXT value = linkText if partialLinkText is not None: by = By.PARTIAL_LINK_TEXT value = partialLinkText if tagName is not None: by = By.TAG_NAME value = tagName if className is not None: by = By.CLASS_NAME value = className if cssSelector is not None: by = By.CSS_SELECTOR value = cssSelector if location is not None: by = By.XPATH value = location if by is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "please to specify how to find the element" ) params = {'using': by, 'value': value} params['id'] = elementId cmdId = self.executeCommand(Command.FIND_CHILD_ELEMENT, params) return cmdId def findChildElements(self, elementId, name=None, tagName=None, className=None, id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None, location=None): """ Find child elements @param elementId: by element id @type elementId: string/none @param name: by name @type name: string/none @param tagName: by tag name @type tagName: string/none @param className: by class name @type className: string/none @param id: by identifier @type id: string/none @param xpath: by xpath, example /html/body/form[1] @type xpath: string/none @param linkText: by link text @type linkText: string/none @param partialLinkText: by partial link text @type partialLinkText: string/none @param cssSelector: by css, example: p.content @type cssSelector: string/none @param location: as by xpath, example /html/body/form[1] @type location: string/none @return: internal command id @rtype: string """ by = None if name is not None: by = By.NAME value = name if id is not None: by = By.ID value = id if xpath is not None: by = By.XPATH value = xpath if linkText is not None: by = By.LINK_TEXT value = linkText if partialLinkText is not None: by = By.PARTIAL_LINK_TEXT value = partialLinkText if tagName is not None: by = By.TAG_NAME value = tagName if className is not None: by = By.CLASS_NAME value = className if cssSelector is not None: by = By.CSS_SELECTOR value = cssSelector if location is not None: by = By.XPATH value = location if by is None: raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "please to specify how to find the element" ) params = {'using': by, 'value': value} params['id'] = elementId cmdId = self.executeCommand(Command.FIND_CHILD_ELEMENTS, params) return cmdId def getTextElement(self, elementId): """ Get the text of the element @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ELEMENT_TEXT, {'id': elementId}) return cmdId def getAttributeElement(self, name, elementId): """ Gets the given attribute or property of the element @param name: name element @type name: string @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ELEMENT_ATTRIBUTE, {'id': elementId, 'name': name}) return cmdId def clickElement(self, elementId): """ Clicks on element @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.CLICK_ELEMENT, {'id': elementId, 'button': 0}) return cmdId def hoverElement(self, elementId): """ Moving the mouse to the middle of an element. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.MOVE_TO, {'element': elementId}) return cmdId def getTagNameElement(self, elementId): """ Get tag name @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId =self.executeCommand(Command.GET_ELEMENT_TAG_NAME, {'id': elementId}) return cmdId def submitElement(self, elementId): """ Submits a form. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SUBMIT_ELEMENT, {'id': elementId}) return cmdId def clearTextElement(self, elementId): """ Clears the text if it's a text entry element. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.CLEAR_ELEMENT, {'id': elementId}) return cmdId def selectedElement(self, elementId): """ Return if the element is selected. Can be used to check if a checkbox or radio button is selected. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.IS_ELEMENT_SELECTED, {'id': elementId}) return cmdId def enabledElement(self, elementId): """ Return if the element is enabled. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.IS_ELEMENT_ENABLED, {'id': elementId}) return cmdId def displayedElement(self, elementId, more={}): """ Whether the element is visible to a user. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.IS_ELEMENT_DISPLAYED, {'id': elementId}, more=more) return cmdId def sizeElement(self, elementId): """ The size of the element. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ELEMENT_SIZE, {'id': elementId}) return cmdId def locationElement(self, elementId): """ The location of the element in the renderable canvas. @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ELEMENT_LOCATION, {'id': elementId}) return cmdId def typeTextElement(self, elementId, text): """ Simulates typing text into the element. @param elementId: element id @type elementId: string @param text: text @type text: string @return: internal command id @rtype: string """ if sys.version_info < (3,): text = unicode(text, 'utf8') typing = [] for val in text: if isinstance(val, Keys): typing.append(val) elif isinstance(val, int): val = val.__str__() for i in range(len(val)): typing.append(val[i]) else: for i in range(len(val)): typing.append(val[i]) cmdId = self.executeCommand(Command.SEND_KEYS_TO_ELEMENT, {'id': elementId, 'value': typing}) return cmdId def typeKeyElement(self, elementId, key): """ Simulates typing key into the element. @param elementId: element id @type elementId: string @param key: SutAdapters.GUI.SELENIUM_KEY_NULL | SutAdapters.GUI.SELENIUM_KEY_CANCEL | SutAdapters.GUI.SELENIUM_KEY_HELP | SutAdapters.GUI.SELENIUM_KEY_BACKSPACE | SutAdapters.GUI.SELENIUM_KEY_TAB | SutAdapters.GUI.SELENIUM_KEY_CLEAR | SutAdapters.GUI.SELENIUM_KEY_RETURN | SutAdapters.GUI.SELENIUM_KEY_ENTER | SutAdapters.GUI.SELENIUM_KEY_SHIFT | SutAdapters.GUI.SELENIUM_KEY_CONTROL | SutAdapters.GUI.SELENIUM_KEY_ALT | SutAdapters.GUI.SELENIUM_KEY_PAUSE | SutAdapters.GUI.SELENIUM_KEY_ESCAPE | SutAdapters.GUI.SELENIUM_KEY_SPACE | SutAdapters.GUI.SELENIUM_KEY_PAGE_UP | SutAdapters.GUI.SELENIUM_KEY_PAGE_DOWN | SutAdapters.GUI.SELENIUM_KEY_END | SutAdapters.GUI.SELENIUM_KEY_HOME | SutAdapters.GUI.SELENIUM_KEY_LEFT | SutAdapters.GUI.SELENIUM_KEY_UP | SutAdapters.GUI.SELENIUM_KEY_RIGHT | SutAdapters.GUI.SELENIUM_KEY_DOWN | SutAdapters.GUI.SELENIUM_KEY_INSERT | SutAdapters.GUI.SELENIUM_KEY_DELETE | SutAdapters.GUI.SELENIUM_KEY_SEMICOLON | SutAdapters.GUI.SELENIUM_KEY_EQUALS | SutAdapters.GUI.SELENIUM_KEY_NUMPAD0 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD1 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD2 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD3 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD4 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD5 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD6 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD7 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD8 | SutAdapters.GUI.SELENIUM_KEY_NUMPAD9 | SutAdapters.GUI.SELENIUM_KEY_MULTIPLY | SutAdapters.GUI.SELENIUM_KEY_ADD | SutAdapters.GUI.SELENIUM_KEY_SEPARATOR | SutAdapters.GUI.SELENIUM_KEY_SUBTRACT | SutAdapters.GUI.SELENIUM_KEY_DECIMAL | SutAdapters.GUI.SELENIUM_KEY_DIVIDE | SutAdapters.GUI.SELENIUM_KEY_F1 | SutAdapters.GUI.SELENIUM_KEY_F2 | SutAdapters.GUI.SELENIUM_KEY_F3 | SutAdapters.GUI.SELENIUM_KEY_F4 | SutAdapters.GUI.SELENIUM_KEY_F5 | SutAdapters.GUI.SELENIUM_KEY_F6 | SutAdapters.GUI.SELENIUM_KEY_F7 | SutAdapters.GUI.SELENIUM_KEY_F8 | SutAdapters.GUI.SELENIUM_KEY_F9 | SutAdapters.GUI.SELENIUM_KEY_F10 | SutAdapters.GUI.SELENIUM_KEY_F11 | SutAdapters.GUI.SELENIUM_KEY_F12 | SutAdapters.GUI.SELENIUM_KEY_META | SutAdapters.GUI.SELENIUM_KEY_COMMAND @type key: strconstant @return: internal command id @rtype: string """ typing = [ key ] cmdId = self.executeCommand(Command.SEND_KEYS_TO_ELEMENT, {'id': elementId, 'value': typing}) return cmdId def runJavascriptElement(self, js, elementId): """ Execute javascript on element @param js: javascript to execute on element @type js: string @param elementId: element id @type elementId: string @return: internal command id @rtype: string """ return self.executeScript(js, {"ELEMENT": elementId} ) def executeScript(self, script, *args): """ Execute javascript @param script: javascript to execute @type script: string @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.EXECUTE_SCRIPT, {'script': script, 'args': list(args)} ) return cmdId # function for mouse def click(self): """ Mouse click @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.CLICK, {'button': 0}) return cmdId def rightClick(self): """ Rigth click from mouse @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.CLICK, {'button': 2}) return cmdId def doubleClick(self): """ Double click from mouse @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.DOUBLE_CLICK) return cmdId def clickDown(self): """ Mouse button down @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.MOUSE_DOWN) return cmdId def clickUp(self): """ Mouse button up @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.MOUSE_UP) return cmdId def mouseMove(self, xoffset, yoffset): """ Moving the mouse to an offset from current mouse position. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.MOVE_TO, {'xoffset': int(xoffset), 'yoffset': int(yoffset)} ) return cmdId # function for cookies def getCookies(self): """ Get a set of dictionaries, corresponding to cookies visible in the current session. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.GET_ALL_COOKIES) return cmdId def deleteCookies(self): """ Delete all cookies in the scope of the session. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.DELETE_ALL_COOKIES) return cmdId def deleteCookie(self, name): """ Deletes a single cookie with the given name. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.DELETE_COOKIE, {'name': name}) return cmdId def addCookie(self, cook): """ Adds a cookie to your current session. @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.ADD_COOKIE, {'cookie': cook}) return cmdId # functions for screenshots def getScreenshot(self): """ Gets the screenshot of the current window @return: internal command id @rtype: string """ cmdId = self.executeCommand(Command.SCREENSHOT) return cmdId # function to check responses def isActionAccepted(self, timeout=10.0, commandName=None, commandId=None, expectedValue=None): """ Waits to receive "action accepted" event until the end of the timeout @param timeout: time max to wait to receive event in second (default=10s) @type timeout: float @param commandName: name action @type commandName: string/none @param commandId: action id @type commandId: string/none @param expectedValue: text expected in vallue @type expectedValue: string/templates/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) # construct the expected template expected = self.encapsule(layer_gui=templates.gui(action=commandName, actionId=commandId, result=ACTION_OK, value=expectedValue )) # try to match the template evt = self.received( expected=expected, timeout=timeout ) return evt def isFrameSwitched(self, timeout=30.0, commandId=None): """ Waits to receive "iframe switched" event until the end of the timeout @param timeout: time max to wait to receive is switched event in second (default=20s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SWITCH_TO_FRAME, commandId=commandId) def isWindowsSwitched(self, timeout=30.0, commandId=None): """ Waits to receive "iwindows switched" event until the end of the timeout @param timeout: time max to wait to receive is switched event in second (default=20s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SWITCH_TO_WINDOW, commandId=commandId) def isNavigStarted(self, timeout=30.0, commandId=None): """ Waits to receive "navigator started" event until the end of the timeout @param timeout: time max to wait to receive navig started event in second (default=20s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.NEW_SESSION, commandId=commandId) def isNavigStopped(self, timeout=30.0, commandId=None): """ Waits to receive "navigator stopped" event until the end of the timeout @param timeout: time max to wait to receive navig stopped event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.QUIT, commandId=commandId) def isWindowClosed(self, timeout=30.0, commandId=None): """ Waits to receive "window closed" event until the end of the timeout @param timeout: time max to wait to receive window closed event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.CLOSE, commandId=commandId) def isUrlLoaded(self, timeout=20.0, commandId=None): """ Waits to receive "url loaded" event until the end of the timeout @param timeout: time max to wait to receive url loaded event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GET, commandId=commandId) def isMaximized(self, timeout=20.0, commandId=None): """ Waits to receive "maximized" event until the end of the timeout @param timeout: time max to wait to receive maximized event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.MAXIMIZE_WINDOW, commandId=commandId) def isRefreshed(self, timeout=20.0, commandId=None): """ Waits to receive "refreshed" event until the end of the timeout @param timeout: time max to wait to receive refresh event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.REFRESH, commandId=commandId) def isGoBack(self, timeout=20.0, commandId=None): """ Waits to receive "go back" event until the end of the timeout @param timeout: time max to wait to receive go back event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GO_BACK, commandId=commandId) def isGoForward(self, timeout=20.0, commandId=None): """ Waits to receive "go forward" event until the end of the timeout @param timeout: time max to wait to receive go forward event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GO_FORWARD, commandId=commandId) def hasWindowHandle(self, timeout=20.0, commandId=None): """ Waits to receive "window handle" event until the end of the timeout @param timeout: time max to wait to receive window handle event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_CURRENT_WINDOW_HANDLE, commandId=commandId) def hasWindowHandles(self, timeout=20.0, commandId=None): """ Waits to receive "window handles" event until the end of the timeout @param timeout: time max to wait to receive window handles event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_WINDOW_HANDLES, commandId=commandId) def hasUrl(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "url event" until the end of the timeout @param timeout: time max to wait to receive url event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @param expectedText: text expected in url @type expectedText: string/operators/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_CURRENT_URL, commandId=commandId, expectedValue=valueLayer) def hasSource(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "code source" event until the end of the timeout @param timeout: time max to wait to receive code source event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @param expectedText: text expected in source @type expectedText: string/operators/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_PAGE_SOURCE, commandId=commandId, expectedValue=valueLayer) def hasWindowTitle(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "window title" event until the end of the timeout @param timeout: time max to wait to receive window title event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @param expectedText: text expected in title @type expectedText: string/operators/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_TITLE, commandId=commandId, expectedValue=valueLayer) def hasScreenshot(self, timeout=20.0, commandId=None): """ Waits to receive "screenshot" event until the end of the timeout @param timeout: time max to wait to receive screenshot event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SCREENSHOT, commandId=commandId) def hasElement(self, timeout=20.0, commandId=None): """ Waits to receive "element" event until the end of the timeout @param timeout: time max to wait to receive element event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.FIND_ELEMENT, commandId=commandId) def hasElements(self, timeout=20.0, commandId=None): """ Waits to receive "elements" event until the end of the timeout @param timeout: time max to wait to receive elements event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.FIND_ELEMENTS, commandId=commandId) def hasChildElement(self, timeout=20.0, commandId=None): """ Waits to receive "element" event until the end of the timeout @param timeout: time max to wait to receive element event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.FIND_CHILD_ELEMENT, commandId=commandId) def hasChildElements(self, timeout=20.0, commandId=None): """ Waits to receive "elements" event until the end of the timeout @param timeout: time max to wait to receive elements event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.FIND_CHILD_ELEMENTS, commandId=commandId) def hasTextElement(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "text element" event until the end of the timeout @param timeout: time max to wait to receive text element event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @param expectedText: text expected in value @type expectedText: string/operators/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ELEMENT_TEXT, commandId=commandId, expectedValue=valueLayer) def hasAttributeElement(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "text attribute" element event until the end of the timeout @param timeout: time max to wait to receive text attribute element event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @param expectedText: text expected in value @type expectedText: string/operators/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ELEMENT_ATTRIBUTE, commandId=commandId, expectedValue=valueLayer) def isElementClicked(self, timeout=20.0, commandId=None): """ Waits to receive "element clicked" event until the end of the timeout @param timeout: time max to wait to receive element clicked event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.CLICK_ELEMENT, commandId=commandId) def isElementSubmitted(self, timeout=20.0, commandId=None): """ Waits to receive "element submitted" event until the end of the timeout @param timeout: time max to wait to receive element submitted event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SUBMIT_ELEMENT, commandId=commandId) def isElementCleared(self, timeout=20.0, commandId=None): """ Waits to receive "element cleared" event until the end of the timeout @param timeout: time max to wait to receive element cleared event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.CLEAR_ELEMENT, commandId=commandId) def isElementSelected(self, timeout=20.0, commandId=None): """ Waits to receive "element selected" event until the end of the timeout @param timeout: time max to wait to receive element selected event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.IS_ELEMENT_SELECTED, commandId=commandId) def isElementEnabled(self, timeout=20.0, commandId=None): """ Waits to receive "element enabled" event until the end of the timeout @param timeout: time max to wait to receive element enabled event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.IS_ELEMENT_ENABLED, commandId=commandId) def isElementDisplayed(self, timeout=20.0, commandId=None): """ Waits to receive "element displayed" event until the end of the timeout @param timeout: time max to wait to receive element displayed event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.IS_ELEMENT_DISPLAYED, commandId=commandId) def isElementSize(self, timeout=20.0, commandId=None): """ Waits to receive "element size" event until the end of the timeout @param timeout: time max to wait to receive element size event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ELEMENT_SIZE, commandId=commandId) def isElementLocation(self, timeout=20.0, commandId=None): """ Waits to receive "element location" event until the end of the timeout @param timeout: time max to wait to receive element location event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ELEMENT_LOCATION, commandId=commandId) def hasTextEntered(self, timeout=20.0, commandId=None): """ Waits to receive "text entered" event until the end of the timeout @param timeout: time max to wait to receive text entered event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SEND_KEYS_TO_ELEMENT, commandId=commandId) def hasMouseMoved(self, timeout=20.0, commandId=None): """ Waits to receive "mouse moved" event until the end of the timeout @param timeout: time max to wait to receive mouse moved event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.MOVE_TO, commandId=commandId) def isClicked(self, timeout=20.0, commandId=None): """ Waits to receive "clicked event" until the end of the timeout @param timeout: time max to wait to receive clicked event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.CLICK, commandId=commandId) def isDoubleClicked(self, timeout=20.0, commandId=None): """ Waits to receive "double clicked" event until the end of the timeout @param timeout: time max to wait to receive double clicked event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.DOUBLE_CLICK, commandId=commandId) def isClickedDown(self, timeout=20.0, commandId=None): """ Waits to receive "clicked down" event until the end of the timeout @param timeout: time max to wait to receive click down event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.MOUSE_DOWN, commandId=commandId) def isClickedUp(self, timeout=20.0, commandId=None): """ Waits to receive "clicked up" event until the end of the timeout @param timeout: time max to wait to receive click up event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.MOUSE_UP, commandId=commandId) def isWait(self, timeout=20.0, commandId=None): """ Waits to receive "wait" event until the end of the timeout @param timeout: time max to wait to receive wait event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.IMPLICIT_WAIT, commandId=commandId) def isAlertDismissed(self, timeout=20.0, commandId=None): """ Waits to receive "dismiss alert" event until the end of the timeout @param timeout: time max to wait to receive dismiss alert event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.DISMISS_ALERT, commandId=commandId) def isAlertAccepted(self, timeout=20.0, commandId=None): """ Waits to receive "accept alert" event until the end of the timeout @param timeout: time max to wait to receive accept alert event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.ACCEPT_ALERT, commandId=commandId) def hasTextAlert(self, timeout=20.0, commandId=None, expectedText=None): """ Waits to receive "text alert" event until the end of the timeout @param timeout: time max to wait to receive text alert event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) valueLayer = TestTemplates.TemplateLayer(name="") if expectedText is not None: valueLayer.addKey(name="value", data=expectedText) return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ALERT_TEXT, commandId=commandId, expectedValue=valueLayer) def isAlertAuthenticated(self, timeout=20.0, commandId=None): """ Waits to receive "authenticated" event until the end of the timeout @param timeout: time max to wait to receive authenticated event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.SET_ALERT_CREDENTIALS, commandId=commandId) def isScriptExecuted(self, timeout=20.0, commandId=None): """ Waits to receive "script executed" event until the end of the timeout @param timeout: time max to wait to receive script executed event in second (default=10s) @type timeout: float @param commandId: action id @type commandId: string/none @return: an event matching with the template or none otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) return self.isActionAccepted(timeout=timeout, commandName=Command.EXECUTE_SCRIPT, commandId=commandId)
39.472462
2,096
0.557304
17,044
173,442
5.628667
0.049343
0.027727
0.03518
0.029186
0.789639
0.769062
0.761641
0.751822
0.744859
0.731662
0
0.0062
0.365765
173,442
4,394
2,097
39.472462
0.865913
0.323774
0
0.59116
0
0
0.034045
0.000967
0
0
0
0
0
1
0.100061
false
0.003069
0.01105
0
0.226519
0
0
0
0
null
0
0
0
0
1
1
1
1
1
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
a31303dd31bd4ee7ec464aae9b77b473605dd2e5
112
py
Python
MathOperations/subtraction.py
mkm99/firstDockerProject
9a0190216d9be7c2a01b428923ffb0e1c932991b
[ "MIT" ]
null
null
null
MathOperations/subtraction.py
mkm99/firstDockerProject
9a0190216d9be7c2a01b428923ffb0e1c932991b
[ "MIT" ]
null
null
null
MathOperations/subtraction.py
mkm99/firstDockerProject
9a0190216d9be7c2a01b428923ffb0e1c932991b
[ "MIT" ]
null
null
null
class Subtraction: @staticmethod def subtract(minuend, subtrahend): return minuend - subtrahend
22.4
38
0.705357
10
112
7.9
0.8
0.43038
0
0
0
0
0
0
0
0
0
0
0.232143
112
5
39
22.4
0.918605
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0
0.25
0.75
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
1
0
0
0
1
1
0
0
6
a3170bce998b31fb9eeace88651e2b8b3bab56d7
37
py
Python
appengine_config.py
jinglundong/GuessGame
d6953d279d476c1281d15369ee18135c241441a5
[ "MIT" ]
null
null
null
appengine_config.py
jinglundong/GuessGame
d6953d279d476c1281d15369ee18135c241441a5
[ "MIT" ]
null
null
null
appengine_config.py
jinglundong/GuessGame
d6953d279d476c1281d15369ee18135c241441a5
[ "MIT" ]
null
null
null
from google.appengine.ext import ndb
18.5
36
0.837838
6
37
5.166667
1
0
0
0
0
0
0
0
0
0
0
0
0.108108
37
1
37
37
0.939394
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
a332a06bfee68be057f4a33d24668014c98c8d10
11,275
py
Python
tests/110_cli_common_options.py
acbaraka/py-html-checker
41f2831f0cedff35236c13a1b7eb6f5a93fd9e29
[ "MIT" ]
1
2021-05-13T15:11:11.000Z
2021-05-13T15:11:11.000Z
tests/110_cli_common_options.py
acbaraka/py-html-checker
41f2831f0cedff35236c13a1b7eb6f5a93fd9e29
[ "MIT" ]
24
2019-08-14T14:51:12.000Z
2022-03-22T20:04:49.000Z
tests/110_cli_common_options.py
acbaraka/py-html-checker
41f2831f0cedff35236c13a1b7eb6f5a93fd9e29
[ "MIT" ]
2
2021-05-13T15:11:14.000Z
2021-07-19T21:27:04.000Z
""" These tests cover shared options for page and site commands. They mockup some validator, exporter and sitemap methods to just return command lines without processing or executing anything else. """ import logging import os import pytest from click.testing import CliRunner from html_checker.cli.entrypoint import cli_frontend from html_checker.export import LoggingExport from html_checker.validator import ValidatorInterface from html_checker.sitemap import Sitemap class DummyReport: """ A dummy reporter to simulate ReportStore signatures but just to add given paths in registry """ def __init__(self, *args, **kwargs): self.registry = [] def add(self, content): print() print("DummyReport: content") print(content) print() print("DummyReport: registry before") print(self.registry) self.registry.append(content) print() print("DummyReport: registry after") print(self.registry) print() def mock_validator_execute_validator(*args, **kwargs): """ Mock method to just return the builded command line without executing it. """ cls = args[0] command = args[1] return command def mock_export_logging_build(*args, **kwargs): """ Mock method to just logging given command lines in ``report`` argument (following validator mockups). """ cls = args[0] report = args[1] for k in report: cls.log.info(" ".join(k)) def mock_sitemap_get_urls(*args, **kwargs): """ Mock method to just return given url as argument so it can pass the dummy url to validator without to read it like a sitemap. """ cls = args[0] path = args[1] return [path] @pytest.mark.parametrize("command_name", [ "page", "site", ]) def test_interpreter_xss(monkeypatch, caplog, settings, command_name): """ '-Xss' option should be correctly added to interpreter part. """ monkeypatch.setattr(ValidatorInterface, "execute_validator", mock_validator_execute_validator) monkeypatch.setattr(ValidatorInterface, "REPORT_CLASS", DummyReport) monkeypatch.setattr(LoggingExport, "build", mock_export_logging_build) monkeypatch.setattr(Sitemap, "get_urls", mock_sitemap_get_urls) commandline = ( "java" " -Xss512k" " -jar {APPLICATION}/vnujar/vnu.jar" " --format json" " --exit-zero-always" " --user-agent {USER_AGENT}" " http://perdu.com" ) expected = [] if command_name == "site": expected.append( ("py-html-checker", logging.INFO, "Sitemap have 1 paths"), ) else: expected.append( ("py-html-checker", logging.INFO, "Launching validation for 1 paths"), ) expected.append( ("py-html-checker", logging.INFO, settings.format(commandline)), ) runner = CliRunner() with runner.isolated_filesystem(): test_cwd = os.getcwd() result = runner.invoke(cli_frontend, [ command_name, "--Xss", "512k", "http://perdu.com" ]) print("=> result.output <=") print(result.output) print() print("=> expected <=") print(expected) print() print("=> caplog.record_tuples <=") print(caplog.record_tuples) print() print("=> result.exception <=") print(result.exception) if result.exception is not None: raise result.exception assert result.exit_code == 0 assert expected == caplog.record_tuples @pytest.mark.parametrize("command_name", [ "page", "site", ]) def test_interpreter_nostream(monkeypatch, caplog, settings, command_name): """ '--no-stream' option should be correctly added to interpreter part. """ monkeypatch.setattr(ValidatorInterface, "execute_validator", mock_validator_execute_validator) monkeypatch.setattr(ValidatorInterface, "REPORT_CLASS", DummyReport) monkeypatch.setattr(LoggingExport, "build", mock_export_logging_build) monkeypatch.setattr(Sitemap, "get_urls", mock_sitemap_get_urls) commandline = ( "java" " -jar {APPLICATION}/vnujar/vnu.jar" " --no-stream" " --format json" " --exit-zero-always" " --user-agent {USER_AGENT}" " http://perdu.com" ) expected = [] if command_name == "site": expected.append( ("py-html-checker", logging.INFO, "Sitemap have 1 paths"), ) else: expected.append( ("py-html-checker", logging.INFO, "Launching validation for 1 paths"), ) expected.append( ("py-html-checker", logging.INFO, settings.format(commandline)), ) runner = CliRunner() with runner.isolated_filesystem(): test_cwd = os.getcwd() result = runner.invoke(cli_frontend, [ command_name, "--no-stream", "http://perdu.com" ]) assert result.exit_code == 0 assert expected == caplog.record_tuples @pytest.mark.parametrize("command_name", [ "page", "site", ]) def test_user_agent(monkeypatch, caplog, settings, command_name): """ '--user-agent' option should be correctly added to every part. """ monkeypatch.setattr(ValidatorInterface, "execute_validator", mock_validator_execute_validator) monkeypatch.setattr(ValidatorInterface, "REPORT_CLASS", DummyReport) monkeypatch.setattr(LoggingExport, "build", mock_export_logging_build) monkeypatch.setattr(Sitemap, "get_urls", mock_sitemap_get_urls) commandline = ( "java" " -jar {APPLICATION}/vnujar/vnu.jar" " --user-agent Foobar" " --format json" " --exit-zero-always" " http://perdu.com" ) expected = [] if command_name == "site": expected.append( ("py-html-checker", logging.INFO, "Sitemap have 1 paths"), ) else: expected.append( ("py-html-checker", logging.INFO, "Launching validation for 1 paths"), ) expected.append( ("py-html-checker", logging.INFO, settings.format(commandline)), ) runner = CliRunner() with runner.isolated_filesystem(): test_cwd = os.getcwd() result = runner.invoke(cli_frontend, [ command_name, "--user-agent", "Foobar", "http://perdu.com" ]) assert result.exit_code == 0 assert expected == caplog.record_tuples @pytest.mark.parametrize("split,paths", [ ( False, ["http://foo.com", "http://bar.com"], ), ( True, ["http://foo.com", "http://bar.com"], ), ]) def test_page_split(monkeypatch, caplog, settings, split, paths): """ '--split' option should cause executing a new nvu validator instance on each path and only one for all path when not enabled. """ monkeypatch.setattr(ValidatorInterface, "execute_validator", mock_validator_execute_validator) monkeypatch.setattr(ValidatorInterface, "REPORT_CLASS", DummyReport) monkeypatch.setattr(LoggingExport, "build", mock_export_logging_build) commandline = settings.format(( "java" " -jar {APPLICATION}/vnujar/vnu.jar" " --format json" " --exit-zero-always" " --user-agent {USER_AGENT}" " " )) # Build expected logs depending split option initial_msg = "Launching validation for {} paths" expected = [ ("py-html-checker", logging.INFO, initial_msg.format(len(paths))), ] # In split mode, there should one command line for each path if split: for p in paths: log = ("py-html-checker", logging.INFO, commandline + p) expected.append( log ), # Else there should be only one command line for all paths else: expected.append( ("py-html-checker", logging.INFO, commandline + " ".join(paths)) ), runner = CliRunner() with runner.isolated_filesystem(): test_cwd = os.getcwd() args = ["page"] if split: args.append("--split") for item in paths: args.append(item) result = runner.invoke(cli_frontend, args) print("=> result.output <=") print(result.output) print() print("=> result.exception <=") print(result.exception) print() print("=> expected <=") print(expected) print() print("=> caplog.record_tuples <=") print(caplog.record_tuples) assert result.exit_code == 0 assert expected == caplog.record_tuples @pytest.mark.parametrize("split,paths", [ ( False, ["http://foo.com", "http://bar.com"], ), ( True, ["http://foo.com", "http://bar.com"], ), ]) def test_site_split(monkeypatch, caplog, settings, split, paths): """ '--split' option should cause executing a new vnu validator instance on each path and only one for all path when not enabled. """ def mock_sitemap_get_urls(*args, **kwargs): """ Mock method to just return harcoded dummy paths we expect from parsed sitemap """ return ["http://foo.com", "http://bar.com"] monkeypatch.setattr(ValidatorInterface, "execute_validator", mock_validator_execute_validator) monkeypatch.setattr(ValidatorInterface, "REPORT_CLASS", DummyReport) monkeypatch.setattr(LoggingExport, "build", mock_export_logging_build) monkeypatch.setattr(Sitemap, "get_urls", mock_sitemap_get_urls) commandline = settings.format(( "java" " -jar {APPLICATION}/vnujar/vnu.jar" " --format json" " --exit-zero-always" " --user-agent {USER_AGENT}" " " )) # Build expected logs initial_msg = "Sitemap have {} paths" expected = [ ("py-html-checker", logging.INFO, initial_msg.format(len(paths))), ] # In split mode, there should one command line for each path if split: for p in paths: log = ("py-html-checker", logging.INFO, commandline + p) expected.append( log ), # Else there should be only one command line for all paths else: expected.append( ("py-html-checker", logging.INFO, commandline + " ".join(paths)) ), runner = CliRunner() with runner.isolated_filesystem(): test_cwd = os.getcwd() args = ["site"] if split: args.append("--split") args.append("http://perdu.com/sitemap.xml") result = runner.invoke(cli_frontend, args, catch_exceptions=False) #print("=> result.output <=") #print(result.output) #print() #print("=> result.exception <=") #print(result.exception) #print() #print("=> expected <=") #print(expected) #print() #print("=> caplog.record_tuples <=") #print(caplog.record_tuples) assert result.exit_code == 0 assert expected == caplog.record_tuples
28.762755
82
0.603548
1,203
11,275
5.541147
0.159601
0.031353
0.029253
0.045005
0.794479
0.757276
0.735974
0.724422
0.719322
0.719322
0
0.002803
0.272284
11,275
391
83
28.836317
0.809628
0.14439
0
0.755474
0
0
0.190819
0.014842
0
0
0
0
0.036496
1
0.040146
false
0
0.029197
0
0.083942
0.116788
0
0
0
null
0
0
0
0
1
1
1
1
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
6
a338c5ed69e61e1bea17f973ef964ffccd9246d1
840
py
Python
CodeWarsKataStuff/Parenthesis reversal.py
perrymant/CodeWarsKataStuff
20eb25a3f0070aee5f5ae9a03a656acd5557c021
[ "MIT" ]
null
null
null
CodeWarsKataStuff/Parenthesis reversal.py
perrymant/CodeWarsKataStuff
20eb25a3f0070aee5f5ae9a03a656acd5557c021
[ "MIT" ]
null
null
null
CodeWarsKataStuff/Parenthesis reversal.py
perrymant/CodeWarsKataStuff
20eb25a3f0070aee5f5ae9a03a656acd5557c021
[ "MIT" ]
null
null
null
s = "())(((" def solve(s): if len(s)%2 == 1: return -1 else: count = 0 front, back = s[:len(s)//2], s[len(s)//2:] for i in zip(front, back): if i == (")", "("): count += 2 if i == ("(", ")"): count += 0 else: count += 1 return count print(solve(s)) """ https://www.codewars.com/kata/simple-reversed-parenthesis/train/python s = "())(((" def solve(s): if len(s)%2 == 1: return -1 else: count = 0 front, back = s[:len(s)//2], s[len(s)//2:] for i in zip(front, back): if i == (")", "("): count += 2 if i == ("(", ")"): count += 0 else: count += 1 return count print(solve(s)) """
19.534884
70
0.365476
102
840
3.009804
0.27451
0.078176
0.09772
0.078176
0.807818
0.807818
0.807818
0.807818
0.807818
0.807818
0
0.037657
0.430952
840
42
71
20
0.604603
0
0
0.125
0
0
0.026178
0
0
0
0
0
0
1
0.0625
false
0
0
0
0.1875
0.0625
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
a34a059c10f2dcecdccb8f0ea81299c7b7e9f1a0
43
py
Python
home/admin.py
R-Wolf/CFD_A_library
b287ed8b2932b0f3b1cf5372f8d3d3494c6439c9
[ "MIT" ]
4
2017-03-14T05:03:03.000Z
2019-04-13T05:13:24.000Z
home/admin.py
gpulkit96/CFD_A_library
b287ed8b2932b0f3b1cf5372f8d3d3494c6439c9
[ "MIT" ]
1
2017-05-18T08:39:46.000Z
2017-05-18T08:39:46.000Z
home/admin.py
gpulkit96/CFD_A_library
b287ed8b2932b0f3b1cf5372f8d3d3494c6439c9
[ "MIT" ]
2
2017-03-13T08:54:21.000Z
2017-05-18T06:24:58.000Z
from django.contrib.admin import AdminSite
21.5
42
0.860465
6
43
6.166667
1
0
0
0
0
0
0
0
0
0
0
0
0.093023
43
1
43
43
0.948718
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
a3518776a6edaa2e16ae6beb04125ae5dc9af16f
102
py
Python
behavioral/memento/logic/__init__.py
Kozak24/Patterns
351d5c11f7c64ce5d58db37b6715fc8f7d31945a
[ "MIT" ]
null
null
null
behavioral/memento/logic/__init__.py
Kozak24/Patterns
351d5c11f7c64ce5d58db37b6715fc8f7d31945a
[ "MIT" ]
null
null
null
behavioral/memento/logic/__init__.py
Kozak24/Patterns
351d5c11f7c64ce5d58db37b6715fc8f7d31945a
[ "MIT" ]
null
null
null
from .player_memento import PlayerMemento from .player import Player from .caretaker import Caretaker
25.5
41
0.852941
13
102
6.615385
0.461538
0.232558
0
0
0
0
0
0
0
0
0
0
0.117647
102
3
42
34
0.955556
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
6e82b8bdddd7bd17c8de898b49786a6723fc8733
268
py
Python
_/0349_05_Code/admin.py
paullewallencom/javascript-978-1-8495-1034-9
7e539d042c644931a9ef2418f66d260a1c6892eb
[ "Apache-2.0" ]
null
null
null
_/0349_05_Code/admin.py
paullewallencom/javascript-978-1-8495-1034-9
7e539d042c644931a9ef2418f66d260a1c6892eb
[ "Apache-2.0" ]
null
null
null
_/0349_05_Code/admin.py
paullewallencom/javascript-978-1-8495-1034-9
7e539d042c644931a9ef2418f66d260a1c6892eb
[ "Apache-2.0" ]
null
null
null
import django.contrib.admin import directory.models import tagging django.contrib.admin.autodiscover() django.contrib.admin.site.register(directory.models.Entity) django.contrib.admin.site.register(directory.models.Location) tagging.register(directory.models.Entity)
29.777778
61
0.850746
34
268
6.705882
0.352941
0.22807
0.315789
0.192982
0.394737
0.394737
0.394737
0
0
0
0
0
0.041045
268
8
62
33.5
0.88716
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.428571
0
0.428571
0
0
0
0
null
1
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
1
0
1
0
0
0
0
6
6e963c476048731431e1fd6141463ac8630a9dec
154
py
Python
finml/portfolio_optimization/__init__.py
yanghoonkim/FinML
f112647a20c0012a4973b3ee230dc4a1350deb9a
[ "MIT" ]
2
2021-01-31T07:54:06.000Z
2021-04-26T05:45:17.000Z
finml/portfolio_optimization/__init__.py
yanghoonkim/FinML
f112647a20c0012a4973b3ee230dc4a1350deb9a
[ "MIT" ]
null
null
null
finml/portfolio_optimization/__init__.py
yanghoonkim/FinML
f112647a20c0012a4973b3ee230dc4a1350deb9a
[ "MIT" ]
3
2021-01-28T06:01:51.000Z
2021-04-26T05:45:21.000Z
from finml.portfolio_optimization.riskaverse import RiskAverseOptimization from finml.portfolio_optimization.simplemeanvariance import SimpleMeanVariance
51.333333
78
0.922078
14
154
10
0.571429
0.128571
0.257143
0.428571
0
0
0
0
0
0
0
0
0.051948
154
2
79
77
0.958904
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
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
1
0
1
0
0
0
0
6
6e9ce0c9ae6d89cf105b7ad135f7dd826afece3f
8,354
py
Python
src/stactools/worldclim/commands.py
stactools-packages/worldclim
da81809f610c802f40de101713f12f8433c20b44
[ "Apache-2.0" ]
null
null
null
src/stactools/worldclim/commands.py
stactools-packages/worldclim
da81809f610c802f40de101713f12f8433c20b44
[ "Apache-2.0" ]
6
2021-07-09T21:07:54.000Z
2021-11-01T21:53:50.000Z
src/stactools/worldclim/commands.py
stactools-packages/worldclim
da81809f610c802f40de101713f12f8433c20b44
[ "Apache-2.0" ]
null
null
null
import logging import os import shutil from glob import glob import click from stactools.worldclim import cog, stac from stactools.worldclim.constants import MONTHLY_DATA_VARIABLES logger = logging.getLogger(__name__) def create_worldclim_command(cli): """Creates the stactools-worldclim command line utility.""" @cli.group( "worldclim", short_help=("Commands for working with stactools-worldclim"), ) def worldclim(): pass @worldclim.command( "create-all-monthly-cogs", short_help="Download and convert all data files to COGs", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_all_monthly_cogs(destination: str): """Creates a STAC Item Args: source (str): HREF of the Asset associated with the Item destination (str): An HREF for the STAC Collection """ cog.download_convert_monthly_dataset(destination) @worldclim.command( "create-all-bioclim-cogs", short_help="Download and convert all data files to COGs", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_all_bioclim_cogs(destination: str): """Creates a STAC Item Args: source (str): HREF of the Asset associated with the Item destination (str): An HREF for the STAC Collection """ cog.download_convert_bioclim_dataset(destination) @worldclim.command( "create-monthly-collection", short_help="Creates a monthly STAC collection", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_collection_command(destination: str): """Creates a STAC Collection Args: destination (str): An HREF for the Collection JSON """ collection = stac.create_monthly_collection() collection.set_self_href(os.path.join(destination, "collection.json")) collection.normalize_hrefs(destination) collection.save_object() collection.validate() return None @worldclim.command( "create-monthly-collection", short_help="Creates a monthly STAC collection", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_monthly_collection_command(destination: str): """Creates a STAC Collection Args: destination (str): An HREF for the Collection JSON """ collection = stac.create_monthly_collection() collection.set_self_href(os.path.join(destination, "collection.json")) collection.normalize_hrefs(destination) collection.save_object() collection.validate() return None @worldclim.command( "create-bioclim-collection", short_help="Creates a monthly STAC collection", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_bioclim_collection_command(destination: str): """Creates a STAC Collection Args: destination (str): An HREF for the Collection JSON """ collection = stac.create_bioclim_collection() collection.set_self_href(os.path.join(destination, "collection.json")) collection.normalize_hrefs(destination) collection.save_object() collection.validate() return None @worldclim.command( "create-monthly-item", short_help="Create a monthly STAC item", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) @click.option( "-c", "--cog", required=True, help="Location of a directory contining the cogs", ) def create_monthly_item_command(destination: str, cog: str): """Creates a STAC Item Args: destination (str): Output directory cog (str): HREF to the Asset COG """ item = stac.create_monthly_item(cog) item.save_object(dest_href=os.path.join( destination, os.path.basename(cog).replace(".tif", ".json"))) item.validate() return None @worldclim.command( "create-bioclim-item", short_help="Create a Bioclimatic STAC item", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) @click.option( "-c", "--cog", required=True, help="Location of a directory contining the cogs", ) def create_bioclim_item_command(destination: str, cog: str): """Creates a STAC Item Args: destination (str): An HREF for the STAC Collection cog (str): HREF to the Asset COG """ item = stac.create_bioclim_item(cog) item.save_object(dest_href=os.path.join( destination, os.path.basename(cog).replace(".tif", ".json"))) item.save_object() item.validate() return None @worldclim.command( "create-full-monthly-collection", short_help="Get all data files and create Items and Collection", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_full_monthly__collection(destination: str): """Creates a STAC Collection and all of its Items and Assets Args: destination (str): An HREF for the STAC Collection """ os.chdir(destination) collection = stac.create_monthly_collection() collection.normalize_hrefs("./") collection.save(dest_href="./") cog.download_convert_monthly_dataset("./") for file_name in glob("./*tmin*.tif"): logger.info(f"Processing {file_name}") id = stac.create_monthly_item(file_name).id os.makedirs(id, exist_ok=True) for data_var in MONTHLY_DATA_VARIABLES.keys(): var_file_name = file_name.replace("tmin", data_var) shutil.move(var_file_name, os.path.join(id, var_file_name)) item = stac.create_monthly_item(os.path.join(id, file_name)) collection.add_item(item) item.validate() logger.info("Saving collection") collection.normalize_hrefs("./") collection.make_all_asset_hrefs_relative() collection.save(dest_href="./") collection.validate() @worldclim.command( "create-full-bioclim-collection", short_help="Get all data files and create Items and Collection", ) @click.option( "-d", "--destination", required=True, help="The output directory for the STAC json", ) def create_full_bioclim__collection(destination: str): """Creates a STAC Collection and all of its Items and Assets Args: destination (str): An HREF for the STAC Collection """ os.chdir(destination) collection = stac.create_bioclim_collection() collection.normalize_hrefs("./") collection.save(dest_href="./") cog.download_convert_bioclim_dataset("./") for file_name in glob("./*.tif"): logger.info(f"Processing {file_name}") id = os.path.basename(file_name).replace(".tif", "") item_dir = id os.makedirs(item_dir, exist_ok=True) new_file_name = os.path.join(item_dir, f"{id}.tif") shutil.move(file_name, new_file_name) item = stac.create_bioclim_item(new_file_name) collection.add_item(item) item.validate() logger.info("Saving collection") collection.normalize_hrefs("./") collection.make_all_asset_hrefs_relative() collection.save(dest_href="./") collection.validate() return worldclim
31.171642
78
0.605818
923
8,354
5.328277
0.114843
0.05124
0.028467
0.04209
0.836112
0.786905
0.772875
0.752948
0.739122
0.733835
0
0
0.288604
8,354
267
79
31.28839
0.827528
0.126526
0
0.625
0
0
0.198169
0.025898
0
0
0
0
0
1
0.055
false
0.005
0.035
0
0.12
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
42c5e64ad52a0a82a1b1df63616bd3576ff2035e
40,931
py
Python
venv/lib/python3.6/site-packages/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_firmware_catalog.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_firmware_catalog.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_firmware_catalog.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Dell EMC OpenManage Ansible Modules # Version 3.4.0 # Copyright (C) 2019-2021 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest from ssl import SSLError from ansible_collections.dellemc.openmanage.plugins.modules import ome_firmware_catalog from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import FakeAnsibleModule from io import StringIO from ansible.module_utils._text import to_text from ansible.module_utils.urls import ConnectionError, SSLValidationError import json from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError MODULE_PATH = 'ansible_collections.dellemc.openmanage.plugins.modules.ome_firmware_catalog.' NO_CHANGES_MSG = "No changes found to be applied." INVALID_CATALOG_ID = "Invalid catalog ID provided." CATALOG_DEL_SUCCESS = "Successfully deleted the firmware catalog." CATALOG_BASELINE_ATTACHED = "Unable to delete as catalog is associated with baseline(s)." CATALOG_JOB_RUNNING = "Catalog job '{name}' with ID {id} is running.Retry after job completion." CHECK_MODE_CHANGE_FOUND_MSG = "Changes found to be applied." CHECK_MODE_CHANGE_NOT_FOUND_MSG = "No changes found to be applied." INVALID_CATALOG_ID = "Invalid catalog ID provided." CATALOG_DEL_SUCCESS = "Successfully deleted the firmware catalog(s)." CATALOG_BASELINE_ATTACHED = "Unable to delete the catalog as it is with baseline(s)." CATALOG_EXISTS = "The catalog with the name '{new_name}' already exists in the system." DELL_ONLINE_EXISTS = "Catalog with 'DELL_ONLINE' repository already exists with the name '{catalog_name}'." NAMES_ERROR = "Only delete operations accept multiple catalog names or IDs." CATALOG_ID_NOT_FOUND = "Catalog with ID '{catalog_id}' not found." CATALOG_NAME_NOT_FOUND = "Catalog '{catalog_name}' not found." CATALOG_UPDATED = "Successfully {operation} the firmware catalog." catalog_info = { "@odata.context": "/api/$metadata#Collection(UpdateService.Catalogs)", "@odata.count": 3, "value": [ { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(29)", "Id": 29, "Filename": "catalog.gz", "SourcePath": "catalog/catalog.gz", "Status": "Failed", "TaskId": 21448, "BaseLocation": None, "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "AssociatedBaselines": ["abc"], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 19, "Name": "catalog_http3", "Description": "catalog desc3", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "HTTP" } }, { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(30)", "Id": 30, "Filename": "catalog.gz", "SourcePath": "catalog/catalog.gz", "Status": "Failed", "BaseLocation": None, "TaskId": 21449, "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 20, "Name": "catalog_http4", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "HTTP" } }, { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } ] } catalog_resp = { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } @pytest.fixture def ome_connection_catalog_mock(mocker, ome_response_mock): connection_class_mock = mocker.patch(MODULE_PATH + 'RestOME') ome_connection_mock_obj = connection_class_mock.return_value.__enter__.return_value ome_connection_mock_obj.invoke_request.return_value = ome_response_mock return ome_connection_mock_obj class TestOmeFirmwareCatalog(FakeAnsibleModule): module = ome_firmware_catalog @pytest.fixture def mock__get_catalog_payload(self, mocker): mock_payload = mocker.patch( MODULE_PATH + '_get_catalog_payload', return_value={"Repistory": "Dummy val"}) return mock_payload def test_ome_catalog_firmware_main_ome_firmware_catalog_no_mandatory_arg_passed_failuer_case(self, ome_default_args, module_mock, mock__get_catalog_payload, ome_connection_catalog_mock): result = self._run_module_with_fail_json(ome_default_args) assert 'catalog_status' not in result inp_param1 = {"hostname": "host ip", "username": "username", "password": "password", "port": 443, "catalog_name": ["catalog_name"]} inp_param2 = {"hostname": "host ip", "username": "username", "password": "password", "port": 443, "catalog_name": ["catalog_name"], "catalog_description": "desc", "source": "10.255.2.128:2607", "source_path": "source_path", "file_name": "file_name", "repository_type": "HTTPS", "repository_username": "repository_username", "repository_password": "repository_password", "repository_domain": "repository_domain", "check_certificate": True} inp_param3 = {"hostname": "host ip", "username": "username", "password": "password", "port": 443, "catalog_name": " ", "catalog_description": None} inp_param4 = {"hostname": "host ip", "username": "username", "password": "password", "port": 443, "catalog_name": ["catalog_name"], "catalog_description": "desc", "source": "10.255.2.128:2607", "source_path": "source_path", "file_name": "file_name", "repository_type": "DELL_ONLINE", "repository_username": "repository_username", "repository_password": "repository_password", "repository_domain": "repository_domain", "check_certificate": True} inp_param5 = {"hostname": "host ip", "username": "username", "password": "password", "port": 443, "catalog_name": ["catalog_name"], "catalog_description": "desc", "source_path": "source_path", "file_name": "file_name", "repository_type": "DELL_ONLINE", "repository_username": "repository_username", "repository_password": "repository_password", "repository_domain": "repository_domain", "check_certificate": True} out1 = {"Repository": {"Name": "catalog_name"}} out2 = {'Filename': 'file_name', 'SourcePath': 'source_path', 'Repository': {'Name': 'catalog_name', 'Description': 'desc', 'Source': '10.255.2.128:2607', 'RepositoryType': 'HTTPS', 'Username': 'repository_username', 'Password': 'repository_password', 'DomainName': 'repository_domain', 'CheckCertificate': True}} out3 = {"Repository": {"Name": " "}} out4 = {'Filename': 'file_name', 'SourcePath': 'source_path', 'Repository': {'Name': 'catalog_name', 'Description': 'desc', 'Source': '10.255.2.128:2607', 'RepositoryType': 'DELL_ONLINE', 'CheckCertificate': True}} out5 = {'Filename': 'file_name', 'SourcePath': 'source_path', 'Repository': {'Name': 'catalog_name', 'Description': 'desc', 'Source': 'downloads.dell.com', 'RepositoryType': 'DELL_ONLINE', 'CheckCertificate': True}} @pytest.mark.parametrize("params", [{"inp": inp_param1, "out": out1}, {"inp": inp_param2, "out": out2}, {"inp": inp_param3, "out": out3} ]) def test_ome_catalog_firmware__get_catalog_payload_success_case(self, params): payload = self.module._get_catalog_payload(params["inp"], params["inp"]["catalog_name"][0]) assert payload == params["out"] @pytest.mark.parametrize("exc_type", [IOError, ValueError, SSLError, TypeError, ConnectionError, HTTPError, URLError]) def test_ome_catalog_firmware_ome_catalog_main_exception_failure_case(self, exc_type, mocker, ome_default_args, ome_connection_catalog_mock, ome_response_mock): ome_default_args.update({"state": "absent", "catalog_name": "t1"}) ome_response_mock.status_code = 400 ome_response_mock.success = False json_str = to_text(json.dumps({"info": "error_details"})) if exc_type == URLError: mocker.patch(MODULE_PATH + 'check_existing_catalog', side_effect=exc_type("url open error")) result = self._run_module(ome_default_args) assert result["unreachable"] is True elif exc_type not in [HTTPError, SSLValidationError]: mocker.patch(MODULE_PATH + 'check_existing_catalog', side_effect=exc_type("exception message")) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True else: mocker.patch(MODULE_PATH + 'check_existing_catalog', side_effect=exc_type('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str))) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True assert 'msg' in result @pytest.mark.parametrize("params", [{"state": "present", "catalog_name": ["catalog_online2"]}, {"state": "present", "catalog_id": [34]}]) def test_ome_catalog_firmware_check_existing_catalog_case01(self, params, ome_connection_catalog_mock): ome_connection_catalog_mock.get_all_items_with_pagination.return_value = {"value": catalog_info["value"]} f_module = self.get_module_mock(params=params) catalog, all_catalog = self.module.check_existing_catalog(f_module, ome_connection_catalog_mock, params["state"]) assert catalog[0] == { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } assert all_catalog == {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"} @pytest.mark.parametrize("params", [{"state": "absent", "catalog_name": ["catalog_online2", "catalog_http4"]}, {"state": "absent", "catalog_id": [34, 30]}]) def test_ome_catalog_firmware_check_existing_catalog_case02(self, params, ome_connection_catalog_mock): ome_connection_catalog_mock.get_all_items_with_pagination.return_value = {"value": catalog_info["value"]} f_module = self.get_module_mock(params=params) catalog, all_catalog = self.module.check_existing_catalog(f_module, ome_connection_catalog_mock, params["state"]) assert catalog == [ { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(30)", "Id": 30, "Filename": "catalog.gz", "SourcePath": "catalog/catalog.gz", "Status": "Failed", "BaseLocation": None, "TaskId": 21449, "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 20, "Name": "catalog_http4", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "HTTP" } }, { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } ] assert all_catalog == {} @pytest.mark.parametrize("params", [{"state": "present", "catalog_name": ["catalog_online2"]}]) def test_ome_catalog_firmware_check_existing_catalog_case03(self, params, ome_connection_catalog_mock): ome_connection_catalog_mock.get_all_items_with_pagination.return_value = {"value": catalog_info["value"]} f_module = self.get_module_mock(params=params) catalog, all_catalog = self.module.check_existing_catalog(f_module, ome_connection_catalog_mock, params["state"], "catalog_online2") assert catalog[0] == { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } assert all_catalog == {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"} def test_ome_catalog_firmware_get_updated_catalog_info(self, ome_connection_catalog_mock): resp = { "@odata.type": "#UpdateService.Catalogs", "@odata.id": "/api/UpdateService/Catalogs(34)", "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Status": "Completed", "TaskId": 21453, "BaseLocation": "downloads.dell.com", "Schedule": { "StartTime": None, "EndTime": None, "Cron": "startnow" }, "BundlesCount": 173, "PredecessorIdentifier": "aaaaaa", "AssociatedBaselines": [], "Repository": { "@odata.type": "#UpdateService.Repository", "Id": 24, "Name": "catalog_online2", "Description": "catalog desc4", "Source": "downloads.dell.com", "DomainName": None, "Username": None, "Password": None, "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } f_module = self.get_module_mock(params={"state": "present", "catalog_name": "catalog_online2"}) ome_connection_catalog_mock.get_all_items_with_pagination.return_value = {"value": catalog_info["value"]} catalog = self.module.get_updated_catalog_info(f_module, ome_connection_catalog_mock, resp) assert catalog == resp @pytest.mark.parametrize("params", [{"mparams": {"state": "present", "job_wait_timeout": 10, "job_wait": True, "catalog_name": ["catalog_online2"]}}]) @pytest.mark.parametrize("action", ["created", "modified"]) def test_ome_catalog_firmware_exit_catalog(self, mocker, ome_connection_catalog_mock, params, action): ome_connection_catalog_mock.job_tracking.return_value = False, "message" mocker.patch(MODULE_PATH + 'time.sleep', return_value=None) f_module = self.get_module_mock(params=params["mparams"]) mocker.patch(MODULE_PATH + 'get_updated_catalog_info', return_value=catalog_resp) msg = CATALOG_UPDATED.format(operation=action) with pytest.raises(Exception) as err: self.module.exit_catalog(f_module, ome_connection_catalog_mock, catalog_resp, action, msg) assert err.value.args[0] == msg @pytest.mark.parametrize("params", [{"mparams": {"state": "present", "job_wait_timeout": 10, "job_wait": False, "catalog_name": ["catalog_online2"]}}]) @pytest.mark.parametrize("action", ["created", "modified"]) def test_ome_catalog_firmware_exit_catalog2(self, mocker, ome_connection_catalog_mock, params, action): mocker.patch(MODULE_PATH + 'time.sleep', return_value=None) f_module = self.get_module_mock(params=params["mparams"]) mocker.patch(MODULE_PATH + 'get_updated_catalog_info', return_value=catalog_resp) msg = CATALOG_UPDATED.format(operation=action) with pytest.raises(Exception) as err: self.module.exit_catalog(f_module, ome_connection_catalog_mock, catalog_resp, action, msg) assert err.value.args[0] == msg def test_ome_catalog_firmware_validate_dell_online_case01(self): all_catalog = {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"} f_module = self.get_module_mock(params={"catalog_name": ["catalog_online2"]}) self.module.validate_dell_online(all_catalog, f_module) def test_ome_catalog_firmware_validate_dell_online_case02(self): all_catalog = {"catalog_http4": "HTTP", "catalog_http3": "HTTP"} f_module = self.get_module_mock(params={"catalog_name": ["catalog_online2"]}) self.module.validate_dell_online(all_catalog, f_module) def test_ome_catalog_firmware_validate_dell_online_case03(self): all_catalog = {"catalog_online3": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"} f_module = self.get_module_mock(params={"catalog_name": ["catalog_online2"]}) with pytest.raises(Exception) as err: self.module.validate_dell_online(all_catalog, f_module) assert err.value.args[0] == DELL_ONLINE_EXISTS.format(catalog_name="catalog_online3") def test_ome_catalog_firmware_create_catalog(self, mocker, ome_response_mock, ome_connection_catalog_mock): f_module = self.get_module_mock(params={"catalog_name": ["catalog_name"]}) ome_response_mock.json_data = catalog_resp mocker.patch(MODULE_PATH + 'exit_catalog', return_value=catalog_resp) self.module.create_catalog(f_module, ome_connection_catalog_mock) def test_ome_catalog_firmware_get_current_catalog_settings(self): payload = self.module.get_current_catalog_settings(catalog_resp) assert payload == {'Filename': 'catalog.xml', 'SourcePath': 'catalog/catalog.gz', 'Repository': {'Name': 'catalog_online2', 'Id': 24, 'Description': 'catalog desc4', 'RepositoryType': 'DELL_ONLINE', 'Source': 'downloads.dell.com', 'CheckCertificate': False}} def test_ome_catalog_firmware_modify_catalog_case01(self, mocker, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_online2"], "new_catalog_name": "catalog_http3"}) modify_payload = { "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, } } mocker.patch(MODULE_PATH + '_get_catalog_payload', return_value=modify_payload) with pytest.raises(Exception) as err: self.module.modify_catalog(f_module, ome_connection_catalog_mock, [catalog_resp], {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"}) assert err.value.args[0] == CATALOG_EXISTS.format(new_name="catalog_http3") def test_ome_catalog_firmware_modify_catalog_case02(self, mocker, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_online2"], "new_catalog_name": "catalog_http10"}) modify_payload = { "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, "RepositoryType": "NFS" } } current_payload = { "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Id": 11, "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } mocker.patch(MODULE_PATH + '_get_catalog_payload', return_value=modify_payload) mocker.patch(MODULE_PATH + 'get_current_catalog_settings', return_value=current_payload) with pytest.raises(Exception) as err: self.module.modify_catalog(f_module, ome_connection_catalog_mock, [catalog_resp], {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"}) assert err.value.args[0] == "Repository type cannot be changed to another repository type." def test_ome_catalog_firmware_modify_catalog_case03(self, mocker, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_online2"], "new_catalog_name": "catalog_http10"}, check_mode=True) modify_payload = { "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": True, "RepositoryType": "DELL_ONLINE" } } # current_payload = { # "Id": 34, # "Filename": "catalog.xml", # "SourcePath": "catalog/catalog.gz", # "Repository": { # "Id": 11, # "Name": "catalog_online2", # "Description": "catalog desc4", # "CheckCertificate": True, # "RepositoryType": "DELL_ONLINE" # } # } mocker.patch(MODULE_PATH + '_get_catalog_payload', return_value=modify_payload) with pytest.raises(Exception) as err: self.module.modify_catalog(f_module, ome_connection_catalog_mock, [catalog_resp], {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"}) assert err.value.args[0] == CHECK_MODE_CHANGE_FOUND_MSG @pytest.mark.parametrize("check_mode", [True, False]) def test_ome_catalog_firmware_modify_catalog_case04(self, check_mode, mocker, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_online2"], "new_catalog_name": "catalog_online2"}, check_mode=check_mode) modify_payload = { "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } current_payload = { "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Id": 11, "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } mocker.patch(MODULE_PATH + '_get_catalog_payload', return_value=modify_payload) mocker.patch(MODULE_PATH + 'get_current_catalog_settings', return_value=current_payload) with pytest.raises(Exception) as err: self.module.modify_catalog(f_module, ome_connection_catalog_mock, [catalog_resp], {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"}) assert err.value.args[0] == CHECK_MODE_CHANGE_NOT_FOUND_MSG def test_ome_catalog_firmware_modify_catalog_case05(self, mocker, ome_connection_catalog_mock, ome_response_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_online2"], "new_catalog_name": "catalog_http10"}, check_mode=False) modify_payload = { "Id": 34, "Filename": "catalog.xml", "SourcePath": "catalog/catalog.gz", "Repository": { "Name": "catalog_online2", "Description": "catalog desc4", "CheckCertificate": False, "RepositoryType": "DELL_ONLINE" } } mocker.patch(MODULE_PATH + '_get_catalog_payload', return_value=modify_payload) ome_response_mock.json_data = catalog_resp mocker.patch(MODULE_PATH + 'exit_catalog', return_value=None) self.module.modify_catalog(f_module, ome_connection_catalog_mock, [catalog_resp], {"catalog_online2": "DELL_ONLINE", "catalog_http4": "HTTP", "catalog_http3": "HTTP"}) def test_ome_catalog_firmware_validate_delete_operation_case1(self, ome_response_mock, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_http3", "catalog_online2"]}, check_mode=False) ome_response_mock.json_data = { "@odata.context": "/api/$metadata#JobService.Job", "@odata.type": "#JobService.Job", "@odata.id": "/api/JobService/Jobs(10025)", "Id": 10025, "JobName": "Default Console Update Execution Task", "JobDescription": "Default Console Update Execution Task", "State": "Enabled", "CreatedBy": "system", "Targets": [], "Params": [], "LastRunStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2051, "Name": "NotRun" }, "JobType": { "@odata.type": "#JobService.JobType", "Id": 124, "Name": "ConsoleUpdateExecution_Task", "Internal": False }, "JobStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2080, "Name": "New" }, } with pytest.raises(Exception) as err: self.module.validate_delete_operation(ome_connection_catalog_mock, f_module, catalog_info["value"], [1, 2]) assert err.value.args[0] == CATALOG_BASELINE_ATTACHED def test_ome_catalog_firmware_validate_delete_operation_case2(self, ome_response_mock, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_http3", "catalog_online2"]}, check_mode=True) ome_response_mock.json_data = { "@odata.context": "/api/$metadata#JobService.Job", "@odata.type": "#JobService.Job", "@odata.id": "/api/JobService/Jobs(10025)", "Id": 10025, "JobName": "Default Console Update Execution Task", "JobDescription": "Default Console Update Execution Task", "State": "Enabled", "CreatedBy": "system", "Targets": [], "Params": [], "LastRunStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2051, "Name": "NotRun" }, "JobType": { "@odata.type": "#JobService.JobType", "Id": 124, "Name": "ConsoleUpdateExecution_Task", "Internal": False }, "JobStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2080, "Name": "New" }, } catalog_info1 = [catalog_resp] with pytest.raises(Exception) as err: self.module.validate_delete_operation(ome_connection_catalog_mock, f_module, catalog_info1, [34]) assert err.value.args[0] == CHECK_MODE_CHANGE_FOUND_MSG def test_ome_catalog_firmware_validate_delete_operation_case3(self, ome_response_mock, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_http3", "catalog_online2"]}, check_mode=False) ome_response_mock.json_data = { "@odata.context": "/api/$metadata#JobService.Job", "@odata.type": "#JobService.Job", "@odata.id": "/api/JobService/Jobs(10025)", "Id": 10025, "JobName": "Default Console Update Execution Task", "JobDescription": "Default Console Update Execution Task", "State": "Enabled", "CreatedBy": "system", "Targets": [], "Params": [], "LastRunStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2051, "Name": "NotRun" }, "JobType": { "@odata.type": "#JobService.JobType", "Id": 124, "Name": "ConsoleUpdateExecution_Task", "Internal": False }, "JobStatus": { "@odata.type": "#JobService.JobStatus", "Id": 2080, "Name": "New" }, } catalog_info1 = [catalog_resp] self.module.validate_delete_operation(ome_connection_catalog_mock, f_module, catalog_info1, [34]) @pytest.mark.parametrize("check_mode", [True, False]) def test_ome_catalog_firmware_validate_delete_operation_case4(self, check_mode, ome_response_mock, ome_connection_catalog_mock): f_module = self.get_module_mock( params={"catalog_name": ["catalog_http3", "catalog_online2"]}, check_mode=check_mode) with pytest.raises(Exception) as err: self.module.validate_delete_operation(ome_connection_catalog_mock, f_module, [], []) assert err.value.args[0] == CHECK_MODE_CHANGE_NOT_FOUND_MSG def test_ome_catalog_firmware_delete_catalog(self, mocker, ome_connection_catalog_mock, ome_response_mock): mocker.patch(MODULE_PATH + 'validate_delete_operation', return_value=None) ome_response_mock.json_data = [1, 2] f_module = self.get_module_mock(params={"state": "absent", "catalog_id": [1, 2]}) with pytest.raises(Exception) as err: self.module.delete_catalog(f_module, ome_connection_catalog_mock, catalog_info["value"]) assert err.value.args[0] == CATALOG_DEL_SUCCESS @pytest.mark.parametrize("exc_type", [IOError, ValueError, SSLError, TypeError, ConnectionError, HTTPError, URLError]) def test_ome_catalog_firmware_main_exception_failure_case(self, exc_type, mocker, ome_default_args, ome_connection_catalog_mock, ome_response_mock): ome_default_args.update({"catalog_name": "catalog1", "repository_type": "HTTPS"}) ome_response_mock.status_code = 400 ome_response_mock.success = False json_str = to_text(json.dumps({"info": "error_details"})) if exc_type == URLError: mocker.patch(MODULE_PATH + 'validate_names', side_effect=exc_type("url open error")) result = self._run_module(ome_default_args) assert result["unreachable"] is True elif exc_type not in [HTTPError, SSLValidationError]: mocker.patch(MODULE_PATH + 'validate_names', side_effect=exc_type("exception message")) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True else: mocker.patch(MODULE_PATH + 'validate_names', side_effect=exc_type('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str))) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True assert 'msg' in result @pytest.mark.parametrize("param", [{"state": "absent", "catalog_id": [1, 2]}, {"state": "absent", "catalog_name": ["abc", "xyz"]}]) def test_ome_catalog_firmware_validate_names(self, param): f_module = self.get_module_mock(params=param) self.module.validate_names("absent", f_module) @pytest.mark.parametrize("param", [{"state": "present", "catalog_id": [1, 2]}, {"state": "present", "catalog_name": ["abc", "xyz"]}]) def test_ome_catalog_firmware_validate_names_exception_case(self, param): f_module = self.get_module_mock(params=param) with pytest.raises(Exception) as err: self.module.validate_names("present", f_module) assert err.value.args[0] == NAMES_ERROR def test_ome_catalog_firmware_argument_exception_case1(self, ome_default_args): ome_default_args.update({"catalog_name": "t1"}) result = self._run_module_with_fail_json(ome_default_args) assert result["msg"] == "state is present but all of the following are missing: repository_type" def test_ome_catalog_firmware_argument_exception_case2(self, ome_default_args): ome_default_args.update({"catalog_id": 1}) result = self._run_module_with_fail_json(ome_default_args) assert result["msg"] == "state is present but all of the following are missing: repository_type" def test_ome_catalog_firmware_argument_exception_case3(self, ome_default_args): result = self._run_module_with_fail_json(ome_default_args) assert result["msg"] == "one of the following is required: catalog_name, catalog_id" def test_ome_catalog_firmware_argument_exception_case4(self, ome_default_args): ome_default_args.update({"repository_type": "HTTPS", "catalog_name": "t1", "catalog_id": 1}) result = self._run_module_with_fail_json(ome_default_args) assert result["msg"] == "parameters are mutually exclusive: catalog_name|catalog_id"
48.785459
126
0.566319
3,867
40,931
5.691492
0.089992
0.029488
0.039075
0.04689
0.849153
0.827252
0.803989
0.789632
0.756736
0.73529
0
0.017398
0.310523
40,931
838
127
48.843675
0.762482
0.013144
0
0.689119
0
0
0.293909
0.038516
0
0
0
0
0.044041
1
0.042746
false
0.024611
0.012953
0
0.073834
0.001295
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
6e3d9fd67b5f7747ab5f342e4ebc73ac2c9bcc92
12,420
py
Python
metric.py
ooooverflow/DigestPath2019
db7b6a0a86bffbe8f44b5d6aa72b4c76e982c0b8
[ "Apache-2.0" ]
1
2021-04-22T02:38:38.000Z
2021-04-22T02:38:38.000Z
metric.py
ooooverflow/DigestPath2019
db7b6a0a86bffbe8f44b5d6aa72b4c76e982c0b8
[ "Apache-2.0" ]
1
2020-02-18T12:09:10.000Z
2021-04-24T16:28:53.000Z
metric.py
ooooverflow/DigestPath2019
db7b6a0a86bffbe8f44b5d6aa72b4c76e982c0b8
[ "Apache-2.0" ]
null
null
null
import numpy as np def compute_overlap(a, b): """ Parameters ---------- a: (N, 4) ndarray of float b: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]) iw = np.minimum(np.expand_dims(a[:, 2], axis=1), b[:, 2]) - np.maximum(np.expand_dims(a[:, 0], 1), b[:, 0]) ih = np.minimum(np.expand_dims(a[:, 3], axis=1), b[:, 3]) - np.maximum(np.expand_dims(a[:, 1], 1), b[:, 1]) iw = np.maximum(iw, 0) ih = np.maximum(ih, 0) ua = np.expand_dims((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), axis=1) + area - iw * ih ua = np.maximum(ua, np.finfo(float).eps) intersection = iw * ih return intersection / ua def _compute_ap(recall, precision): """ Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. # Arguments recall: The recall curve (list). precision: The precision curve (list). # Returns The average precision as computed in py-faster-rcnn. """ # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], recall, [1.])) mpre = np.concatenate(([0.], precision, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def compute_froc(true_positives, false_positives, recall, num_pic): for index in range(len(true_positives)): tp = true_positives[index] fp = false_positives[index] r = recall[index] def detection_metric(pred_bboxes, gt_bboxes, pred_scores, iou_threshold=0.3, score_threshold=0.5): ''' :param pred_bboxes: list -> [num_pic, num_box, 4] (sorted already, descending order) :param gt_bboxes: list -> [num_pic, num_box, 4] :param pred_scores: list -> [num_pic, num_box] :return: ''' false_positives = np.zeros((0,)) true_positives = np.zeros((0,)) scores = np.zeros((0,)) num_annotations = 0.0 for i in range(len(pred_bboxes)): detections = pred_bboxes[i] annotations = np.array(gt_bboxes[i]) num_annotations += len(annotations) detected_annotations = [] for j, d in enumerate(detections): score = pred_scores[i][j] if score < score_threshold: # score has been sorted in descending order break scores = np.append(scores, score) overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations) assigned_annotation = np.argmax(overlaps, axis=1) max_overlap = overlaps[0, assigned_annotation] if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations: false_positives = np.append(false_positives, 0) true_positives = np.append(true_positives, 1) detected_annotations.append(assigned_annotation) else: false_positives = np.append(false_positives, 1) true_positives = np.append(true_positives, 0) indices = np.argsort(-scores) false_positives = false_positives[indices] true_positives = true_positives[indices] # compute false positives and true positives false_positives = np.cumsum(false_positives) true_positives = np.cumsum(true_positives) # compute recall and precision recall = true_positives / num_annotations precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps) # compute average precision average_precision = _compute_ap(recall, precision) return average_precision, recall, precision def calculate_metric_final(pred_bboxes, gt_bboxes, pred_scores, iou_threshold=0.3, score_threshold=0.5): ''' :param pred_bboxes: list -> [num_pic, num_box, 4] (sorted already, descending order) :param gt_bboxes: list -> [num_pic, num_box, 4] :param pred_scores: list -> [num_pic, num_box] :return: ''' false_positives = np.zeros((0,)) true_positives = np.zeros((0,)) scores = np.zeros((0,)) num_annotations = 0.0 # scores of predict box in negative image scores_normal_region = np.zeros((0,)) num_pos = 0 normal_regions = 0 FPs = 0 for i in range(len(pred_bboxes)): detections = pred_bboxes[i] annotations = np.array(gt_bboxes[i]) num_annotations += len(annotations) if len(annotations) != 0: num_pos += 1 # positive region # calculate precision and recall detected_annotations = [] for j, d in enumerate(detections): score = pred_scores[i][j] if score < score_threshold: # score has been sorted in descending order break scores = np.append(scores, score) overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations) assigned_annotation = np.argmax(overlaps, axis=1) max_overlap = overlaps[0, assigned_annotation] if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations: false_positives = np.append(false_positives, 0) true_positives = np.append(true_positives, 1) detected_annotations.append(assigned_annotation) else: false_positives = np.append(false_positives, 1) true_positives = np.append(true_positives, 0) else: # negative region (normal region) # calculate FPs normal_regions += 1 for j, d in enumerate(detections): score = pred_scores[i][j] if score < score_threshold: # score has been sorted in descending order break FPs += 1 scores_normal_region = np.append(scores_normal_region, score) indices = np.argsort(-scores) scores = scores[indices] false_positives = false_positives[indices] true_positives = true_positives[indices] indices = np.argsort(-scores_normal_region) scores_normal_region = scores_normal_region[indices] # compute false positives and true positives false_positives = np.cumsum(false_positives) true_positives = np.cumsum(true_positives) # compute recall and precision recall = true_positives / num_annotations if len(recall) == 0: recall = [0] precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps) if len(precision) == 0: precision = [0] # compute FROC fps_list = [1, 2, 4, 8, 16, 32] recall_list = [] for fps in fps_list: total_fps_num = fps * normal_regions if total_fps_num >= len(scores_normal_region): recall_list.append(float(recall[-1])) else: score_min = scores_normal_region[total_fps_num-1] score_index = np.where(scores>=score_min)[0] if score_index.shape[0] == 0: recall_list.append(0) else: score_index = score_index[-1] recall_list.append(float(recall[score_index])) froc = np.mean(recall_list) FPs = float(FPs / normal_regions) FPs = max(100 - FPs, 0) return recall, precision, froc, FPs def calculate_metric_final_new(pred_bboxes, gt_bboxes, pred_scores, iou_threshold=0.3, score_threshold=0.5): ''' :param pred_bboxes: list -> [num_pic, num_box, 4] (sorted already, descending order) :param gt_bboxes: list -> [num_pic, num_box, 4] :param pred_scores: list -> [num_pic, num_box] :return: ''' false_positives = np.zeros((0,)) true_positives = np.zeros((0,)) scores = np.zeros((0,)) num_annotations = 0.0 # scores of predict box in negative image scores_normal_region = np.zeros((0,)) num_pos = 0 normal_regions = 0 FPs = 0 for i in range(len(pred_bboxes)): detections = pred_bboxes[i] annotations = np.array(gt_bboxes[i]) num_annotations += len(annotations) if len(annotations) != 0: num_pos += 1 # positive region # calculate precision and recall detected_annotations = [] for j, d in enumerate(detections): score = pred_scores[i][j] if score < 0.05: # score has been sorted in descending order break scores = np.append(scores, score) overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations) assigned_annotation = np.argmax(overlaps, axis=1) max_overlap = overlaps[0, assigned_annotation] if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations: false_positives = np.append(false_positives, 0) true_positives = np.append(true_positives, 1) detected_annotations.append(assigned_annotation) else: false_positives = np.append(false_positives, 1) true_positives = np.append(true_positives, 0) else: # negative region (normal region) # calculate FPs normal_regions += 1 for j, d in enumerate(detections): score = pred_scores[i][j] if score < 0.05: # score has been sorted in descending order break FPs += 1 scores_normal_region = np.append(scores_normal_region, score) indices = np.argsort(-scores) scores = scores[indices] false_positives = false_positives[indices] true_positives = true_positives[indices] indices = np.argsort(-scores_normal_region) scores_normal_region = scores_normal_region[indices] # compute false positives and true positives false_positives = np.cumsum(false_positives) true_positives = np.cumsum(true_positives) # compute recall and precision recall = true_positives / num_annotations if len(recall) == 0: recall = np.array([0]) precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps) if len(precision) == 0: precision = np.array([0]) # index where precision greater equal 0.2 index_record = np.where(precision >= 0.2)[0] if index_record.shape[0] != 0: index_record = index_record[-1] # recall, precision, FPs when precision is 0.2 recall_record = recall[:index_record+1] precision_record = precision[:index_record+1] score_record = scores[:index_record+1] else: recall_record = [0] precision_record = [0] score_record = [0] scores_normal_region_record = scores_normal_region[scores_normal_region > score_record[-1]] FPs_record = scores_normal_region_record.shape[0] FPs_record = float(FPs_record / normal_regions) FPs_record = max(100 - FPs_record, 0) # compute FROC when precision is 0.2 fps_list = [1, 2, 4, 8, 16, 32] recall_list = [] for fps in fps_list: total_fps_num = fps * normal_regions if total_fps_num >= len(scores_normal_region_record): recall_list.append(float(recall_record[-1])) else: score_min = scores_normal_region_record[total_fps_num - 1] score_index = np.where(score_record >= score_min)[0] if score_index.shape[0] == 0: recall_list.append(0) else: score_index = score_index[-1] recall_list.append(float(recall_record[score_index])) froc_record = np.mean(recall_list) recall = recall[scores > score_threshold] precision = precision[scores > score_threshold] scores = scores[scores > score_threshold] if recall.shape[0] == 0: recall = np.append(recall, 0) if precision.shape[0] == 0: precision = np.append(precision, 0) if scores.shape[0] == 0: scores = np.append(scores, 0) scores_normal_region = scores_normal_region[scores_normal_region > score_threshold] # compute FROC fps_list = [1, 2, 4, 8, 16, 32] recall_list = [] for fps in fps_list: total_fps_num = fps * normal_regions if total_fps_num >= len(scores_normal_region): recall_list.append(float(recall[-1])) else: score_min = scores_normal_region[total_fps_num-1] score_index = np.where(scores>=score_min)[0] if score_index.shape[0] == 0: recall_list.append(0) else: score_index = score_index[-1] recall_list.append(float(recall[score_index])) froc = np.mean(recall_list) FPs = float(len(scores_normal_region) / normal_regions) FPs = max(100 - FPs, 0) return recall, precision, froc, FPs, recall_record, precision_record, froc_record, FPs_record, score_record
33.387097
112
0.667472
1,700
12,420
4.665882
0.096471
0.068835
0.059002
0.01475
0.750756
0.744579
0.728568
0.71886
0.715204
0.708396
0
0.022176
0.219404
12,420
372
113
33.387097
0.795977
0.169002
0
0.723849
0
0
0
0
0
0
0
0
0
1
0.025105
false
0
0.004184
0
0.050209
0
0
0
0
null
0
0
0
0
1
1
1
1
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
6
281c43516c74dbc7e5b43ed485e8e3bbe48b6072
293
py
Python
client/swagger_client/api/__init__.py
icclab/MasterMind-ServiceManager
d8e0013218bb7a5fa16d1e3c5cff06a6854815f1
[ "Apache-2.0" ]
null
null
null
client/swagger_client/api/__init__.py
icclab/MasterMind-ServiceManager
d8e0013218bb7a5fa16d1e3c5cff06a6854815f1
[ "Apache-2.0" ]
null
null
null
client/swagger_client/api/__init__.py
icclab/MasterMind-ServiceManager
d8e0013218bb7a5fa16d1e3c5cff06a6854815f1
[ "Apache-2.0" ]
2
2018-02-02T17:02:27.000Z
2021-06-29T07:42:24.000Z
from __future__ import absolute_import # flake8: noqa # import apis into api package from swagger_client.api.network_api import NetworkApi from swagger_client.api.stack_api import StackApi from swagger_client.api.swarm_api import SwarmApi from swagger_client.api.volume_api import VolumeApi
29.3
53
0.856655
44
293
5.409091
0.454545
0.184874
0.285714
0.336134
0
0
0
0
0
0
0
0.003817
0.105802
293
9
54
32.555556
0.90458
0.139932
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
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
1
0
1
0
1
0
0
6
2856dc3f258c5e115ab67fe84e608d17bc8c509d
49
py
Python
src/stub_module.py
grzegorznowak/tensorflow-rrn-server
1011ea465c298263fa177ba34ba0db0897985d8f
[ "Unlicense" ]
null
null
null
src/stub_module.py
grzegorznowak/tensorflow-rrn-server
1011ea465c298263fa177ba34ba0db0897985d8f
[ "Unlicense" ]
4
2018-02-12T11:13:54.000Z
2018-02-12T20:24:23.000Z
src/stub_module.py
grzegorznowak/tensorflow-rrn-server
1011ea465c298263fa177ba34ba0db0897985d8f
[ "Unlicense" ]
1
2018-02-11T23:19:47.000Z
2018-02-11T23:19:47.000Z
def justAStubFunctionForATest(): return 1234
24.5
33
0.77551
4
49
9.5
1
0
0
0
0
0
0
0
0
0
0
0.097561
0.163265
49
2
34
24.5
0.829268
0
0
0
0
0
0
0
0
0
0
0
0
1
0.5
true
0
0
0.5
1
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
1
1
0
0
1
0
0
0
6
95693e1e7492b0845c1a7d4c968b5a986cddaa6b
31
py
Python
projects/thesis/continuous/custom/continuous/continuous_conv/__init__.py
cpark90/rrrcnn
ba66cc391265be76fa3896b66459ff7241b47972
[ "Apache-2.0" ]
null
null
null
projects/thesis/continuous/custom/continuous/continuous_conv/__init__.py
cpark90/rrrcnn
ba66cc391265be76fa3896b66459ff7241b47972
[ "Apache-2.0" ]
null
null
null
projects/thesis/continuous/custom/continuous/continuous_conv/__init__.py
cpark90/rrrcnn
ba66cc391265be76fa3896b66459ff7241b47972
[ "Apache-2.0" ]
null
null
null
from .continuous_conv import *
15.5
30
0.806452
4
31
6
1
0
0
0
0
0
0
0
0
0
0
0
0.129032
31
1
31
31
0.888889
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
957608c2134577c8f3f06313eb7155b55d45d19a
27
py
Python
src_old/__init__.py
m0000Amir/BST_BS_types_set
c455aaafa632a0de8a1075262097f042993721c7
[ "MIT" ]
null
null
null
src_old/__init__.py
m0000Amir/BST_BS_types_set
c455aaafa632a0de8a1075262097f042993721c7
[ "MIT" ]
2
2020-11-08T19:48:23.000Z
2022-03-12T00:58:34.000Z
src_old/__init__.py
m0000Amir/BST_BS_types_set
c455aaafa632a0de8a1075262097f042993721c7
[ "MIT" ]
null
null
null
# TODO: remove this package
27
27
0.777778
4
27
5.25
1
0
0
0
0
0
0
0
0
0
0
0
0.148148
27
1
27
27
0.913043
0.925926
0
null
0
null
0
0
null
0
0
1
null
1
null
true
0
0
null
null
null
1
1
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
1
0
0
0
1
0
0
0
0
0
0
6
95c5c78e0bfd9662b3a267387462a41d0b30251e
8,021
py
Python
DepthGAN/networks/generator_vggnet.py
sharanramjee/single-image-stereo-depth-estimation
2ec69a3980171189b75c996eca72c053fa6a5fd8
[ "MIT" ]
null
null
null
DepthGAN/networks/generator_vggnet.py
sharanramjee/single-image-stereo-depth-estimation
2ec69a3980171189b75c996eca72c053fa6a5fd8
[ "MIT" ]
null
null
null
DepthGAN/networks/generator_vggnet.py
sharanramjee/single-image-stereo-depth-estimation
2ec69a3980171189b75c996eca72c053fa6a5fd8
[ "MIT" ]
null
null
null
from networks.blocks import * class VggNetMD(nn.Module): def __init__(self, num_in_layers, num_out_layers=2, normalize=None): super(VggNetMD, self).__init__() # encoder self.conv1 = ConvBlock(num_in_layers, 32, 7, normalize=normalize) # H/2 self.conv2 = ConvBlock(32, 64, 5, normalize=normalize) # H/4 self.conv3 = ConvBlock(64, 128, 3, normalize=normalize) # H/8 self.conv4 = ConvBlock(128, 256, 3, normalize=normalize) # H/16 self.conv5 = ConvBlock(256, 512, 3, normalize=normalize) # H/32 self.conv6 = ConvBlock(512, 512, 3, normalize=normalize) # H/64 self.conv7 = ConvBlock(512, 512, 3, normalize=normalize) # H/128 # decoder self.upconv7 = Upconv(512, 512, 3, 2, normalize=normalize) self.iconv7 = Conv(512 + 512, 512, 3, 1, normalize=normalize) self.upconv6 = Upconv(512, 512, 3, 2, normalize=normalize) self.iconv6 = Conv(512 + 512, 512, 3, 1, normalize=normalize) self.upconv5 = Upconv(512, 256, 3, 2, normalize=normalize) self.iconv5 = Conv(256 + 256, 256, 3, 1, normalize=normalize) self.upconv4 = Upconv(256, 128, 3, 2, normalize=normalize) self.iconv4 = Conv(128 + 128, 128, 3, 1, normalize=normalize) self.disp4_layer = GetDisp(128, num_out_layers=num_out_layers) self.upconv3 = Upconv(128, 64, 3, 2, normalize=normalize) self.iconv3 = Conv(64 + 64 + num_out_layers, 64, 3, 1, normalize=normalize) self.disp3_layer = GetDisp(64, num_out_layers=num_out_layers) self.upconv2 = Upconv(64, 32, 3, 2, normalize=normalize) self.iconv2 = Conv(32 + 32 + num_out_layers, 32, 3, 1, normalize=normalize) self.disp2_layer = GetDisp(32, num_out_layers=num_out_layers) self.upconv1 = Upconv(32, 16, 3, 2, normalize=normalize) self.iconv1 = Conv(16 + num_out_layers, 16, 3, 1, normalize=normalize) self.disp1_layer = GetDisp(16, num_out_layers=num_out_layers) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform_(m.weight) def forward(self, x): # encoder x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(x2) x4 = self.conv4(x3) x5 = self.conv5(x4) x6 = self.conv6(x5) x7 = self.conv7(x6) # skips skip1 = x1 skip2 = x2 skip3 = x3 skip4 = x4 skip5 = x5 skip6 = x6 # decoder upconv7 = self.upconv7(x7) concat7 = torch.cat((upconv7, skip6), 1) iconv7 = self.iconv7(concat7) upconv6 = self.upconv6(iconv7) concat6 = torch.cat((upconv6, skip5), 1) iconv6 = self.iconv6(concat6) upconv5 = self.upconv5(iconv6) concat5 = torch.cat((upconv5, skip4), 1) iconv5 = self.iconv5(concat5) upconv4 = self.upconv4(iconv5) concat4 = torch.cat((upconv4, skip3), 1) iconv4 = self.iconv4(concat4) self.disp4 = self.disp4_layer(iconv4) self.udisp4 = nn.functional.interpolate(self.disp4, scale_factor=2, mode='bilinear', align_corners=True) upconv3 = self.upconv3(iconv4) concat3 = torch.cat((upconv3, skip2, self.udisp4), 1) iconv3 = self.iconv3(concat3) self.disp3 = self.disp3_layer(iconv3) self.udisp3 = nn.functional.interpolate(self.disp3, scale_factor=2, mode='bilinear', align_corners=True) upconv2 = self.upconv2(iconv3) concat2 = torch.cat((upconv2, skip1, self.udisp3), 1) iconv2 = self.iconv2(concat2) self.disp2 = self.disp2_layer(iconv2) self.udisp2 = nn.functional.interpolate(self.disp2, scale_factor=2, mode='bilinear', align_corners=True) upconv1 = self.upconv1(iconv2) concat1 = torch.cat((upconv1, self.udisp2), 1) iconv1 = self.iconv1(concat1) self.disp1 = self.disp1_layer(iconv1) return self.disp1, self.disp2, self.disp3, self.disp4 class VggNetSuper(nn.Module): def __init__(self, num_in_layers, num_out_layers=2, normalize=None): super(VggNetSuper, self).__init__() # encoder self.conv1 = ConvBlock(num_in_layers, 32, 7, normalize=normalize) # H/2 self.conv2 = ConvBlock(32, 64, 5, normalize=normalize) # H/4 self.conv3 = ConvBlock(64, 128, 3, normalize=normalize) # H/8 self.conv4 = ConvBlock(128, 256, 3, normalize=normalize) # H/16 self.conv5 = ConvBlock(256, 512, 3, normalize=normalize) # H/32 self.conv6 = ConvBlock(512, 512, 3, normalize=normalize) # H/64 self.conv7 = ConvBlock(512, 512, 3, normalize=normalize) # H/128 # decoder self.upconv7 = Upconv(512, 512, 3, 2, normalize=normalize) self.iconv7 = Conv(512 + 512, 512, 3, 1, normalize=normalize) self.upconv6 = Upconv(512, 512, 3, 2, normalize=normalize) self.iconv6 = Conv(512 + 512, 512, 3, 1, normalize=normalize) self.upconv5 = Upconv(512, 256, 3, 2, normalize=normalize) self.iconv5 = Conv(256 + 256, 256, 3, 1, normalize=normalize) self.upconv4 = Upconv(256, 128, 3, 2, normalize=normalize) self.iconv4 = Conv(128 + 128, 128, 3, 1, normalize=normalize) self.upconv3 = Upconv(128, 64, 3, 2, normalize=normalize) self.iconv3 = Conv(64 + 64, 64, 3, 1, normalize=normalize) self.upconv2 = Upconv(64, 32, 3, 2, normalize=normalize) self.iconv2 = Conv(32 + 32, 32, 3, 1, normalize=normalize) self.upconv1 = Upconv(32, 16, 3, 2, normalize=normalize) self.iconv1 = Conv(16, 16, 3, 1, normalize=normalize) self.disp1_layer = GetDisp(16, num_out_layers=num_out_layers) self.upconv0 = Upconv(16, 8, 3, 2, normalize=normalize) self.iconv0 = Conv(8 + num_out_layers, 8, 3, 1, normalize=normalize) self.disp0_layer = GetDisp(8, num_out_layers=num_out_layers) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform_(m.weight) def forward(self, x): # encoder x1 = self.conv1(x) x2 = self.conv2(x1) x3 = self.conv3(x2) x4 = self.conv4(x3) x5 = self.conv5(x4) x6 = self.conv6(x5) x7 = self.conv7(x6) # skips skip1 = x1 skip2 = x2 skip3 = x3 skip4 = x4 skip5 = x5 skip6 = x6 # decoder upconv7 = self.upconv7(x7) concat7 = torch.cat((upconv7, skip6), 1) iconv7 = self.iconv7(concat7) upconv6 = self.upconv6(iconv7) concat6 = torch.cat((upconv6, skip5), 1) iconv6 = self.iconv6(concat6) upconv5 = self.upconv5(iconv6) concat5 = torch.cat((upconv5, skip4), 1) iconv5 = self.iconv5(concat5) upconv4 = self.upconv4(iconv5) concat4 = torch.cat((upconv4, skip3), 1) iconv4 = self.iconv4(concat4) upconv3 = self.upconv3(iconv4) concat3 = torch.cat((upconv3, skip2), 1) iconv3 = self.iconv3(concat3) upconv2 = self.upconv2(iconv3) concat2 = torch.cat((upconv2, skip1), 1) iconv2 = self.iconv2(concat2) upconv1 = self.upconv1(iconv2) iconv1 = self.iconv1(upconv1) self.disp1 = self.disp1_layer(iconv1) self.udisp1 = nn.functional.interpolate(self.disp1, scale_factor=2, mode='bilinear', align_corners=True) upconv0 = self.upconv0(iconv1) concat0 = torch.cat((upconv0, self.udisp1), 1) iconv0 = self.iconv0(concat0) self.disp0 = self.disp0_layer(iconv0) # Unlike the other generators, return the smallest disparity first, # so we can use the 256 x 512 disparities during test times without problems. return self.disp1, self.disp0
39.707921
112
0.599801
1,021
8,021
4.629775
0.131244
0.167548
0.139623
0.063465
0.806008
0.775545
0.742966
0.726888
0.69304
0.649884
0
0.116331
0.280888
8,021
201
113
39.905473
0.70319
0.035282
0
0.748299
0
0
0.00415
0
0
0
0
0
0
1
0.027211
false
0
0.006803
0
0.061224
0
0
0
0
null
0
0
0
1
1
1
1
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
6
95eeb0ab46a0d71a2ad97ee9e754c560df687d03
48,790
py
Python
diffcal3.py
Anshnrag02/Calculator-Calculus
16e099c4a505e1757b661c1fe0db74eac320bc94
[ "MIT" ]
null
null
null
diffcal3.py
Anshnrag02/Calculator-Calculus
16e099c4a505e1757b661c1fe0db74eac320bc94
[ "MIT" ]
null
null
null
diffcal3.py
Anshnrag02/Calculator-Calculus
16e099c4a505e1757b661c1fe0db74eac320bc94
[ "MIT" ]
null
null
null
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_dniwindow(object): def setupUi(self, dniwindow): dniwindow.setObjectName("dniwindow") dniwindow.resize(900, 768) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(dniwindow.sizePolicy().hasHeightForWidth()) dniwindow.setSizePolicy(sizePolicy) dniwindow.setAutoFillBackground(False) dniwindow.setStyleSheet("background-color: rgb(26, 26, 26);") self.diffandintcal = QtWidgets.QWidget(dniwindow) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.diffandintcal.sizePolicy().hasHeightForWidth()) self.diffandintcal.setSizePolicy(sizePolicy) self.diffandintcal.setStyleSheet("\n" "QMainWindow::centralWidget()->layout()->setContentsMargins(0,0,0,0);") self.diffandintcal.setObjectName("diffandintcal") self.gridLayout_7 = QtWidgets.QGridLayout(self.diffandintcal) self.gridLayout_7.setObjectName("gridLayout_7") self.dframe_main = QtWidgets.QFrame(self.diffandintcal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dframe_main.sizePolicy().hasHeightForWidth()) self.dframe_main.setSizePolicy(sizePolicy) self.dframe_main.setStyleSheet("background-color: rgb(26,26,26);") self.dframe_main.setFrameShape(QtWidgets.QFrame.StyledPanel) self.dframe_main.setFrameShadow(QtWidgets.QFrame.Raised) self.dframe_main.setObjectName("dframe_main") self.gridLayout_6 = QtWidgets.QGridLayout(self.dframe_main) self.gridLayout_6.setObjectName("gridLayout_6") self.dfram_cal = QtWidgets.QFrame(self.dframe_main) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dfram_cal.sizePolicy().hasHeightForWidth()) self.dfram_cal.setSizePolicy(sizePolicy) self.dfram_cal.setMinimumSize(QtCore.QSize(800, 400)) self.dfram_cal.setStyleSheet("color: rgb(0, 0, 0);") self.dfram_cal.setFrameShape(QtWidgets.QFrame.StyledPanel) self.dfram_cal.setFrameShadow(QtWidgets.QFrame.Raised) self.dfram_cal.setObjectName("dfram_cal") self.gridLayout_3 = QtWidgets.QGridLayout(self.dfram_cal) self.gridLayout_3.setObjectName("gridLayout_3") self.dgrid = QtWidgets.QGridLayout() self.dgrid.setObjectName("dgrid") self.dbtn_3 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_3.sizePolicy().hasHeightForWidth()) self.dbtn_3.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_3.setFont(font) self.dbtn_3.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_3.setShortcut("") self.dbtn_3.setObjectName("dbtn_3") self.dgrid.addWidget(self.dbtn_3, 1, 5, 1, 1) self.dbtn_icos = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_icos.sizePolicy().hasHeightForWidth()) self.dbtn_icos.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_icos.setFont(font) self.dbtn_icos.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_icos.setObjectName("dbtn_icos") self.dgrid.addWidget(self.dbtn_icos, 2, 1, 1, 1) self.dbtn_rc = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_rc.sizePolicy().hasHeightForWidth()) self.dbtn_rc.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_rc.setFont(font) self.dbtn_rc.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_rc.setObjectName("dbtn_rc") self.dgrid.addWidget(self.dbtn_rc, 4, 2, 1, 1) self.dbtn_0 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_0.sizePolicy().hasHeightForWidth()) self.dbtn_0.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_0.setFont(font) self.dbtn_0.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_0.setObjectName("dbtn_0") self.dgrid.addWidget(self.dbtn_0, 4, 4, 1, 1) self.dbtn_div = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_div.sizePolicy().hasHeightForWidth()) self.dbtn_div.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_div.setFont(font) self.dbtn_div.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_div.setObjectName("dbtn_div") self.dgrid.addWidget(self.dbtn_div, 4, 6, 1, 1) self.dbtn_x = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_x.sizePolicy().hasHeightForWidth()) self.dbtn_x.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_x.setFont(font) self.dbtn_x.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_x.setObjectName("dbtn_x") self.dgrid.addWidget(self.dbtn_x, 0, 6, 1, 1) self.dbtn_1 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_1.sizePolicy().hasHeightForWidth()) self.dbtn_1.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_1.setFont(font) self.dbtn_1.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_1.setObjectName("dbtn_1") self.dgrid.addWidget(self.dbtn_1, 1, 3, 1, 1) self.dbtn_int = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_int.sizePolicy().hasHeightForWidth()) self.dbtn_int.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_int.setFont(font) self.dbtn_int.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_int.setObjectName("dbtn_int") self.dgrid.addWidget(self.dbtn_int, 0, 3, 1, 3) self.dbtn_cos = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_cos.sizePolicy().hasHeightForWidth()) self.dbtn_cos.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_cos.setFont(font) self.dbtn_cos.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_cos.setObjectName("dbtn_cos") self.dgrid.addWidget(self.dbtn_cos, 1, 1, 1, 1) self.dbtn_add = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_add.sizePolicy().hasHeightForWidth()) self.dbtn_add.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_add.setFont(font) self.dbtn_add.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_add.setObjectName("dbtn_add") self.dgrid.addWidget(self.dbtn_add, 1, 6, 1, 1) self.dbtn_subt = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_subt.sizePolicy().hasHeightForWidth()) self.dbtn_subt.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_subt.setFont(font) self.dbtn_subt.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_subt.setObjectName("dbtn_subt") self.dgrid.addWidget(self.dbtn_subt, 2, 6, 1, 1) self.dbtn_5 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_5.sizePolicy().hasHeightForWidth()) self.dbtn_5.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_5.setFont(font) self.dbtn_5.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_5.setShortcut("") self.dbtn_5.setObjectName("dbtn_5") self.dgrid.addWidget(self.dbtn_5, 2, 4, 1, 1) self.dbtn_mul = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_mul.sizePolicy().hasHeightForWidth()) self.dbtn_mul.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_mul.setFont(font) self.dbtn_mul.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_mul.setObjectName("dbtn_mul") self.dgrid.addWidget(self.dbtn_mul, 3, 6, 1, 1) self.dbtn_sin = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_sin.sizePolicy().hasHeightForWidth()) self.dbtn_sin.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_sin.setFont(font) self.dbtn_sin.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_sin.setObjectName("dbtn_sin") self.dgrid.addWidget(self.dbtn_sin, 1, 0, 1, 1) self.dbtn_tan = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_tan.sizePolicy().hasHeightForWidth()) self.dbtn_tan.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_tan.setFont(font) self.dbtn_tan.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_tan.setObjectName("dbtn_tan") self.dgrid.addWidget(self.dbtn_tan, 1, 2, 1, 1) self.dbtn_2 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_2.sizePolicy().hasHeightForWidth()) self.dbtn_2.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_2.setFont(font) self.dbtn_2.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_2.setShortcut("") self.dbtn_2.setObjectName("dbtn_2") self.dgrid.addWidget(self.dbtn_2, 1, 4, 1, 1) self.dbtn_isin = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_isin.sizePolicy().hasHeightForWidth()) self.dbtn_isin.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_isin.setFont(font) self.dbtn_isin.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_isin.setObjectName("dbtn_isin") self.dgrid.addWidget(self.dbtn_isin, 2, 0, 1, 1) self.dbtn_itan = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_itan.sizePolicy().hasHeightForWidth()) self.dbtn_itan.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_itan.setFont(font) self.dbtn_itan.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_itan.setObjectName("dbtn_itan") self.dgrid.addWidget(self.dbtn_itan, 2, 2, 1, 1) self.dbtn_lc = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_lc.sizePolicy().hasHeightForWidth()) self.dbtn_lc.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_lc.setFont(font) self.dbtn_lc.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_lc.setObjectName("dbtn_lc") self.dgrid.addWidget(self.dbtn_lc, 4, 1, 1, 1) self.dbtn_log = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_log.sizePolicy().hasHeightForWidth()) self.dbtn_log.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_log.setFont(font) self.dbtn_log.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_log.setObjectName("dbtn_log") self.dgrid.addWidget(self.dbtn_log, 3, 1, 1, 1) self.dbtn_4 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_4.sizePolicy().hasHeightForWidth()) self.dbtn_4.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_4.setFont(font) self.dbtn_4.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_4.setShortcut("") self.dbtn_4.setObjectName("dbtn_4") self.dgrid.addWidget(self.dbtn_4, 2, 3, 1, 1) self.dbtn_e = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_e.sizePolicy().hasHeightForWidth()) self.dbtn_e.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_e.setFont(font) self.dbtn_e.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_e.setObjectName("dbtn_e") self.dgrid.addWidget(self.dbtn_e, 3, 0, 1, 1) self.dbtn_6 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_6.sizePolicy().hasHeightForWidth()) self.dbtn_6.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_6.setFont(font) self.dbtn_6.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_6.setShortcut("") self.dbtn_6.setObjectName("dbtn_6") self.dgrid.addWidget(self.dbtn_6, 2, 5, 1, 1) self.dbtn_7 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_7.sizePolicy().hasHeightForWidth()) self.dbtn_7.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_7.setFont(font) self.dbtn_7.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_7.setObjectName("dbtn_7") self.dgrid.addWidget(self.dbtn_7, 3, 3, 1, 1) self.dbtn_pow = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_pow.sizePolicy().hasHeightForWidth()) self.dbtn_pow.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_pow.setFont(font) self.dbtn_pow.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_pow.setObjectName("dbtn_pow") self.dgrid.addWidget(self.dbtn_pow, 3, 2, 1, 1) self.dbtn_diff = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_diff.sizePolicy().hasHeightForWidth()) self.dbtn_diff.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_diff.setFont(font) self.dbtn_diff.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_diff.setObjectName("dbtn_diff") self.dgrid.addWidget(self.dbtn_diff, 0, 0, 1, 3) self.dbtn_8 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_8.sizePolicy().hasHeightForWidth()) self.dbtn_8.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_8.setFont(font) self.dbtn_8.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_8.setObjectName("dbtn_8") self.dgrid.addWidget(self.dbtn_8, 3, 4, 1, 1) self.dbtn_9 = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_9.sizePolicy().hasHeightForWidth()) self.dbtn_9.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_9.setFont(font) self.dbtn_9.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_9.setObjectName("dbtn_9") self.dgrid.addWidget(self.dbtn_9, 3, 5, 1, 1) self.dbtn_C = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_C.sizePolicy().hasHeightForWidth()) self.dbtn_C.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_C.setFont(font) self.dbtn_C.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_C.setObjectName("dbtn_C") self.dgrid.addWidget(self.dbtn_C, 4, 3, 1, 1) self.dbtn_back = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_back.sizePolicy().hasHeightForWidth()) self.dbtn_back.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(28) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_back.setFont(font) self.dbtn_back.setStyleSheet("QPushButton{\n" " font: 87 28pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_back.setObjectName("dbtn_back") self.dgrid.addWidget(self.dbtn_back, 4, 5, 1, 1) self.dbtn_exit = QtWidgets.QPushButton(self.dfram_cal) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dbtn_exit.sizePolicy().hasHeightForWidth()) self.dbtn_exit.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(24) font.setBold(False) font.setItalic(False) font.setWeight(10) self.dbtn_exit.setFont(font) self.dbtn_exit.setStyleSheet("QPushButton{\n" " font: 87 24pt \"Arial Black\";\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(0, 0, 0);\n" " border-radius: 35px;\n" "}\n" "\n" "QPushButton:hover{\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(26, 26, 26);\n" " border: 5px solid white\n" "}\n" "\n" "\n" "\n" "QPushButton:hover:!pressed\n" "{\n" " \n" " background-color: rgb(61, 61, 61);\n" " color: rgb(255,255,255);\n" "border: 0px solid white\n" "}\n" "\n" "") self.dbtn_exit.setObjectName("dbtn_exit") self.dgrid.addWidget(self.dbtn_exit, 4, 0, 1, 1) self.gridLayout_3.addLayout(self.dgrid, 0, 0, 1, 1) self.gridLayout_6.addWidget(self.dfram_cal, 2, 0, 1, 1) self.dframe_input = QtWidgets.QFrame(self.dframe_main) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dframe_input.sizePolicy().hasHeightForWidth()) self.dframe_input.setSizePolicy(sizePolicy) self.dframe_input.setStyleSheet("color: rgb(0, 0, 0);") self.dframe_input.setFrameShape(QtWidgets.QFrame.StyledPanel) self.dframe_input.setFrameShadow(QtWidgets.QFrame.Raised) self.dframe_input.setObjectName("dframe_input") self.gridLayout_4 = QtWidgets.QGridLayout(self.dframe_input) self.gridLayout_4.setObjectName("gridLayout_4") self.dinput = QtWidgets.QLineEdit(self.dframe_input) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dinput.sizePolicy().hasHeightForWidth()) self.dinput.setSizePolicy(sizePolicy) self.dinput.setMinimumSize(QtCore.QSize(0, 150)) font = QtGui.QFont() font.setPointSize(26) font.setBold(True) font.setWeight(75) self.dinput.setFont(font) self.dinput.setStyleSheet("color: rgb(255, 255, 255);") self.dinput.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.dinput.setObjectName("dinput") self.gridLayout_4.addWidget(self.dinput, 1, 0, 1, 1) spacerItem = QtWidgets.QSpacerItem(0, 25, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_6.addWidget(self.dframe_input, 0, 0, 1, 1) spacerItem1 = QtWidgets.QSpacerItem(0, 75, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.gridLayout_6.addItem(spacerItem1, 1, 0, 1, 1) self.gridLayout_7.addWidget(self.dframe_main, 0, 0, 1, 1) dniwindow.setCentralWidget(self.diffandintcal) self.statusbar = QtWidgets.QStatusBar(dniwindow) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.statusbar.sizePolicy().hasHeightForWidth()) self.statusbar.setSizePolicy(sizePolicy) self.statusbar.setObjectName("statusbar") dniwindow.setStatusBar(self.statusbar) self.retranslateUi(dniwindow) QtCore.QMetaObject.connectSlotsByName(dniwindow) def retranslateUi(self, dniwindow): _translate = QtCore.QCoreApplication.translate dniwindow.setWindowTitle(_translate("dniwindow", "Differentiaion and Integration")) self.dbtn_3.setText(_translate("dniwindow", "3")) self.dbtn_icos.setText(_translate("dniwindow", "acos( )")) self.dbtn_rc.setText(_translate("dniwindow", ")")) self.dbtn_rc.setShortcut(_translate("dniwindow", ")")) self.dbtn_0.setText(_translate("dniwindow", "0")) self.dbtn_0.setShortcut(_translate("dniwindow", "0")) self.dbtn_div.setText(_translate("dniwindow", "÷")) self.dbtn_div.setShortcut(_translate("dniwindow", "/")) self.dbtn_x.setText(_translate("dniwindow", "X")) self.dbtn_x.setShortcut(_translate("dniwindow", "X")) self.dbtn_1.setText(_translate("dniwindow", "1")) self.dbtn_1.setShortcut(_translate("dniwindow", "1")) self.dbtn_int.setText(_translate("dniwindow", "Integrate")) self.dbtn_cos.setText(_translate("dniwindow", "cos( )")) self.dbtn_add.setText(_translate("dniwindow", "+")) self.dbtn_add.setShortcut(_translate("dniwindow", "+")) self.dbtn_subt.setText(_translate("dniwindow", "-")) self.dbtn_subt.setShortcut(_translate("dniwindow", "-")) self.dbtn_5.setText(_translate("dniwindow", "5")) self.dbtn_mul.setText(_translate("dniwindow", "×")) self.dbtn_mul.setShortcut(_translate("dniwindow", "*")) self.dbtn_sin.setText(_translate("dniwindow", "sin( )")) self.dbtn_tan.setText(_translate("dniwindow", "tan( )")) self.dbtn_2.setText(_translate("dniwindow", "2")) self.dbtn_isin.setText(_translate("dniwindow", "asin( )")) self.dbtn_itan.setText(_translate("dniwindow", "atan( )")) self.dbtn_lc.setText(_translate("dniwindow", "(")) self.dbtn_lc.setShortcut(_translate("dniwindow", "(")) self.dbtn_log.setText(_translate("dniwindow", "log()")) self.dbtn_4.setText(_translate("dniwindow", "4")) self.dbtn_e.setText(_translate("dniwindow", "e")) self.dbtn_e.setShortcut(_translate("dniwindow", "E")) self.dbtn_6.setText(_translate("dniwindow", "6")) self.dbtn_7.setText(_translate("dniwindow", "7")) self.dbtn_pow.setText(_translate("dniwindow", "x^y")) self.dbtn_pow.setShortcut(_translate("dniwindow", "^")) self.dbtn_diff.setText(_translate("dniwindow", "Differentiate")) self.dbtn_8.setText(_translate("dniwindow", "8")) self.dbtn_8.setShortcut(_translate("dniwindow", "8")) self.dbtn_9.setText(_translate("dniwindow", "9")) self.dbtn_C.setText(_translate("dniwindow", "C")) self.dbtn_back.setText(_translate("dniwindow", "⌫")) self.dbtn_back.setShortcut(_translate("dniwindow", "Backspace")) self.dbtn_exit.setText(_translate("dniwindow", "Exit")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) dniwindow = QtWidgets.QMainWindow() ui = Ui_dniwindow() ui.setupUi(dniwindow) dniwindow.show() sys.exit(app.exec_())
35.535324
116
0.628735
5,810
48,790
5.204991
0.028916
0.020502
0.018452
0.043517
0.790615
0.720347
0.713535
0.711683
0.702292
0.700175
0
0.054492
0.213138
48,790
1,372
117
35.561224
0.733141
0
0
0.740849
0
0
0.291408
0.019739
0
0
0
0
0
1
0.001464
false
0
0.001464
0
0.00366
0
0
0
0
null
0
0
0
0
1
1
1
1
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
6
95fcface1d2894449d3d231fce8b70736a29969d
96
py
Python
venv/lib/python3.8/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py
Retraces/UkraineBot
3d5d7f8aaa58fa0cb8b98733b8808e5dfbdb8b71
[ "MIT" ]
2
2022-03-13T01:58:52.000Z
2022-03-31T06:07:54.000Z
venv/lib/python3.8/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
19
2021-11-20T04:09:18.000Z
2022-03-23T15:05:55.000Z
venv/lib/python3.8/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
null
null
null
/home/runner/.cache/pip/pool/f4/61/43/e763c63a0d1ccc9734a1496913cb132551d99e66a6f38b5eabddfcc5e8
96
96
0.895833
9
96
9.555556
1
0
0
0
0
0
0
0
0
0
0
0.40625
0
96
1
96
96
0.489583
0
0
0
0
0
0
0
0
1
0
0
0
0
null
null
0
0
null
null
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
1
0
0
0
1
0
0
0
0
0
0
0
0
6
c2a684df7084e028f52ea5c1d4aed2c2dbce8127
45
py
Python
hello_world.py
AmitSuresh/learning-python
f1ea5b9f3659f21504b1b0e452c03239b03cde85
[ "MIT" ]
null
null
null
hello_world.py
AmitSuresh/learning-python
f1ea5b9f3659f21504b1b0e452c03239b03cde85
[ "MIT" ]
null
null
null
hello_world.py
AmitSuresh/learning-python
f1ea5b9f3659f21504b1b0e452c03239b03cde85
[ "MIT" ]
null
null
null
#say hello print("Hello Python World!!!!")
15
31
0.644444
6
45
4.833333
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.155556
45
3
31
15
0.763158
0.2
0
0
0
0
0.647059
0
0
0
0
0
0
1
0
true
0
0
0
0
1
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
1
0
null
0
0
0
0
0
0
1
0
0
0
0
1
0
6
c2ba8e542b46498c70016a06cc0639dcc036abcc
31,211
py
Python
tests/test_listener.py
bernard357/shellbot
daf64fbab4085d1591bf9a1aecd06b4fc615d132
[ "Apache-2.0" ]
11
2017-04-30T18:10:27.000Z
2021-11-07T16:59:29.000Z
tests/test_listener.py
DataCraft-AI/shellbot
daf64fbab4085d1591bf9a1aecd06b4fc615d132
[ "Apache-2.0" ]
38
2017-04-20T17:33:05.000Z
2017-11-10T20:19:07.000Z
tests/test_listener.py
DataCraft-AI/shellbot
daf64fbab4085d1591bf9a1aecd06b4fc615d132
[ "Apache-2.0" ]
3
2017-04-21T21:14:53.000Z
2021-07-27T22:01:21.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import gc import json import logging import mock from multiprocessing import Process, Queue import os import sys from threading import Timer import time import yaml from shellbot import Context, Engine, Listener, SpaceFactory, Vibes from shellbot.events import Event, Message, Join, Leave class MyEngine(Engine): injected_bot = None def get_bot(self, id): logging.debug("Injecting test bot") return self.injected_bot class MyChannel(object): is_direct = False class MyBot(object): channel = MyChannel() id = '234' fan = Queue() def __init__(self, engine): self.engine = engine def say(self, text, content=None, file=None): self.engine.mouth.put(Vibes(text, content, file, self.id)) def on_enter(self): pass my_message = Message({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "attachment" : "media.png", "url" : "http://www.example.com/images/media.png", }) my_private_message = Message({ "id": "Y2lzY29zcGFyazovL3VzL01FU1NB0xMWU3LTljODctNTljZjJjNDRhYmIy", "roomId": "Y2lzY29zcGFyazovL3VzL1JP0zY2VmLWJiNDctOTZlZjA1NmJhYzFl", "roomType": "direct", "text": "test", "stamp": "2017-07-22T16:49:22.008Z", "hook": "shellbot-messages", "personEmail": "foo.bar@again.org", "personId": "Y2lzY29zcGFyazovL3VzL1LTQ5YzQtYTIyYi1mYWYwZWQwMjkyMzU", "content": "test", "from_id": 'Y2lzY29zcGFyazovL3VzL1LTQ5YzQtYTIyYi1mYWYwZWQwMjkyMzU', "from_label": 'foo.bar@again.org', 'is_direct': True, "mentioned_ids": [], "channel_id": 'Y2lzY29zcGFyazovL3VzL1JP0zY2VmLWJiNDctOTZlZjA1NmJhYzFl', }) my_join = Join({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "actor_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }) my_leave = Leave({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "spce_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "actor_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }) my_enter = Join({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "actor_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }) my_exit = Leave({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "actor_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }) my_event = Event({ "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }) class ListenerTests(unittest.TestCase): def setUp(self): self.engine = MyEngine(ears=Queue(), mouth=Queue()) self.engine.configure() self.engine.set('bot.id', "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg") self.bot = MyBot(engine=self.engine) self.engine.injected_bot = self.bot def tearDown(self): del self.bot del self.engine collected = gc.collect() if collected: logging.info("Garbage collector: collected %d objects." % (collected)) def test_work(self): logging.info("*** run") self.engine.set('general.switch', 'on') listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 listener.process = mock.Mock(side_effect=Exception('TEST')) self.engine.ears.put(('dummy')) self.engine.ears.put(None) listener.run() self.assertEqual(self.engine.get('listener.counter'), 0) listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 listener.process = mock.Mock(side_effect=KeyboardInterrupt('ctl-C')) self.engine.ears.put(('dummy')) listener.run() self.assertEqual(self.engine.get('listener.counter'), 0) def test_run_wait(self): logging.info("*** run/wait while empty and not ready") self.engine.listener.DEFER_DURATION = 0.0 self.engine.set('general.switch', 'on') self.engine.listener.start() t = Timer(0.1, self.engine.ears.put, [str(my_message)]) t.start() time.sleep(0.2) self.engine.set('general.switch', 'off') self.engine.listener.join() def test_process(self): logging.info('*** process ***') listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 self.engine.set('listener.counter', 22) with self.assertRaises(AssertionError): listener.process('hello world') self.assertEqual(self.engine.get('listener.counter'), 23) listener.on_message = mock.Mock() listener.process(str(my_message)) self.assertEqual(self.engine.get('listener.counter'), 24) self.assertTrue(listener.on_message.called) listener.on_message = mock.Mock() listener.process(str(my_private_message)) self.assertEqual(self.engine.get('listener.counter'), 25) self.assertTrue(listener.on_message.called) listener.on_join = mock.Mock() listener.process(str(my_join)) self.assertEqual(self.engine.get('listener.counter'), 26) self.assertTrue(listener.on_join.called) listener.on_leave = mock.Mock() listener.process(str(my_leave)) self.assertEqual(self.engine.get('listener.counter'), 27) self.assertTrue(listener.on_leave.called) listener.on_inbound = mock.Mock() listener.process(str(my_event)) self.assertEqual(self.engine.get('listener.counter'), 28) self.assertTrue(listener.on_inbound.called) def test_process_filter(self): logging.info('*** process/filter ***') class Mocked(object): def filter(self, event): event.flag = True text = event.get('text') if text: event.text = text.title() self.event = event return event mocked = Mocked() listener = Listener(engine=self.engine, filter=mocked.filter) listener.DEFER_DURATION = 0.0 self.engine.set('listener.counter', 22) mocked.event = None listener.process(str(my_message)) self.assertEqual(self.engine.get('listener.counter'), 23) self.assertEqual(mocked.event.text, 'The Pm For This Project Is Mike C. And The Engineering Manager Is Jane W.') self.assertTrue(mocked.event.flag) listener.process(str(my_private_message)) self.assertEqual(self.engine.get('listener.counter'), 24) self.assertEqual(mocked.event.text, 'Test') self.assertTrue(mocked.event.flag) mocked.event = None listener.process(str(my_join)) self.assertEqual(self.engine.get('listener.counter'), 25) self.assertTrue(mocked.event.flag) mocked.event = None listener.process(str(my_leave)) self.assertEqual(self.engine.get('listener.counter'), 26) self.assertTrue(mocked.event.flag) mocked.event = None listener.process(str(my_event)) self.assertEqual(self.engine.get('listener.counter'), 27) self.assertTrue(mocked.event.flag) def test_on_message(self): logging.info('*** on_message ***') listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 listener.on_message(my_message) listener.on_message(my_private_message) with self.assertRaises(AssertionError): listener.on_message(my_join) with self.assertRaises(AssertionError): listener.on_message(my_leave) with self.assertRaises(AssertionError): listener.on_message(my_event) with mock.patch.object(self.engine, 'dispatch', return_value=None) as mocked: listener.on_message(my_message) self.assertTrue(mocked.called) def test_on_message_fan(self): logging.info('*** on_message/fan ***') self.engine.set('bot.id', '*not*for*me') class MyFan(object): def __init__(self): self.called = False def put(self, arguments): self.called = True self.bot.fan = MyFan() listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 listener.on_message(my_message) self.assertFalse(self.bot.fan.called) label = 'fan.' + my_message.channel_id logging.debug(u"- stamping '{}'".format(label)) self.engine.set(label, time.time()) listener.on_message(my_message) self.assertTrue(self.bot.fan.called) def test_on_join(self): logging.info('*** on_join ***') class Handler(object): def __init__(self): self.entered = False self.joined = False def on_enter(self, **kwargs): self.entered = True def on_join(self, **kwargs): self.joined = True handler = Handler() self.engine.register('enter', handler) self.engine.register('join', handler) listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 with self.assertRaises(AssertionError): listener.on_join(my_message) with self.assertRaises(AssertionError): listener.on_join(my_private_message) self.assertFalse(handler.entered) self.assertFalse(handler.joined) listener.on_join(my_enter) self.assertTrue(handler.entered) self.assertFalse(handler.joined) listener.on_join(my_join) self.assertTrue(handler.entered) self.assertTrue(handler.joined) with self.assertRaises(AssertionError): listener.on_join(my_leave) with self.assertRaises(AssertionError): listener.on_join(my_event) with mock.patch.object(self.engine, 'dispatch', return_value=None) as mocked: listener.on_join(my_join) self.assertTrue(mocked.called) def test_on_leave(self): logging.info('*** on_leave ***') class Handler(object): def __init__(self): self.out = False self.left = False def on_exit(self, **kwargs): self.out = True def on_leave(self, **kwargs): self.left = True handler = Handler() self.engine.register('exit', handler) self.engine.register('leave', handler) listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 with self.assertRaises(AssertionError): listener.on_leave(my_message) with self.assertRaises(AssertionError): listener.on_leave(my_private_message) with self.assertRaises(AssertionError): listener.on_leave(my_join) self.assertFalse(handler.out) self.assertFalse(handler.left) listener.on_leave(my_exit) self.assertTrue(handler.out) self.assertFalse(handler.left) listener.on_leave(my_leave) self.assertTrue(handler.out) self.assertTrue(handler.left) with self.assertRaises(AssertionError): listener.on_leave(my_event) with mock.patch.object(self.engine, 'dispatch', return_value=None) as mocked: listener.on_leave(my_leave) self.assertTrue(mocked.called) def test_on_inbound(self): logging.info('*** on_inbound ***') listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 with self.assertRaises(AssertionError): listener.on_inbound(my_message) with self.assertRaises(AssertionError): listener.on_inbound(my_private_message) with self.assertRaises(AssertionError): listener.on_inbound(my_join) with self.assertRaises(AssertionError): listener.on_inbound(my_leave) listener.on_inbound(my_event) with mock.patch.object(self.engine, 'dispatch', return_value=None) as mocked: listener.on_inbound(my_event) self.assertTrue(mocked.called) def test_static(self): logging.info('*** Static test ***') listener = Listener(engine=self.engine) listener.DEFER_DURATION = 0.0 listener.start() listener.join(0.1) if listener.is_alive(): logging.info('Stopping listener') self.engine.set('general.switch', 'off') listener.join() self.assertFalse(listener.is_alive()) self.assertEqual(self.engine.get('listener.counter', 0), 0) def test_dynamic(self): logging.info('*** Dynamic test ***') items = [ { "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "PROJECT UPDATE - A new project plan has been published on Box: http://box.com/s/lf5vj. The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", }, { "id" : "2_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "/shelly version", "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }, { "id" : "2_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "", "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }, { "id" : "3_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "@shelly help", "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }, { "id" : "3_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "!shelly help help", "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], }, { "id" : "4_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk", "channel_id" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0", "roomType" : "group", "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX", "toPersonEmail" : "julie@example.com", "text" : "PROJECT UPDATE - A new project plan has been published on Box: http://box.com/s/lf5vj. The PM for this project is Mike C. and the Engineering Manager is Jane W.", "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:mike@example.com> and the Engineering Manager is <@personEmail:jane@example.com>.", "files" : [ "http://www.example.com/images/media.png" ], "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "personEmail" : "matt@example.com", "stamp" : "2015-10-18T14:26:16+00:00", "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ], "from_id" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY", "mentioned_ids" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM" ], }, { "id": "Y2lzY29zcGFyazovL3VzL01FU1NB0xMWU3LTljODctNTljZjJjNDRhYmIy", "roomId": "Y2lzY29zcGFyazovL3VzL1JP0zY2VmLWJiNDctOTZlZjA1NmJhYzFl", "roomType": "direct", "text": "test", "stamp": "2017-07-22T16:49:22.008Z", "hook": "shellbot-messages", "personEmail": "foo.bar@again.org", "personId": "Y2lzY29zcGFyazovL3VzL1LTQ5YzQtYTIyYi1mYWYwZWQwMjkyMzU", "content": "test", "from_id": 'Y2lzY29zcGFyazovL3VzL1LTQ5YzQtYTIyYi1mYWYwZWQwMjkyMzU', "from_label": 'foo.bar@again.org', 'is_direct': True, "mentioned_ids": [], "channel_id": 'Y2lzY29zcGFyazovL3VzL1JP0zY2VmLWJiNDctOTZlZjA1NmJhYzFl', }, ] for item in items: self.engine.ears.put(str(Message(item))) self.engine.ears.put(None) tee = Queue() def filter(item): tee.put(str(item)) return item listener = Listener(engine=self.engine, filter=filter) listener.DEFER_DURATION = 0.0 listener.run() time.sleep(0.01) self.assertEqual(self.engine.get('listener.counter'), 7) with self.assertRaises(Exception): self.engine.ears.get_nowait() self.assertEqual( self.engine.mouth.get_nowait().text, 'Shelly version *unknown*') self.assertEqual( self.engine.mouth.get_nowait().text, u'Available commands:\n' + u'help - Show commands and usage') self.assertEqual( self.engine.mouth.get_nowait().text, u'Available commands:\n' + u'help - Show commands and usage') self.assertEqual( self.engine.mouth.get_nowait().text, u'help - Show commands and usage\nusage: help <command>') self.assertEqual( self.engine.mouth.get_nowait().text, u"Sorry, I do not know how to handle 'test'") with self.assertRaises(Exception): print(self.engine.mouth.get_nowait()) self.maxDiff = None for item in items: item.update({'type': 'message'}) self.assertEqual(yaml.safe_load(tee.get()), item) with self.assertRaises(Exception): print(tee.get_nowait()) if __name__ == '__main__': Context.set_logger() sys.exit(unittest.main())
47.146526
243
0.685848
2,559
31,211
8.271981
0.103165
0.031652
0.017952
0.023621
0.863001
0.836924
0.819114
0.801398
0.772581
0.753496
0
0.069118
0.208708
31,211
661
244
47.217852
0.78799
0.001346
0
0.621013
0
0.018762
0.492572
0.312863
0
0
0
0
0.133208
1
0.050657
false
0.001876
0.02439
0
0.105066
0.003752
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
c2c8550bfc6e1c525999f2cf97df790af92c9452
169
py
Python
xbee/backend/__init__.py
PowerFlex/python-xbee-intercept
0c07f3a5f16f479ad7c925cd31638598030cf5a7
[ "MIT" ]
65
2015-12-06T02:38:28.000Z
2017-09-05T16:46:07.000Z
xbee/backend/__init__.py
PowerFlex/python-xbee-intercept
0c07f3a5f16f479ad7c925cd31638598030cf5a7
[ "MIT" ]
44
2015-10-23T15:33:54.000Z
2017-09-01T06:39:50.000Z
xbee/backend/__init__.py
PowerFlex/python-xbee-intercept
0c07f3a5f16f479ad7c925cd31638598030cf5a7
[ "MIT" ]
43
2015-12-15T02:52:21.000Z
2017-06-24T17:14:53.000Z
""" XBee package initalization file info@n.io """ from xbee.backend.ieee import XBee from xbee.backend.zigbee import ZigBee from xbee.backend.digimesh import DigiMesh
16.9
42
0.792899
25
169
5.36
0.52
0.179104
0.335821
0
0
0
0
0
0
0
0
0
0.12426
169
9
43
18.777778
0.905405
0.248521
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
1
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
1
0
1
0
0
6
6c0979dbcc947d029811bc87860b7ceac0569554
104
py
Python
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/utils/api/schema.py
leoyunhyung/cookiecutter-django
2c906684e964b7d0c2ae571eeba86c19f37f1a08
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/utils/api/schema.py
leoyunhyung/cookiecutter-django
2c906684e964b7d0c2ae571eeba86c19f37f1a08
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/utils/api/schema.py
leoyunhyung/cookiecutter-django
2c906684e964b7d0c2ae571eeba86c19f37f1a08
[ "BSD-3-Clause" ]
null
null
null
from drf_yasg.inspectors import SwaggerAutoSchema class CustomAutoSchema(SwaggerAutoSchema): pass
17.333333
49
0.836538
10
104
8.6
0.9
0
0
0
0
0
0
0
0
0
0
0
0.125
104
5
50
20.8
0.945055
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.333333
0.333333
0
0.666667
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
1
1
0
1
0
0
6
6c2533dc3e3471d9bc209400fed0796203f4547c
9,985
py
Python
cheshire3/web/test/testQueryFactory.py
cheshire3/cheshire3
306348831ec110229c78a7c5f0f2026a0f394d2c
[ "Python-2.0", "Unlicense" ]
3
2015-08-02T09:03:28.000Z
2017-12-06T09:26:14.000Z
cheshire3/web/test/testQueryFactory.py
cheshire3/cheshire3
306348831ec110229c78a7c5f0f2026a0f394d2c
[ "Python-2.0", "Unlicense" ]
5
2015-08-17T01:16:35.000Z
2015-09-16T21:51:27.000Z
cheshire3/web/test/testQueryFactory.py
cheshire3/cheshire3
306348831ec110229c78a7c5f0f2026a0f394d2c
[ "Python-2.0", "Unlicense" ]
6
2015-05-17T15:32:20.000Z
2020-04-22T08:43:16.000Z
u"""Cheshire3 Web QueryFactory Unittests. QueryFactory configurations may be customized by the user. For the purposes of unittesting, configuration files will be ignored and QueryFactory instances will be instantiated using configuration data defined within this testing module, and tests carried out on instances. """ try: import unittest2 as unittest except ImportError: import unittest from lxml import etree from cheshire3.cqlParser import * from cheshire3.queryFactory import SimpleQueryFactory from cheshire3.web.www_utils import FieldStorageDict from cheshire3.test.testQueryFactory import SimpleQueryFactoryTestCase class WwwQueryFactoryTestCase(SimpleQueryFactoryTestCase): """Cheshire3 SimpleQueryFactory Test Case.""" def _get_class(self): return SimpleQueryFactory def _get_config(self): return etree.XML('''\ <subConfig type="documentFactory" id="{0.__name__}"> <objectType>cheshire3.queryFactory.{0.__name__}</objectType> </subConfig>'''.format(self._get_class())) def test_get_query_clause_www(self): "Test simple clause." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='all', fieldcont1='spam' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, SearchClause) # Check Index self.assertIsInstance(query.index, Index) self.assertEqual(query.index.prefix, 'cql') self.assertEqual(query.index.value, 'anywhere') # Check Relation self.assertIsInstance(query.relation, Relation) self.assertEqual(query.relation.value, 'all') # Check Value self.assertIsInstance(query.term, Term) self.assertEqual(query.term.value, 'spam') def test_get_query_clause2_www(self): "Test simple clause with multiple terms." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='all', fieldcont1='spam eggs' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, SearchClause) # Check Index self.assertIsInstance(query.index, Index) self.assertEqual(query.index.prefix, 'cql') self.assertEqual(query.index.value, 'anywhere') # Check Relation self.assertIsInstance(query.relation, Relation) self.assertEqual(query.relation.value, 'all') # Check Value self.assertIsInstance(query.term, Term) self.assertEqual(query.term.value, 'spam eggs') def test_get_query_clause_www_exact(self): "Test simple clause with 'exact' relation." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='exact', fieldcont1='spam eggs' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, SearchClause) # Check Index self.assertIsInstance(query.index, Index) self.assertEqual(query.index.prefix, 'cql') self.assertEqual(query.index.value, 'anywhere') # Check Relation self.assertIsInstance(query.relation, Relation) self.assertEqual(query.relation.value, 'exact') # Check Value self.assertIsInstance(query.term, Term) self.assertEqual(query.term.value, 'spam eggs') def test_get_query_clause_www_exact_quotes(self): "Test simple clause with 'exact' relation and quotes." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='exact', fieldcont1='"spam eggs"' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, SearchClause) # Check Index self.assertIsInstance(query.index, Index) self.assertEqual(query.index.prefix, 'cql') self.assertEqual(query.index.value, 'anywhere') # Check Relation self.assertIsInstance(query.relation, Relation) self.assertEqual(query.relation.value, 'exact') # Check Value self.assertIsInstance(query.term, Term) self.assertEqual(query.term.value, '"spam eggs"') def test_get_query_triple_www(self): "Test query with boolean." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='all', fieldcont1='spam', fieldbool1='and', fieldidx2='cql.anywhere', fieldrel2='all', fieldcont2='eggs' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, Triple) # Check left clause self.assertIsInstance(query.leftOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.leftOperand.toCQL(), u'cql.anywhere all "spam"') # Check boolean self.assertIsInstance(query.boolean, Boolean) self.assertEqual(query.boolean.value, 'and') # Check right clause self.assertIsInstance(query.rightOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.rightOperand.toCQL(), u'cql.anywhere all "eggs"') def test_get_query_triple2_www(self): "Test query with boolean and multiple terms." form = FieldStorageDict( fieldidx1='cql.anywhere', fieldrel1='all', fieldcont1='spam', fieldbool1='and', fieldidx2='cql.anywhere', fieldrel2='all', fieldcont2='eggs bacon' ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, Triple) # Check left clause self.assertIsInstance(query.leftOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.leftOperand.toCQL(), u'cql.anywhere all "spam"') # Check boolean self.assertIsInstance(query.boolean, Boolean) self.assertEqual(query.boolean.value, 'and') # Check right clause self.assertIsInstance(query.rightOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.rightOperand.toCQL(), u'cql.anywhere all "eggs bacon"') def test_get_query_triple_www_compound(self): "Test query with boolean and multiple indexes." form = FieldStorageDict( fieldidx1='cql.anywhere||dc.description', fieldrel1='all', fieldcont1='spam', ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, Triple) # Check left clause self.assertIsInstance(query.leftOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.leftOperand.toCQL(), u'cql.anywhere all "spam"') # Check boolean self.assertIsInstance(query.boolean, Boolean) self.assertEqual(query.boolean.value, 'or') # Check right clause self.assertIsInstance(query.rightOperand, SearchClause) # remember terms get quoted during parsing self.assertEqual(query.rightOperand.toCQL(), u'dc.description all "spam"') def test_get_query_triple_www_compound_phrase(self): "Test query with boolean and multiple indexes with internal phrase." form = FieldStorageDict( fieldidx1='cql.anywhere||dc.description', fieldrel1='all', fieldcont1='spam "eggs and bacon"', ) query = self.testObj.get_query( self.session, form, format='www' ) # Check query instance self.assertIsInstance(query, Triple) # Check left clause self.assertIsInstance(query.leftOperand, Triple) # Remember terms get quoted during parsing self.assertEqual( query.leftOperand.leftOperand.toCQL(), u'cql.anywhere =/cql.relevant/cql.proxinfo "eggs and bacon"' ) self.assertEqual(query.leftOperand.boolean.value, u'and') self.assertEqual( query.leftOperand.rightOperand.toCQL(), u'cql.anywhere all "spam"' ) # Check boolean self.assertIsInstance(query.boolean, Boolean) self.assertEqual(query.boolean.value, 'or') # Check right clause self.assertIsInstance(query.rightOperand, Triple) # Remember terms get quoted during parsing self.assertEqual( query.rightOperand.leftOperand.toCQL(), u'dc.description =/cql.relevant/cql.proxinfo "eggs and bacon"' ) self.assertEqual(query.rightOperand.boolean.value, u'and') self.assertEqual( query.rightOperand.rightOperand.toCQL(), u'dc.description all "spam"' ) def load_tests(loader, tests, pattern): suite = loader.loadTestsFromTestCase(WwwQueryFactoryTestCase) return suite if __name__ == '__main__': tr = unittest.TextTestRunner(verbosity=2) tr.run(load_tests(unittest.defaultTestLoader, [], 'test*.py'))
35.917266
78
0.61362
971
9,985
6.236869
0.143151
0.10568
0.1321
0.019815
0.81572
0.797721
0.785832
0.747193
0.722754
0.716149
0
0.006376
0.29314
9,985
278
79
35.917266
0.851658
0.154732
0
0.613208
0
0
0.139338
0.022001
0
0
0
0
0.301887
1
0.051887
false
0
0.037736
0.009434
0.108491
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
dd62af95b04f1070eb44f95ad276a30786bb5113
32
py
Python
storage_formats/apache_parquet/python/fastparquet_test/__init__.py
statisticsnorway/microdata-testing
3b14a2f6f08791a666c659bbdc9cdf9d41a4c23d
[ "Apache-2.0" ]
null
null
null
storage_formats/apache_parquet/python/fastparquet_test/__init__.py
statisticsnorway/microdata-testing
3b14a2f6f08791a666c659bbdc9cdf9d41a4c23d
[ "Apache-2.0" ]
null
null
null
storage_formats/apache_parquet/python/fastparquet_test/__init__.py
statisticsnorway/microdata-testing
3b14a2f6f08791a666c659bbdc9cdf9d41a4c23d
[ "Apache-2.0" ]
null
null
null
from .fastparquet_test import *
16
31
0.8125
4
32
6.25
1
0
0
0
0
0
0
0
0
0
0
0
0.125
32
1
32
32
0.892857
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
06f038d193e36736889068a208f8833e7e41b7a5
3,138
py
Python
basicswap/rpc_xmr.py
tecnovert/basicswap
6a9e759629ab856b77993bcd2a7cb4fd29c10a1d
[ "MIT" ]
8
2019-07-25T14:55:13.000Z
2022-02-17T16:02:19.000Z
basicswap/rpc_xmr.py
tecnovert/basicswap
6a9e759629ab856b77993bcd2a7cb4fd29c10a1d
[ "MIT" ]
2
2021-01-04T07:22:49.000Z
2021-02-14T13:10:44.000Z
basicswap/rpc_xmr.py
tecnovert/basicswap
6a9e759629ab856b77993bcd2a7cb4fd29c10a1d
[ "MIT" ]
11
2019-08-02T08:41:37.000Z
2022-03-27T12:02:27.000Z
# -*- coding: utf-8 -*- import json import requests def callrpc_xmr(rpc_port, auth, method, params=[], rpc_host='127.0.0.1', path='json_rpc', timeout=120): # auth is a tuple: (username, password) try: url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, path) request_body = { 'method': method, 'params': params, 'id': 2, 'jsonrpc': '2.0' } headers = { 'Content-Type': 'application/json' } p = requests.post(url, data=json.dumps(request_body), auth=requests.auth.HTTPDigestAuth(auth[0], auth[1]), headers=headers, timeout=timeout) r = json.loads(p.text) except Exception as ex: raise ValueError('RPC Server Error: {}'.format(str(ex))) if 'error' in r and r['error'] is not None: raise ValueError('RPC error ' + str(r['error'])) return r['result'] def callrpc_xmr_na(rpc_port, method, params=[], rpc_host='127.0.0.1', path='json_rpc', timeout=120): try: url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, path) request_body = { 'method': method, 'params': params, 'id': 2, 'jsonrpc': '2.0' } headers = { 'Content-Type': 'application/json' } p = requests.post(url, data=json.dumps(request_body), headers=headers, timeout=timeout) r = json.loads(p.text) except Exception as ex: raise ValueError('RPC Server Error: {}'.format(str(ex))) if 'error' in r and r['error'] is not None: raise ValueError('RPC error ' + str(r['error'])) return r['result'] def callrpc_xmr2(rpc_port, method, params=None, rpc_host='127.0.0.1', timeout=120): try: url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, method) headers = { 'Content-Type': 'application/json' } if params is None: p = requests.post(url, headers=headers, timeout=timeout) else: p = requests.post(url, data=json.dumps(params), headers=headers, timeout=timeout) r = json.loads(p.text) except Exception as ex: raise ValueError('RPC Server Error: {}'.format(str(ex))) return r def make_xmr_rpc_func(port, host='127.0.0.1'): port = port host = host def rpc_func(method, params=None, wallet=None, timeout=120): nonlocal port nonlocal host return callrpc_xmr_na(port, method, params, rpc_host=host, timeout=timeout) return rpc_func def make_xmr_rpc2_func(port, host='127.0.0.1'): port = port host = host def rpc_func(method, params=None, wallet=None, timeout=120): nonlocal port nonlocal host return callrpc_xmr2(port, method, params, rpc_host=host, timeout=timeout) return rpc_func def make_xmr_wallet_rpc_func(port, auth, host='127.0.0.1'): port = port auth = auth host = host def rpc_func(method, params=None, wallet=None, timeout=120): nonlocal port, auth, host return callrpc_xmr(port, auth, method, params, rpc_host=host, timeout=timeout) return rpc_func
30.764706
148
0.593053
418
3,138
4.344498
0.169856
0.072687
0.026432
0.029736
0.827643
0.807269
0.7913
0.765419
0.765419
0.765419
0
0.02851
0.262269
3,138
101
149
31.069307
0.75594
0.018802
0
0.666667
0
0
0.119961
0
0
0
0
0
0
1
0.115385
false
0
0.025641
0
0.25641
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
6649f8e57a7599aa28416a4220d47a0ece8e0329
103
py
Python
h2o-py/tests/utils/__init__.py
kyoren/https-github.com-h2oai-h2o-3
77b27109c84c4739f9f1b7a3078f8992beefc813
[ "Apache-2.0" ]
1
2016-09-30T05:58:18.000Z
2016-09-30T05:58:18.000Z
h2o-py/tests/utils/__init__.py
kyoren/https-github.com-h2oai-h2o-3
77b27109c84c4739f9f1b7a3078f8992beefc813
[ "Apache-2.0" ]
null
null
null
h2o-py/tests/utils/__init__.py
kyoren/https-github.com-h2oai-h2o-3
77b27109c84c4739f9f1b7a3078f8992beefc813
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 # module utils # from (utils) from ipynb_demo_runner import * from utilsPY import *
14.714286
31
0.737864
15
103
4.933333
0.733333
0.243243
0
0
0
0
0
0
0
0
0
0.011765
0.174757
103
6
32
17.166667
0.858824
0.398058
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
b07e605ad0d78c18c781d630d9eb94f6e3b76c55
7,859
py
Python
twunnel/generator__ssl.py
jvansteirteghem/twunnel
6de57636c7a9df03fe8452c5bc57071aad3719a7
[ "MIT" ]
16
2015-02-09T11:45:05.000Z
2021-07-22T12:21:25.000Z
twunnel/generator__ssl.py
jvansteirteghem/twunnel
6de57636c7a9df03fe8452c5bc57071aad3719a7
[ "MIT" ]
null
null
null
twunnel/generator__ssl.py
jvansteirteghem/twunnel
6de57636c7a9df03fe8452c5bc57071aad3719a7
[ "MIT" ]
7
2015-02-23T18:38:17.000Z
2021-04-15T11:10:19.000Z
# Copyright (c) Jeroen Van Steirteghem # See LICENSE import OpenSSL import time def generateCertificateAuthority(configuration): configuration.setdefault("CERTIFICATE", {}) configuration["CERTIFICATE"].setdefault("AUTHORITY", {}) configuration["CERTIFICATE"]["AUTHORITY"].setdefault("FILE", "") configuration["CERTIFICATE"]["AUTHORITY"].setdefault("KEY", {}) configuration["CERTIFICATE"]["AUTHORITY"]["KEY"].setdefault("FILE", "") configuration["CERTIFICATE"]["AUTHORITY"]["KEY"].setdefault("PASSPHRASE", "") configuration["CERTIFICATE"]["AUTHORITY"].setdefault("SUBJECT", {}) configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("COUNTRY_NAME", "") configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("STATE_OR_PROVINCE_NAME", "") configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("LOCALITY_NAME", "") configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("ORGANISATION_NAME", "") configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("ORGANISATIONAL_UNIT_NAME", "") configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"].setdefault("COMMON_NAME", "") ca_key = OpenSSL.crypto.PKey() ca_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) ca = OpenSSL.crypto.X509() ca.set_version(3) ca.set_serial_number(int(time.time() * 10000)) if configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["COUNTRY_NAME"] != "": ca.get_subject().C = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["COUNTRY_NAME"] if configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["STATE_OR_PROVINCE_NAME"] != "": ca.get_subject().ST = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["STATE_OR_PROVINCE_NAME"] if configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["LOCALITY_NAME"] != "": ca.get_subject().L = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["LOCALITY_NAME"] if configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["ORGANISATION_NAME"] != "": ca.get_subject().O = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["ORGANISATION_NAME"] if configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["ORGANISATIONAL_UNIT_NAME"] != "": ca.get_subject().OU = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["ORGANISATIONAL_UNIT_NAME"] ca.get_subject().CN = configuration["CERTIFICATE"]["AUTHORITY"]["SUBJECT"]["COMMON_NAME"] ca.gmtime_adj_notBefore(0) ca.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60) ca.set_issuer(ca.get_subject()) ca.set_pubkey(ca_key) ca.add_extensions([OpenSSL.crypto.X509Extension("basicConstraints", True, "CA:TRUE")]) ca.add_extensions([OpenSSL.crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=ca)]) ca.add_extensions([OpenSSL.crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca)]) ca.sign(ca_key, "sha1") data = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca) f = open(configuration["CERTIFICATE"]["AUTHORITY"]["FILE"], "wb") f.write(data) f.close() if configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["PASSPHRASE"] != "": data = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, ca_key, "aes-256-cbc", configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["PASSPHRASE"]) else: data = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, ca_key) f = open(configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["FILE"], "wb") f.write(data) f.close() def generateCertificate(configuration): configuration.setdefault("CERTIFICATE", {}) configuration["CERTIFICATE"].setdefault("AUTHORITY", {}) configuration["CERTIFICATE"]["AUTHORITY"].setdefault("FILE", "") configuration["CERTIFICATE"]["AUTHORITY"].setdefault("KEY", {}) configuration["CERTIFICATE"]["AUTHORITY"]["KEY"].setdefault("FILE", "") configuration["CERTIFICATE"]["AUTHORITY"]["KEY"].setdefault("PASSPHRASE", "") configuration["CERTIFICATE"].setdefault("FILE", "") configuration["CERTIFICATE"].setdefault("KEY", {}) configuration["CERTIFICATE"]["KEY"].setdefault("FILE", "") configuration["CERTIFICATE"]["KEY"].setdefault("PASSPHRASE", "") configuration["CERTIFICATE"].setdefault("SUBJECT", {}) configuration["CERTIFICATE"]["SUBJECT"].setdefault("COUNTRY_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("STATE_OR_PROVINCE_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("LOCALITY_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("ORGANISATION_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("ORGANISATIONAL_UNIT_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("COMMON_NAME", "") configuration["CERTIFICATE"]["SUBJECT"].setdefault("ALTERNATIVE_NAME", "") f = open(configuration["CERTIFICATE"]["AUTHORITY"]["FILE"], "rb") data = f.read() f.close() ca = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, data) f = open(configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["FILE"], "rb") data = f.read() f.close() if configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["PASSPHRASE"] != "": ca_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, data, configuration["CERTIFICATE"]["AUTHORITY"]["KEY"]["PASSPHRASE"]) else: ca_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, data) c_key = OpenSSL.crypto.PKey() c_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) c = OpenSSL.crypto.X509() c.set_version(3) c.set_serial_number(int(time.time() * 10000)) if configuration["CERTIFICATE"]["SUBJECT"]["COUNTRY_NAME"] != "": c.get_subject().C = configuration["CERTIFICATE"]["SUBJECT"]["COUNTRY_NAME"] if configuration["CERTIFICATE"]["SUBJECT"]["STATE_OR_PROVINCE_NAME"] != "": c.get_subject().ST = configuration["CERTIFICATE"]["SUBJECT"]["STATE_OR_PROVINCE_NAME"] if configuration["CERTIFICATE"]["SUBJECT"]["LOCALITY_NAME"] != "": c.get_subject().L = configuration["CERTIFICATE"]["SUBJECT"]["LOCALITY_NAME"] if configuration["CERTIFICATE"]["SUBJECT"]["ORGANISATION_NAME"] != "": c.get_subject().O = configuration["CERTIFICATE"]["SUBJECT"]["ORGANISATION_NAME"] if configuration["CERTIFICATE"]["SUBJECT"]["ORGANISATIONAL_UNIT_NAME"] != "": c.get_subject().OU = configuration["CERTIFICATE"]["SUBJECT"]["ORGANISATIONAL_UNIT_NAME"] c.get_subject().CN = configuration["CERTIFICATE"]["SUBJECT"]["COMMON_NAME"] c.gmtime_adj_notBefore(0) c.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60) c.set_issuer(ca.get_subject()) c.set_pubkey(c_key) c.add_extensions([OpenSSL.crypto.X509Extension("basicConstraints", True, "CA:FALSE")]) c.add_extensions([OpenSSL.crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=c)]) c.add_extensions([OpenSSL.crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", subject=ca, issuer=ca)]) if configuration["CERTIFICATE"]["SUBJECT"]["ALTERNATIVE_NAME"] != "": c.add_extensions([OpenSSL.crypto.X509Extension("subjectAltName", False, configuration["CERTIFICATE"]["SUBJECT"]["ALTERNATIVE_NAME"])]) c.sign(ca_key, "sha1") data = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c) f = open(configuration["CERTIFICATE"]["FILE"], "wb") f.write(data) f.close() if configuration["CERTIFICATE"]["KEY"]["PASSPHRASE"] != "": data = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, c_key, "aes-256-cbc", configuration["CERTIFICATE"]["KEY"]["PASSPHRASE"]) else: data = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, c_key) f = open(configuration["CERTIFICATE"]["KEY"]["FILE"], "wb") f.write(data) f.close()
56.539568
161
0.688001
799
7,859
6.604506
0.12015
0.295623
0.212621
0.128861
0.882509
0.782642
0.562441
0.502748
0.373697
0.291832
0
0.011114
0.118463
7,859
139
162
56.539568
0.750577
0.006108
0
0.245763
1
0
0.302856
0.040978
0
0
0
0
0
1
0.016949
false
0.076271
0.016949
0
0.033898
0
0
0
0
null
1
1
0
1
1
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
1
0
0
0
0
0
6
b08099495b8d943baa39c812185243c1726ae0cb
141
py
Python
python/tests/test_pangram.py
matyama/codewars
3386dbdb1cd3fa6556356591f377a72bf4bba4e6
[ "MIT" ]
null
null
null
python/tests/test_pangram.py
matyama/codewars
3386dbdb1cd3fa6556356591f377a72bf4bba4e6
[ "MIT" ]
null
null
null
python/tests/test_pangram.py
matyama/codewars
3386dbdb1cd3fa6556356591f377a72bf4bba4e6
[ "MIT" ]
null
null
null
from codewars.pangram import is_pangram def test_pangram() -> None: assert is_pangram('The quick, brown fox jumps over the lazy dog!')
23.5
70
0.744681
22
141
4.636364
0.772727
0.176471
0
0
0
0
0
0
0
0
0
0
0.170213
141
5
71
28.2
0.871795
0
0
0
0
0
0.319149
0
0
0
0
0
0.333333
1
0.333333
true
0
0.333333
0
0.666667
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
1
0
1
0
1
0
0
6
b0b697bd758110ba8c46d8603f2f69cef35bfdc7
33
py
Python
amocrm_asterisk_ng/scenario/core/__init__.py
iqtek/amocrn_asterisk_ng
429a8d0823b951c855a49c1d44ab0e05263c54dc
[ "MIT" ]
null
null
null
amocrm_asterisk_ng/scenario/core/__init__.py
iqtek/amocrn_asterisk_ng
429a8d0823b951c855a49c1d44ab0e05263c54dc
[ "MIT" ]
null
null
null
amocrm_asterisk_ng/scenario/core/__init__.py
iqtek/amocrn_asterisk_ng
429a8d0823b951c855a49c1d44ab0e05263c54dc
[ "MIT" ]
null
null
null
from .IScenario import IScenario
16.5
32
0.848485
4
33
7
0.75
0
0
0
0
0
0
0
0
0
0
0
0.121212
33
1
33
33
0.965517
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
b0e19971674a0b704dc723ef290235b4ba5dd2e4
23
py
Python
messaging_components/brokers/qpid/__init__.py
fgiorgetti/qpid-dispatch-tests
164c609d28db87692eed53d5361aa1ee5c97375c
[ "Apache-2.0" ]
null
null
null
messaging_components/brokers/qpid/__init__.py
fgiorgetti/qpid-dispatch-tests
164c609d28db87692eed53d5361aa1ee5c97375c
[ "Apache-2.0" ]
null
null
null
messaging_components/brokers/qpid/__init__.py
fgiorgetti/qpid-dispatch-tests
164c609d28db87692eed53d5361aa1ee5c97375c
[ "Apache-2.0" ]
null
null
null
from .qpid import Qpid
11.5
22
0.782609
4
23
4.5
0.75
0
0
0
0
0
0
0
0
0
0
0
0.173913
23
1
23
23
0.947368
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
9ff464f8ac929b04a1fa88f188fd3c5d90d09fcf
32,710
py
Python
tests/base/cache_pool_test.py
RevenueCat/meta-memcache-py
755ecfc4cfbb029d3435590c5f9aa8a8aa2a36e3
[ "MIT" ]
null
null
null
tests/base/cache_pool_test.py
RevenueCat/meta-memcache-py
755ecfc4cfbb029d3435590c5f9aa8a8aa2a36e3
[ "MIT" ]
4
2022-01-10T23:06:43.000Z
2022-03-08T22:49:39.000Z
tests/base/cache_pool_test.py
RevenueCat/meta-memcache-py
755ecfc4cfbb029d3435590c5f9aa8a8aa2a36e3
[ "MIT" ]
null
null
null
import pickle import zlib from dataclasses import dataclass from unittest.mock import MagicMock, call import pytest from pytest_mock import MockerFixture from meta_memcache import CachePool, Key, MemcacheError, SetMode from meta_memcache.base.base_write_failure_tracker import BaseWriteFailureTracker from meta_memcache.base.connection_pool import ConnectionPool from meta_memcache.base.memcache_socket import MemcacheSocket from meta_memcache.configuration import ( LeasePolicy, RecachePolicy, StalePolicy, default_binary_key_encoding, ) from meta_memcache.errors import MemcacheServerError from meta_memcache.protocol import ( Flag, IntFlag, Miss, NotStored, ServerVersion, Success, Value, ) from meta_memcache.serializer import MixedSerializer class FakeCachePool(CachePool): def __init__(self, connection_pool: ConnectionPool, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.connection_pool = connection_pool def _get_pool(self, key: Key) -> ConnectionPool: return self.connection_pool @dataclass class Foo: bar: str @dataclass class Bar: foo: str @pytest.fixture def write_failure_tracker(mocker: MockerFixture) -> BaseWriteFailureTracker: return mocker.MagicMock(spec=BaseWriteFailureTracker) @pytest.fixture def memcache_socket(mocker: MockerFixture) -> MemcacheSocket: memcache_socket = mocker.MagicMock(spec=MemcacheSocket) memcache_socket.get_version.return_value = ServerVersion.STABLE return memcache_socket @pytest.fixture def memcache_socket_1_6_6(mocker: MockerFixture) -> MemcacheSocket: memcache_socket = mocker.MagicMock(spec=MemcacheSocket) memcache_socket.get_version.return_value = ServerVersion.AWS_1_6_6 return memcache_socket @pytest.fixture def cache_pool( mocker: MockerFixture, memcache_socket: MemcacheSocket, write_failure_tracker: BaseWriteFailureTracker, ) -> FakeCachePool: connection_pool = mocker.MagicMock(spec=ConnectionPool) connection_pool.get_connection().__enter__.return_value = memcache_socket return FakeCachePool( connection_pool=connection_pool, serializer=MixedSerializer(), binary_key_encoding_fn=default_binary_key_encoding, write_failure_tracker=write_failure_tracker, ) @pytest.fixture def cache_pool_1_6_6( mocker: MockerFixture, memcache_socket_1_6_6: MemcacheSocket, write_failure_tracker: BaseWriteFailureTracker, ) -> FakeCachePool: connection_pool = mocker.MagicMock(spec=ConnectionPool) connection_pool.get_connection().__enter__.return_value = memcache_socket_1_6_6 return FakeCachePool( connection_pool=connection_pool, serializer=MixedSerializer(), binary_key_encoding_fn=default_binary_key_encoding, write_failure_tracker=write_failure_tracker, ) def test_set_cmd( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, ) -> None: memcache_socket.get_response.return_value = Success() cache_pool.set(key="foo", value="bar", ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F0\r\nbar\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value="bar", ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F0\r\nbar\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=123, ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F2\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() value = [1, 2, 3] data = pickle.dumps(value, protocol=0) cache_pool.set(key=Key("foo"), value=value, ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo " + str(len(data)).encode() + b" T300 F1\r\n" + data + b"\r\n", with_noop=False, ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() value = False # Bools should be stored pickled data = pickle.dumps(value, protocol=0) cache_pool.set(key=Key("foo"), value=value, ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo " + str(len(data)).encode() + b" T300 F1\r\n" + data + b"\r\n", with_noop=False, ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=b"123", ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F16\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() value = b"123" * 100 data = zlib.compress(value) cache_pool.set(key=Key("foo"), value=value, ttl=300) memcache_socket.sendall.assert_called_once_with( b"ms foo " + str(len(data)).encode() + b" T300 F24\r\n" + data + b"\r\n", with_noop=False, ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=123, ttl=300, set_mode=SetMode.ADD) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F2 ME\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=123, ttl=300, set_mode=SetMode.APPEND) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F2 MA\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=123, ttl=300, set_mode=SetMode.PREPEND) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F2 MP\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=123, ttl=300, set_mode=SetMode.REPLACE) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 F2 MR\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=b"123", ttl=300, no_reply=True) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 q T300 F16\r\n123\r\n", with_noop=True ) memcache_socket.get_response.assert_not_called() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set(key=Key("foo"), value=b"123", ttl=300, cas_token=666) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 C666 F16\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set( key=Key("foo"), value=b"123", ttl=300, cas_token=666, stale_policy=StalePolicy() ) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 T300 C666 F16\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.set( key=Key("foo"), value=b"123", ttl=300, cas_token=666, stale_policy=StalePolicy(mark_stale_on_cas_mismatch=True), ) memcache_socket.sendall.assert_called_once_with( b"ms foo 3 I T300 C666 F16\r\n123\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() def test_set_cmd_1_6_6( memcache_socket_1_6_6: MemcacheSocket, cache_pool_1_6_6: FakeCachePool, ) -> None: memcache_socket_1_6_6.get_response.return_value = Success() cache_pool_1_6_6.set(key="foo", value="bar", ttl=300) memcache_socket_1_6_6.sendall.assert_called_once_with( b"ms foo S3 T300 F0\r\nbar\r\n", with_noop=False ) memcache_socket_1_6_6.get_response.assert_called_once_with() def test_set_success_fail( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, ) -> None: memcache_socket.get_response.return_value = Success() result = cache_pool.set(key=Key("foo"), value="bar", ttl=300) assert result is True memcache_socket.get_response.return_value = NotStored() result = cache_pool.set(key=Key("foo"), value="bar", ttl=300) assert result is False def test_delete_cmd( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, ) -> None: memcache_socket.get_response.return_value = Success() cache_pool.delete(key="foo") memcache_socket.sendall.assert_called_once_with(b"md foo\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.delete(key=Key("foo")) memcache_socket.sendall.assert_called_once_with(b"md foo\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.delete(key=Key("foo"), cas_token=666) memcache_socket.sendall.assert_called_once_with(b"md foo C666\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.delete(key=Key("foo"), no_reply=True) memcache_socket.sendall.assert_called_once_with(b"md foo q\r\n", with_noop=True) memcache_socket.get_response.assert_not_called() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.delete(key=Key("foo"), stale_policy=StalePolicy()) memcache_socket.sendall.assert_called_once_with(b"md foo\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.delete( key=Key("foo"), stale_policy=StalePolicy(mark_stale_on_deletion_ttl=30), ) memcache_socket.sendall.assert_called_once_with( b"md foo I T30\r\n", with_noop=False ) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() def test_delete_success_fail( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, ) -> None: memcache_socket.get_response.return_value = Success() result = cache_pool.delete(key=Key("foo")) assert result is True memcache_socket.get_response.return_value = NotStored() result = cache_pool.delete(key=Key("foo")) assert result is False def test_touch_cmd( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, ) -> None: memcache_socket.get_response.return_value = Success() cache_pool.touch(key="foo", ttl=60) memcache_socket.sendall.assert_called_once_with(b"mg foo T60\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.touch(key=Key("foo"), ttl=60) memcache_socket.sendall.assert_called_once_with(b"mg foo T60\r\n", with_noop=False) memcache_socket.get_response.assert_called_once_with() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() cache_pool.touch(key=Key("foo"), ttl=60, no_reply=True) memcache_socket.sendall.assert_called_once_with( b"mg foo q T60\r\n", with_noop=False ) memcache_socket.get_response.assert_not_called() memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() def test_get_cmd(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: memcache_socket.get_response.return_value = Miss() cache_pool.get(key="foo") memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get(key=Key("foo")) memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get(key=Key("foo"), touch_ttl=300) memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get(key=Key("foo"), recache_policy=RecachePolicy()) memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f R30\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get(key=Key("foo"), touch_ttl=300, recache_policy=RecachePolicy()) memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f R30 T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get( key=Key("large_key" * 50), touch_ttl=300, recache_policy=RecachePolicy() ) memcache_socket.sendall.assert_called_once_with( b"mg 4gCNJuSyOJPGW8kRddioRlPx b t l v c h f R30 T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() cache_pool.get( key=Key("úníçod⍷", is_unicode=True), touch_ttl=300, recache_policy=RecachePolicy(), ) memcache_socket.sendall.assert_called_once_with( b"mg lCV3WxKxtWrdY4s1+R710+9J b t l v c h f R30 T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() memcache_socket.get_response.return_value = Value(size=0) cache_pool.get_or_lease( key=Key("foo"), lease_policy=LeasePolicy(), touch_ttl=300, recache_policy=RecachePolicy(ttl=60), ) memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f N30 R60 T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() def test_get_miss(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: memcache_socket.get_response.return_value = Miss() result, cas_token = cache_pool.get_cas_typed(key=Key("foo"), cls=Foo) assert result is None assert cas_token is None memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() result = cache_pool.get_typed(key=Key("foo"), cls=Foo) assert result is None memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() result, cas_token = cache_pool.get_cas(key=Key("foo")) assert result is None assert cas_token is None memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() result = cache_pool.get(key=Key("foo")) assert result is None memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() def test_get_value(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.return_value = Value( size=len(encoded_value.data), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = encoded_value.data result, cas_token = cache_pool.get_cas_typed( key=Key("foo"), cls=Foo, ) assert result == expected_value assert cas_token == expected_cas_token result = cache_pool.get_typed(key=Key("foo"), cls=Foo) assert result == expected_value result, cas_token = cache_pool.get_cas(key=Key("foo")) assert result == expected_value assert cas_token == expected_cas_token result = cache_pool.get(key=Key("foo")) assert result == expected_value def test_get_other(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: memcache_socket.get_response.return_value = Success() try: cache_pool.get( key=Key("foo"), ) raise AssertionError("Should not be reached") except MemcacheError as e: assert "Unexpected response" in str(e) def test_value_wrong_type( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool ) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.return_value = Value( size=len(encoded_value.data), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = encoded_value.data result, cas_token = cache_pool.get_cas_typed(key=Key("foo"), cls=Bar) assert result is None assert cas_token == expected_cas_token memcache_socket.get_value.assert_called_once_with(len(encoded_value.data)) try: cache_pool.get_cas_typed(key=Key("foo"), cls=Bar, error_on_type_mismatch=True) raise AssertionError("Should not be reached") except ValueError as e: assert "Expecting <class 'tests.base.cache_pool_test.Bar'> got Foo" in str(e) result = cache_pool.get_typed(key=Key("foo"), cls=Bar) assert result is None try: cache_pool.get_typed(key=Key("foo"), cls=Bar, error_on_type_mismatch=True) raise AssertionError("Should not be reached") except ValueError as e: assert "Expecting <class 'tests.base.cache_pool_test.Bar'> got Foo" in str(e) @pytest.fixture def time(mocker: MockerFixture) -> MagicMock: return mocker.patch("meta_memcache.base.cache_pool.time", autospec=True) def test_recache_win_returns_miss( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.return_value = Value( size=len(encoded_value.data), flags=set([Flag.WIN, Flag.STALE]), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = encoded_value.data result, cas_token = cache_pool.get_cas(key=Key("foo")) assert result is None assert cas_token == expected_cas_token def test_recache_lost_returns_stale_value( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.return_value = Value( size=len(encoded_value.data), flags=set([Flag.LOST, Flag.STALE]), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = encoded_value.data result, cas_token = cache_pool.get_cas(key=Key("foo")) assert result == expected_value assert cas_token == expected_cas_token def test_get_or_lease_hit( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.return_value = Value( size=len(encoded_value.data), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = encoded_value.data result, cas_token = cache_pool.get_or_lease_cas( key=Key("foo"), lease_policy=LeasePolicy() ) assert result == expected_value assert cas_token == expected_cas_token memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f N30\r\n", with_noop=False ) memcache_socket.get_value.assert_called_once_with(len(encoded_value.data)) time.sleep.assert_not_called() def test_get_or_lease_miss_win( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 memcache_socket.get_response.return_value = Value( size=0, flags=set([Flag.WIN]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = b"" result, cas_token = cache_pool.get_or_lease_cas( key=Key("foo"), lease_policy=LeasePolicy() ) assert result is None assert cas_token == expected_cas_token memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f N30\r\n", with_noop=False ) memcache_socket.get_value.assert_called_once_with(0) time.sleep.assert_not_called() def test_get_or_lease_miss_lost_then_data( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 expected_value = Foo("hello world") encoded_value = MixedSerializer().serialize(expected_value) memcache_socket.get_response.side_effect = [ Value( size=0, flags=set([Flag.LOST]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token - 1, }, ), Value( size=0, flags=set([Flag.LOST]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token - 1, }, ), Value( size=len(encoded_value.data), int_flags={ IntFlag.CLIENT_FLAG: encoded_value.encoding_id, IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ), ] memcache_socket.get_value.side_effect = [b"", b"", encoded_value.data] result, cas_token = cache_pool.get_or_lease_cas( key=Key("foo"), lease_policy=LeasePolicy() ) assert result == expected_value assert cas_token == expected_cas_token memcache_socket.sendall.assert_has_calls( [ call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), ] ) memcache_socket.get_value.assert_has_calls( [ call(0), call(0), call(len(encoded_value.data)), ] ) time.sleep.assert_has_calls([call(1.0), call(1.2)]) def test_get_or_lease_miss_lost_then_win( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 memcache_socket.get_response.side_effect = [ Value( size=0, flags=set([Flag.LOST]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token - 1, }, ), Value( size=0, flags=set([Flag.LOST]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token - 1, }, ), Value( size=0, flags=set([Flag.WIN]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ), ] memcache_socket.get_value.side_effect = [b"", b"", b""] result, cas_token = cache_pool.get_or_lease_cas( key=Key("foo"), lease_policy=LeasePolicy() ) assert result is None assert cas_token == expected_cas_token memcache_socket.sendall.assert_has_calls( [ call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), ] ) memcache_socket.get_value.assert_has_calls( [ call(0), call(0), call(0), ] ) time.sleep.assert_has_calls([call(1.0), call(1.2)]) def test_get_or_lease_miss_runs_out_of_retries( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, time: MagicMock ) -> None: expected_cas_token = 123 memcache_socket.get_response.return_value = Value( size=0, flags=set([Flag.LOST]), int_flags={ IntFlag.RETURNED_CAS_TOKEN: expected_cas_token, }, ) memcache_socket.get_value.return_value = b"" result, cas_token = cache_pool.get_or_lease_cas( key=Key("foo"), lease_policy=LeasePolicy( miss_retries=4, wait_backoff_factor=10, miss_max_retry_wait=15 ), ) assert result is None assert cas_token == expected_cas_token memcache_socket.sendall.assert_has_calls( [ call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), call(b"mg foo t l v c h f N30\r\n", with_noop=False), ] ) memcache_socket.get_value.assert_has_calls( [ call(0), call(0), call(0), call(0), ] ) time.sleep.assert_has_calls([call(1.0), call(10.0), call(15.0)]) def test_get_or_lease_errors( memcache_socket: MemcacheSocket, cache_pool: FakeCachePool ) -> None: # We should never get a miss memcache_socket.get_response.return_value = Miss() try: cache_pool.get_or_lease( key=Key("foo"), lease_policy=LeasePolicy(), touch_ttl=300, recache_policy=RecachePolicy(ttl=60), ) raise AssertionError("Should not be reached") except MemcacheError: pass memcache_socket.sendall.assert_called_once_with( b"mg foo t l v c h f N30 R60 T300\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() try: cache_pool.get_or_lease( key=Key("foo"), lease_policy=LeasePolicy(miss_retries=-10), touch_ttl=300, recache_policy=RecachePolicy(ttl=60), ) raise AssertionError("Should not be reached") except ValueError as e: assert "Wrong lease_policy: miss_retries needs to be greater than 0" in str(e) def test_write_failure_tracker( # memcache_socket: MemcacheSocket, cache_pool: FakeCachePool, write_failure_tracker: BaseWriteFailureTracker, ) -> None: cache_pool.connection_pool.get_connection.side_effect = MemcacheServerError( server="broken:11211", message="uh-oh" ) try: cache_pool.get(key=Key("foo")) raise AssertionError("Should not be reached") except MemcacheServerError as e: assert "uh-oh" in str(e) write_failure_tracker.add_key.assert_not_called() try: cache_pool.delete(key=Key("foo")) raise AssertionError("Should not be reached") except MemcacheServerError as e: assert "uh-oh" in str(e) write_failure_tracker.add_key.assert_called_once_with(Key("foo")) write_failure_tracker.add_key.reset_mock() try: cache_pool.set(key=Key("foo"), value=1, ttl=10) raise AssertionError("Should not be reached") except MemcacheServerError as e: assert "uh-oh" in str(e) write_failure_tracker.add_key.assert_called_once_with(Key("foo")) write_failure_tracker.add_key.reset_mock() def test_delta_cmd(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: memcache_socket.get_response.return_value = Miss() cache_pool.delta(key="foo", delta=1, no_reply=True) memcache_socket.sendall.assert_called_once_with(b"ma foo q D1\r\n", with_noop=True) memcache_socket.sendall.reset_mock() cache_pool.delta(key=Key("foo"), delta=1, no_reply=True) memcache_socket.sendall.assert_called_once_with(b"ma foo q D1\r\n", with_noop=True) memcache_socket.sendall.reset_mock() cache_pool.delta(key=Key("foo"), delta=1, refresh_ttl=60, no_reply=True) memcache_socket.sendall.assert_called_once_with( b"ma foo q D1 T60\r\n", with_noop=True ) memcache_socket.sendall.reset_mock() cache_pool.delta(key=Key("foo"), delta=-2, no_reply=True) memcache_socket.sendall.assert_called_once_with( b"ma foo q D2 M-\r\n", with_noop=True ) memcache_socket.sendall.reset_mock() cache_pool.delta_initialize( key=Key("foo"), delta=1, initial_value=10, initial_ttl=60, no_reply=True, cas_token=123, ) memcache_socket.sendall.assert_called_once_with( b"ma foo q D1 C123 J10 N60\r\n", with_noop=True ) memcache_socket.sendall.reset_mock() memcache_socket.get_response.assert_not_called() result = cache_pool.delta(key=Key("foo"), delta=1) assert result is False memcache_socket.sendall.assert_called_once_with(b"ma foo D1\r\n", with_noop=False) memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() result = cache_pool.delta_and_get(key=Key("foo"), delta=1) assert result is None memcache_socket.sendall.assert_called_once_with(b"ma foo v D1\r\n", with_noop=False) memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() result = cache_pool.delta_initialize_and_get( key=Key("foo"), delta=1, initial_value=0, initial_ttl=60 ) assert result is None memcache_socket.sendall.assert_called_once_with( b"ma foo v D1 J0 N60\r\n", with_noop=False ) memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() memcache_socket.get_response.return_value = Success() result = cache_pool.delta(key=Key("foo"), delta=1) assert result is True memcache_socket.sendall.assert_called_once_with(b"ma foo D1\r\n", with_noop=False) memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() memcache_socket.get_response.return_value = Value(size=2) memcache_socket.get_value.return_value = b"10" result = cache_pool.delta_and_get(key=Key("foo"), delta=1) assert result == 10 memcache_socket.sendall.assert_called_once_with(b"ma foo v D1\r\n", with_noop=False) memcache_socket.sendall.reset_mock() memcache_socket.get_response.reset_mock() memcache_socket.get_value.reset_mock() def test_multi_get(memcache_socket: MemcacheSocket, cache_pool: FakeCachePool) -> None: memcache_socket.get_response.side_effect = [ Miss(), Value(size=2, int_flags={IntFlag.CLIENT_FLAG: MixedSerializer.BINARY}), Value(size=2, flags=set([Flag.WIN])), ] memcache_socket.get_value.return_value = b"OK" results = cache_pool.multi_get( keys=[ Key("miss"), Key("found"), Key("lease"), ] ) assert memcache_socket.sendall.mock_calls == [ call(b"mg miss t l v h f\r\n", with_noop=False), call(b"mg found t l v h f\r\n", with_noop=False), call(b"mg lease t l v h f\r\n", with_noop=False), ] assert memcache_socket.get_response.call_count == 3 assert memcache_socket.get_value.mock_calls == [ call(2), call(2), ] assert results == { Key("miss"): None, Key("found"): b"OK", Key("lease"): None, }
34.32319
88
0.698074
4,573
32,710
4.686202
0.056418
0.15483
0.080121
0.093327
0.89272
0.881335
0.869155
0.85133
0.84559
0.839851
0
0.019647
0.198624
32,710
952
89
34.359244
0.797848
0.002751
0
0.632226
0
0
0.070885
0.004538
0
0
0
0
0.184502
1
0.0369
false
0.00123
0.01722
0.00369
0.068881
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
b011bc8633bd17ed506f12f6b5aba04dbf8e07d2
87
py
Python
afs/lla/CacheManagerLLAError.py
chanke/afspy
525e7b3b53e58be515f11b83cc59ddb0765ef8e5
[ "BSD-2-Clause" ]
null
null
null
afs/lla/CacheManagerLLAError.py
chanke/afspy
525e7b3b53e58be515f11b83cc59ddb0765ef8e5
[ "BSD-2-Clause" ]
null
null
null
afs/lla/CacheManagerLLAError.py
chanke/afspy
525e7b3b53e58be515f11b83cc59ddb0765ef8e5
[ "BSD-2-Clause" ]
null
null
null
from afs.util.AFSError import AFSError class CacheManagerLLAError(AFSError): pass
17.4
38
0.804598
10
87
7
0.8
0
0
0
0
0
0
0
0
0
0
0
0.137931
87
4
39
21.75
0.933333
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.333333
0.333333
0
0.666667
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
1
1
0
1
0
0
6
b0506168d80e31db172bc727c2eb23873b1f83bb
13,550
py
Python
laserfiche_api/api/attributes_api.py
Layer8Err/laserfiche_api
8c9030c8f5cc245b61858bd096a1ad3c58cdbfd2
[ "BSD-2-Clause" ]
1
2021-06-17T23:51:25.000Z
2021-06-17T23:51:25.000Z
laserfiche_api/api/attributes_api.py
Layer8Err/laserfiche_api
8c9030c8f5cc245b61858bd096a1ad3c58cdbfd2
[ "BSD-2-Clause" ]
null
null
null
laserfiche_api/api/attributes_api.py
Layer8Err/laserfiche_api
8c9030c8f5cc245b61858bd096a1ad3c58cdbfd2
[ "BSD-2-Clause" ]
null
null
null
# coding: utf-8 """ Laserfiche API Welcome to the Laserfiche API Swagger Playground. You can try out any of our API calls against your live Laserfiche Cloud account. Visit the developer center for more details: <a href=\"https://developer.laserfiche.com\">https://developer.laserfiche.com</a><p><strong>Build# : </strong>650780</p> # noqa: E501 OpenAPI spec version: 1-alpha Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from laserfiche_api.api_client import ApiClient class AttributesApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_trustee_attribute_key_value_pairs(self, repo_id, **kwargs): # noqa: E501 """Get the attribute key value pairs associated with the authenticated user. # noqa: E501 - Returns the attribute key value pairs associated with the authenticated user. Alternatively, return only the attribute key value pairs that are associated with the \"Everyone\" group. - Attribute keys can be used with subsequent calls to get specific attribute values. - Allowed OData query options: Select, count, orderby. Optional query parameters : everyone (bool, default false). When true, this route does not return the attributes that are tied to the currently authenticated user, but rather the attributes assigned to the \"Everyone\" group. Note when this true, this response does not include both the \"Everyone\" groups attribute and the currently authenticated user, but only the \"Everyone\" groups. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_trustee_attribute_key_value_pairs(repo_id, async_req=True) >>> result = thread.get() :param async_req bool :param str repo_id: The requested repository id. (required) :param bool everyone: Boolean value that indicates whether to return attributes key value pairs associated with everyone or the currently authenticated user. :param str select: Limits the properties returned in the result. :param str orderby: Specifies the order in which items are returned. The maximum number of expressions is 5. :param bool count: Indicates whether the total count of items within a collection are returned in the result. :return: ODataValueOfListOfAttribute If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_trustee_attribute_key_value_pairs_with_http_info(repo_id, **kwargs) # noqa: E501 else: (data) = self.get_trustee_attribute_key_value_pairs_with_http_info(repo_id, **kwargs) # noqa: E501 return data def get_trustee_attribute_key_value_pairs_with_http_info(self, repo_id, **kwargs): # noqa: E501 """Get the attribute key value pairs associated with the authenticated user. # noqa: E501 - Returns the attribute key value pairs associated with the authenticated user. Alternatively, return only the attribute key value pairs that are associated with the \"Everyone\" group. - Attribute keys can be used with subsequent calls to get specific attribute values. - Allowed OData query options: Select, count, orderby. Optional query parameters : everyone (bool, default false). When true, this route does not return the attributes that are tied to the currently authenticated user, but rather the attributes assigned to the \"Everyone\" group. Note when this true, this response does not include both the \"Everyone\" groups attribute and the currently authenticated user, but only the \"Everyone\" groups. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_trustee_attribute_key_value_pairs_with_http_info(repo_id, async_req=True) >>> result = thread.get() :param async_req bool :param str repo_id: The requested repository id. (required) :param bool everyone: Boolean value that indicates whether to return attributes key value pairs associated with everyone or the currently authenticated user. :param str select: Limits the properties returned in the result. :param str orderby: Specifies the order in which items are returned. The maximum number of expressions is 5. :param bool count: Indicates whether the total count of items within a collection are returned in the result. :return: ODataValueOfListOfAttribute If the method is called asynchronously, returns the request thread. """ all_params = ['repo_id', 'everyone', 'select', 'orderby', 'count'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_trustee_attribute_key_value_pairs" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'repo_id' is set if ('repo_id' not in params or params['repo_id'] is None): raise ValueError("Missing the required parameter `repo_id` when calling `get_trustee_attribute_key_value_pairs`") # noqa: E501 collection_formats = {} path_params = {} if 'repo_id' in params: path_params['repoId'] = params['repo_id'] # noqa: E501 query_params = [] if 'everyone' in params: query_params.append(('everyone', params['everyone'])) # noqa: E501 if 'select' in params: query_params.append(('$select', params['select'])) # noqa: E501 if 'orderby' in params: query_params.append(('$orderby', params['orderby'])) # noqa: E501 if 'count' in params: query_params.append(('$count', params['count'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['Authorization'] # noqa: E501 return self.api_client.call_api( '/v1-alpha/Repositories/{repoId}/Attributes', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ODataValueOfListOfAttribute', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_trustee_attribute_value_by_key(self, repo_id, attribute_key, **kwargs): # noqa: E501 """Get an attribute object by key associated with the authenticated user. # noqa: E501 - Returns the attribute associated with the key. Alternatively, return the attribute associated with the key within \"Everyone\" group. - Optional query parameters : everyone (bool, default false). When true, the server only searches for the attribute value with the given key upon the authenticated users attributes. If false, only the authenticated users attributes will be queried. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_trustee_attribute_value_by_key(repo_id, attribute_key, async_req=True) >>> result = thread.get() :param async_req bool :param str repo_id: The requested repository id. (required) :param str attribute_key: The requested attribute key. (required) :param bool everyone: Boolean value that indicates whether to return attributes associated with everyone or the currently authenticated user. :return: Attribute If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_trustee_attribute_value_by_key_with_http_info(repo_id, attribute_key, **kwargs) # noqa: E501 else: (data) = self.get_trustee_attribute_value_by_key_with_http_info(repo_id, attribute_key, **kwargs) # noqa: E501 return data def get_trustee_attribute_value_by_key_with_http_info(self, repo_id, attribute_key, **kwargs): # noqa: E501 """Get an attribute object by key associated with the authenticated user. # noqa: E501 - Returns the attribute associated with the key. Alternatively, return the attribute associated with the key within \"Everyone\" group. - Optional query parameters : everyone (bool, default false). When true, the server only searches for the attribute value with the given key upon the authenticated users attributes. If false, only the authenticated users attributes will be queried. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_trustee_attribute_value_by_key_with_http_info(repo_id, attribute_key, async_req=True) >>> result = thread.get() :param async_req bool :param str repo_id: The requested repository id. (required) :param str attribute_key: The requested attribute key. (required) :param bool everyone: Boolean value that indicates whether to return attributes associated with everyone or the currently authenticated user. :return: Attribute If the method is called asynchronously, returns the request thread. """ all_params = ['repo_id', 'attribute_key', 'everyone'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_trustee_attribute_value_by_key" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'repo_id' is set if ('repo_id' not in params or params['repo_id'] is None): raise ValueError("Missing the required parameter `repo_id` when calling `get_trustee_attribute_value_by_key`") # noqa: E501 # verify the required parameter 'attribute_key' is set if ('attribute_key' not in params or params['attribute_key'] is None): raise ValueError("Missing the required parameter `attribute_key` when calling `get_trustee_attribute_value_by_key`") # noqa: E501 collection_formats = {} path_params = {} if 'repo_id' in params: path_params['repoId'] = params['repo_id'] # noqa: E501 if 'attribute_key' in params: path_params['attributeKey'] = params['attribute_key'] # noqa: E501 query_params = [] if 'everyone' in params: query_params.append(('everyone', params['everyone'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['Authorization'] # noqa: E501 return self.api_client.call_api( '/v1-alpha/Repositories/{repoId}/Attributes/{attributeKey}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Attribute', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
53.769841
736
0.674022
1,694
13,550
5.201299
0.138135
0.032686
0.036659
0.034956
0.896607
0.880944
0.876858
0.860629
0.855181
0.840767
0
0.01226
0.247528
13,550
251
737
53.984064
0.851903
0.503469
0
0.6875
0
0
0.210826
0.071521
0
0
0
0
0
1
0.039063
false
0
0.03125
0
0.125
0
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
b0646df301bf75184eea8336601f5fe48968d8f0
156
py
Python
model/loss.py
mohammadKhalifa/Bi-lateral-multiperspective-matching
9298f8fee7adb79e45e6700d21f22e8781b0bfe7
[ "MIT" ]
null
null
null
model/loss.py
mohammadKhalifa/Bi-lateral-multiperspective-matching
9298f8fee7adb79e45e6700d21f22e8781b0bfe7
[ "MIT" ]
null
null
null
model/loss.py
mohammadKhalifa/Bi-lateral-multiperspective-matching
9298f8fee7adb79e45e6700d21f22e8781b0bfe7
[ "MIT" ]
null
null
null
import torch.nn.functional as F from torch.nn import BCELoss def my_loss(y_input, y_target): loss = BCELoss() return loss(y_input, y_target)
22.285714
35
0.711538
26
156
4.076923
0.576923
0.132075
0.188679
0.207547
0.320755
0
0
0
0
0
0
0
0.205128
156
6
36
26
0.854839
0
0
0
0
0
0
0
0
0
0
0
0
1
0.2
false
0
0.4
0
0.8
0
1
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
1
0
1
0
0
6
c690d491755d74bf0544705a76b58dca151c8d9e
113
py
Python
testsmainnet/loantoken/test_LoanTokenLogicStandardEvents.py
syuukawa/contractsV2
71d7ef458c9d8f98823d1c28f711f7b0e5286520
[ "Apache-2.0" ]
null
null
null
testsmainnet/loantoken/test_LoanTokenLogicStandardEvents.py
syuukawa/contractsV2
71d7ef458c9d8f98823d1c28f711f7b0e5286520
[ "Apache-2.0" ]
null
null
null
testsmainnet/loantoken/test_LoanTokenLogicStandardEvents.py
syuukawa/contractsV2
71d7ef458c9d8f98823d1c28f711f7b0e5286520
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 import pytest from brownie import * from fixedint import * from helpers import setupLoanPool
16.142857
33
0.79646
15
113
6
0.666667
0.222222
0
0
0
0
0
0
0
0
0
0.010309
0.141593
113
6
34
18.833333
0.917526
0.150442
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
c6c137ebc7be25480f8135fd743c6d1e0933bc9f
33
py
Python
gnfetcher/__init__.py
aadu999/gnfetcher
f080de54ca8028ef44677f3eb7ac28139eee7453
[ "MIT" ]
null
null
null
gnfetcher/__init__.py
aadu999/gnfetcher
f080de54ca8028ef44677f3eb7ac28139eee7453
[ "MIT" ]
null
null
null
gnfetcher/__init__.py
aadu999/gnfetcher
f080de54ca8028ef44677f3eb7ac28139eee7453
[ "MIT" ]
null
null
null
from .gnfetcher import gnfetcher
16.5
32
0.848485
4
33
7
0.75
0
0
0
0
0
0
0
0
0
0
0
0.121212
33
1
33
33
0.965517
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
05fb40489b18e6e516071861d764f4eada39cf52
30
py
Python
package/numbers/__init__.py
venkateshvsn/patterns
7e1d1926b40695a65e04c370655c5d79dd63bf6e
[ "MIT" ]
null
null
null
package/numbers/__init__.py
venkateshvsn/patterns
7e1d1926b40695a65e04c370655c5d79dd63bf6e
[ "MIT" ]
null
null
null
package/numbers/__init__.py
venkateshvsn/patterns
7e1d1926b40695a65e04c370655c5d79dd63bf6e
[ "MIT" ]
null
null
null
print('patterns of numbers')
15
29
0.733333
4
30
5.5
1
0
0
0
0
0
0
0
0
0
0
0
0.133333
30
1
30
30
0.846154
0
0
0
0
0
0.655172
0
0
0
0
0
0
1
0
true
0
0
0
0
1
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
1
0
null
0
0
0
0
0
0
1
0
0
0
0
1
0
6
af7946e225c363412c88f52646d73aff467ea4f3
42
py
Python
src/data/__init__.py
gokhankesler/tensorflow-archive
0625c12e3b63bedcad441a503a342697edb40c78
[ "MIT" ]
null
null
null
src/data/__init__.py
gokhankesler/tensorflow-archive
0625c12e3b63bedcad441a503a342697edb40c78
[ "MIT" ]
null
null
null
src/data/__init__.py
gokhankesler/tensorflow-archive
0625c12e3b63bedcad441a503a342697edb40c78
[ "MIT" ]
null
null
null
#!/usr/bin/python from .get_data import *
14
23
0.714286
7
42
4.142857
1
0
0
0
0
0
0
0
0
0
0
0
0.119048
42
3
23
14
0.783784
0.380952
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
af7bdd577bdc314776603cf42fa549a2c7bdfffb
35
py
Python
ctrnn_cpg/__init__.py
Karabazmos/neat-python
f779585553f29aec1513a1260852c9ad24967dbe
[ "BSD-3-Clause" ]
null
null
null
ctrnn_cpg/__init__.py
Karabazmos/neat-python
f779585553f29aec1513a1260852c9ad24967dbe
[ "BSD-3-Clause" ]
null
null
null
ctrnn_cpg/__init__.py
Karabazmos/neat-python
f779585553f29aec1513a1260852c9ad24967dbe
[ "BSD-3-Clause" ]
null
null
null
"Run NEAT algorithm for CTRNN-CPG."
35
35
0.771429
6
35
4.5
1
0
0
0
0
0
0
0
0
0
0
0
0.114286
35
1
35
35
0.870968
0.942857
0
0
0
0
0.916667
0
0
0
0
0
0
1
0
true
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
1
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
6
af890c6c633c4e4bd07f7cfd3ad6f834be7f2ade
80
py
Python
lib/candy_editor/qt/controls/SearchView/__init__.py
lihaochen910/Candy
d12cb964768459c22f30c22531d3e1734901e814
[ "MIT" ]
1
2021-11-06T14:38:37.000Z
2021-11-06T14:38:37.000Z
lib/candy_editor/qt/controls/SearchView/__init__.py
lihaochen910/Candy
d12cb964768459c22f30c22531d3e1734901e814
[ "MIT" ]
5
2021-11-06T04:23:06.000Z
2022-03-12T01:03:25.000Z
lib/candy_editor/qt/controls/SearchView/__init__.py
lihaochen910/Candy
d12cb964768459c22f30c22531d3e1734901e814
[ "MIT" ]
1
2021-11-07T05:19:51.000Z
2021-11-07T05:19:51.000Z
from .SearchView import SearchView, requestSearchView, registerSearchEnumerator
40
79
0.8875
6
80
11.833333
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.075
80
1
80
80
0.959459
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
afd4e9883df72f97d3a7d58efe59d4913a006bf6
224
py
Python
stellar_model/model/horizon/price.py
MartinThoma/stellar-model
a21969f3d1aac1e95cb32747d54b72a30e21dda9
[ "Apache-2.0" ]
8
2021-04-25T09:58:39.000Z
2022-01-22T05:01:37.000Z
stellar_model/model/horizon/price.py
MartinThoma/stellar-model
a21969f3d1aac1e95cb32747d54b72a30e21dda9
[ "Apache-2.0" ]
8
2021-06-02T12:46:21.000Z
2021-11-29T01:23:42.000Z
stellar_model/model/horizon/price.py
MartinThoma/stellar-model
a21969f3d1aac1e95cb32747d54b72a30e21dda9
[ "Apache-2.0" ]
3
2021-07-21T03:58:05.000Z
2021-08-01T00:03:11.000Z
from pydantic import BaseModel from pydantic import Field class Price(BaseModel): """ Represents a price """ n: int = Field(description="The numerator.") d: int = Field(description="The denominator.")
18.666667
50
0.674107
26
224
5.807692
0.615385
0.15894
0.238411
0.291391
0
0
0
0
0
0
0
0
0.214286
224
11
51
20.363636
0.857955
0.080357
0
0
0
0
0.157895
0
0
0
0
0
0
1
0
true
0
0.4
0
1
0
1
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
1
0
1
0
0
6
bb6a454f9df5b3bcb5d21a18dc27aa89f515a9bc
39
py
Python
src/data/transform_data.py
wiflore/ds-template
94a97fb3ed7588144653eda5a7cf7c9ac91d732f
[ "MIT" ]
null
null
null
src/data/transform_data.py
wiflore/ds-template
94a97fb3ed7588144653eda5a7cf7c9ac91d732f
[ "MIT" ]
14
2020-12-26T23:41:53.000Z
2020-12-28T14:32:23.000Z
src/data/transform_data.py
wiflore/ds-template
94a97fb3ed7588144653eda5a7cf7c9ac91d732f
[ "MIT" ]
2
2021-03-27T00:12:42.000Z
2021-11-20T12:54:52.000Z
import logging from pathlib import Path
19.5
24
0.871795
6
39
5.666667
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.128205
39
2
24
19.5
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
bbc861f333d742363473afc376945b26b4624186
39
py
Python
amd64-linux/lib/python/mod_ebony_fpga_commands.py
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
1
2020-06-15T10:41:18.000Z
2020-06-15T10:41:18.000Z
amd64-linux/lib/python/mod_ebony_fpga_commands.py
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
null
null
null
amd64-linux/lib/python/mod_ebony_fpga_commands.py
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
3
2020-08-10T10:25:02.000Z
2021-09-12T01:12:09.000Z
from cli import * import sim_commands
9.75
19
0.794872
6
39
5
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.179487
39
3
20
13
0.9375
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
bbf6cfd9b22ac423cc8ededad1777e3b0693673b
201
py
Python
model/helpers/__init__.py
dc-avasilev/testing-api
3f46406daa7e9145352e8cfba0878b2b3df510c6
[ "MIT" ]
1
2021-09-13T21:37:58.000Z
2021-09-13T21:37:58.000Z
model/helpers/__init__.py
dc-avasilev/testing-api
3f46406daa7e9145352e8cfba0878b2b3df510c6
[ "MIT" ]
null
null
null
model/helpers/__init__.py
dc-avasilev/testing-api
3f46406daa7e9145352e8cfba0878b2b3df510c6
[ "MIT" ]
null
null
null
from .json_helper import ( AlternateJsonEncoder, JsonHelper ) from .log_helper import LogHelper from .logger import Logger from .xml_helper import XMLHelper from .yaml_helper import YamlHelper
22.333333
35
0.80597
25
201
6.32
0.52
0.303797
0
0
0
0
0
0
0
0
0
0
0.154229
201
8
36
25.125
0.929412
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.625
0
0.625
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
1
0
1
0
1
0
0
6
a54854fb7adb5303713ee66af8603ea190f50c8a
437
py
Python
tests/test_utils.py
ashlylau/PyStatDP
42a2497b38b0df6a1528b255e994aa332e41f9ea
[ "MIT" ]
8
2020-07-25T02:54:24.000Z
2021-02-25T12:56:03.000Z
tests/test_utils.py
ashlylau/PyStatDP
42a2497b38b0df6a1528b255e994aa332e41f9ea
[ "MIT" ]
11
2020-08-19T08:24:49.000Z
2021-06-29T05:42:12.000Z
tests/test_utils.py
ashlylau/PyStatDP
42a2497b38b0df6a1528b255e994aa332e41f9ea
[ "MIT" ]
7
2020-10-19T14:43:55.000Z
2021-06-05T08:23:43.000Z
from pystatdp.utils import arr_n_check def test_negative_privacy(): assert arr_n_check(-0.9, 0.5, 3) == (0.4,0.9,1.4) def test_callable(): assert callable(arr_n_check) def test_inappropriats_n_checks(): assert arr_n_check(0.9, 0.5, -3) == (0.4,0.9,1.4) def test_inappropriats_n_checks1(): assert arr_n_check(0.9, 0.5, 4) == (0.4,0.9,1.4) def test_very_large_test_range(): assert arr_n_check(0.9, 1, 5) == (0.9,)
25.705882
53
0.677346
90
437
3.011111
0.277778
0.059041
0.199262
0.221402
0.542435
0.424354
0.361624
0.361624
0.243542
0.243542
0
0.107527
0.148741
437
16
54
27.3125
0.620968
0
0
0
0
0
0
0
0
0
0
0
0.454545
1
0.454545
true
0
0.090909
0
0.545455
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
1
0
1
1
0
0
0
1
0
0
6
a54a3b4c00161b37ba226676dfc70cbc38823626
6
py
Python
seven.py
15637945839/first
b92de2797e99f9b0a0fa771ccb27a248397ba405
[ "MIT" ]
null
null
null
seven.py
15637945839/first
b92de2797e99f9b0a0fa771ccb27a248397ba405
[ "MIT" ]
null
null
null
seven.py
15637945839/first
b92de2797e99f9b0a0fa771ccb27a248397ba405
[ "MIT" ]
null
null
null
i = 7
3
5
0.333333
2
6
1
1
0
0
0
0
0
0
0
0
0
0
0.333333
0.5
6
1
6
6
0.333333
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
1
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
a5a9210a8ccb384442c73a41f8fc32597fd83b08
1,120
py
Python
src/test.py
sihrc/2048-Python-ML
c61a85deb9dcb3a4183c59fb33ef5ca9c9b5a824
[ "MIT" ]
1
2017-01-03T22:02:44.000Z
2017-01-03T22:02:44.000Z
src/test.py
sihrc/2048-Python-ML
c61a85deb9dcb3a4183c59fb33ef5ca9c9b5a824
[ "MIT" ]
null
null
null
src/test.py
sihrc/2048-Python-ML
c61a85deb9dcb3a4183c59fb33ef5ca9c9b5a824
[ "MIT" ]
null
null
null
import unittest from model import Model import numpy as np class DirectionTests(unittest.TestCase): def test_up(self): model = Model() model.grid = np.array([[0,0,0,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]) model.up() self.assertTrue((np.array([[0,0,0,0],[2,0,0,0],[0,0,0,0],[0,0,0,0]]) == model.grid).all()) def test_down(self): model = Model() model.grid = np.array([[0,0,0,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]) model.down() self.assertTrue((np.array([[0,0,0,0],[0,0,0,2],[0,0,0,0],[0,0,0,0]]) == model.grid).all()) def test_right(self): model = Model() model.grid = np.array([[0,0,0,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]) model.right() self.assertTrue((np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,2,0]]) == model.grid).all()) def test_left(self): model = Model() model.grid = np.array([[0,0,0,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]) model.left() self.assertTrue((np.array([[0,0,2,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]) == model.grid).all()) if __name__ == "__main__": unittest.main()
32.941176
98
0.514286
223
1,120
2.529148
0.116592
0.368794
0.473404
0.531915
0.746454
0.746454
0.675532
0.675532
0.638298
0.634752
0
0.142222
0.196429
1,120
34
99
32.941176
0.484444
0
0
0.307692
0
0
0.007136
0
0
0
0
0
0.153846
1
0.153846
false
0
0.115385
0
0.307692
0
0
0
0
null
1
1
1
0
1
0
0
0
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
a5b5bc7711b23d1b0dc7479dabc2515097d87663
155
py
Python
ps4you/client/admin.py
bogomaz1987/ps4you
7222425fb469dd966ba33de11405b9aa5e37ba67
[ "Apache-2.0" ]
null
null
null
ps4you/client/admin.py
bogomaz1987/ps4you
7222425fb469dd966ba33de11405b9aa5e37ba67
[ "Apache-2.0" ]
2
2020-06-05T17:41:58.000Z
2021-06-01T22:00:29.000Z
ps4you/client/admin.py
bogomaz1987/ps4you
7222425fb469dd966ba33de11405b9aa5e37ba67
[ "Apache-2.0" ]
null
null
null
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from client.models import Client admin.site.register(Client, UserAdmin)
22.142857
47
0.832258
22
155
5.863636
0.5
0.155039
0.263566
0
0
0
0
0
0
0
0
0
0.103226
155
6
48
25.833333
0.928058
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.75
0
0.75
0
1
0
0
null
0
1
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
1
0
1
0
0
6
3c22044f77a239e0bc8c2735144d7cc0bff5fff1
120
py
Python
testmath.py
asfanmuhd/py4fun
2f89a155d28654a140ea557190d8b013d9b5faf7
[ "Unlicense" ]
null
null
null
testmath.py
asfanmuhd/py4fun
2f89a155d28654a140ea557190d8b013d9b5faf7
[ "Unlicense" ]
null
null
null
testmath.py
asfanmuhd/py4fun
2f89a155d28654a140ea557190d8b013d9b5faf7
[ "Unlicense" ]
null
null
null
x=int(2) y=int(2) z=y**x*y**x A=z**z print("wait_._._._._._._._._._._._._._._._._._._._._._._._") print(A**A)
13.333333
61
0.483333
19
120
1.789474
0.421053
0.235294
0
0
0
0
0
0
0
0
0
0.019231
0.133333
120
8
62
15
0.307692
0
0
0
0
0.166667
0.463636
0.463636
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
1
0
1
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
3c41a151dffea0d7bbf3a47bb47603d76fb8f42c
303
py
Python
electrumsv/wallet_database/migrations/__init__.py
electrumsv/electrumsv
a2d9027ccec338cadfca778888e6ef7f077b1651
[ "MIT" ]
136
2019-01-10T15:49:09.000Z
2022-02-20T04:46:39.000Z
electrumsv/wallet_database/migrations/__init__.py
electrumsv/electrumsv
a2d9027ccec338cadfca778888e6ef7f077b1651
[ "MIT" ]
790
2019-01-07T01:53:35.000Z
2022-03-30T23:04:28.000Z
electrumsv/wallet_database/migrations/__init__.py
electrumsv/electrumsv
a2d9027ccec338cadfca778888e6ef7f077b1651
[ "MIT" ]
65
2019-01-10T23:55:30.000Z
2021-12-19T06:47:13.000Z
from . import migration_0022_create_database from . import migration_0023_add_wallet_events from . import migration_0024_account_transactions from . import migration_0025_invoices from . import migration_0026_txo_coinbase_flag from . import migration_0027_tx_refactor2 from . import migration_0028_mapi
37.875
49
0.884488
42
303
5.880952
0.571429
0.283401
0.538462
0
0
0
0
0
0
0
0
0.105455
0.092409
303
7
50
43.285714
0.792727
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
1
1
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
1
0
1
0
0
6
3c5201513ede8a86c4dbaa5b69dc94dbd8c4ae1b
96
py
Python
venv/lib/python3.8/site-packages/cachy/helpers.py
Retraces/UkraineBot
3d5d7f8aaa58fa0cb8b98733b8808e5dfbdb8b71
[ "MIT" ]
2
2022-03-13T01:58:52.000Z
2022-03-31T06:07:54.000Z
venv/lib/python3.8/site-packages/cachy/helpers.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
19
2021-11-20T04:09:18.000Z
2022-03-23T15:05:55.000Z
venv/lib/python3.8/site-packages/cachy/helpers.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
null
null
null
/home/runner/.cache/pip/pool/a4/34/86/1fb303d8046fba694f97a2a1c9c14720ffd0424e4ab16440e957ecd3c5
96
96
0.895833
9
96
9.555556
1
0
0
0
0
0
0
0
0
0
0
0.427083
0
96
1
96
96
0.46875
0
0
0
0
0
0
0
0
1
0
0
0
0
null
null
0
0
null
null
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
1
0
0
0
1
0
0
0
0
0
0
0
0
6
b1af09d5d7ed57fdb98065637e063323216450d5
285
py
Python
algorithms/LearningAlgorithm.py
lucaspg96/pattern-recognition
ba78c90795e9074825436e5cf5d394cedf869225
[ "MIT" ]
1
2018-11-08T00:59:15.000Z
2018-11-08T00:59:15.000Z
algorithms/LearningAlgorithm.py
lucaspg96/pattern-recognition
ba78c90795e9074825436e5cf5d394cedf869225
[ "MIT" ]
null
null
null
algorithms/LearningAlgorithm.py
lucaspg96/pattern-recognition
ba78c90795e9074825436e5cf5d394cedf869225
[ "MIT" ]
null
null
null
import abc class LearningAlgorithm(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def fit(self,X,Y,itter=100): return @abc.abstractmethod def predict(self,X): return @abc.abstractmethod def score(self,X,Y): return
17.8125
32
0.603509
32
285
5.25
0.53125
0.303571
0.357143
0.309524
0
0
0
0
0
0
0
0.015075
0.301754
285
16
33
17.8125
0.829146
0
0
0.5
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.083333
0.25
0.75
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
1
0
0
0
1
1
0
0
6
b1b6d53f78d7366295c47c4f922b90f1d070c84d
173
py
Python
src/learners/__init__.py
data-sachez-2511/pl_classification
637b85c58d723925ae4d3fce08db2842786c750a
[ "MIT" ]
8
2021-11-13T19:21:36.000Z
2021-12-14T15:00:16.000Z
src/learners/__init__.py
data-sachez-2511/pl_classification
637b85c58d723925ae4d3fce08db2842786c750a
[ "MIT" ]
6
2021-11-11T13:05:21.000Z
2021-12-13T09:59:05.000Z
src/learners/__init__.py
data-sachez-2511/pl_classification
637b85c58d723925ae4d3fce08db2842786c750a
[ "MIT" ]
null
null
null
from learners.classificator_learner import ClassificatorLearner from learners.regressor_learner import RegressorLearner from learners.triplets_learner import TripletsLearner
57.666667
63
0.919075
18
173
8.666667
0.555556
0.230769
0
0
0
0
0
0
0
0
0
0
0.063584
173
3
64
57.666667
0.962963
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
5932601a32770f3184798cb13a001457cf2bf20a
35
py
Python
part4/second.py
MADTeacher/python_basics
06ae43d8063c1c8426a4fbb53443b6d1ee727951
[ "MIT" ]
null
null
null
part4/second.py
MADTeacher/python_basics
06ae43d8063c1c8426a4fbb53443b6d1ee727951
[ "MIT" ]
null
null
null
part4/second.py
MADTeacher/python_basics
06ae43d8063c1c8426a4fbb53443b6d1ee727951
[ "MIT" ]
4
2020-10-04T12:24:14.000Z
2022-01-16T17:01:59.000Z
def function(): print('second')
17.5
19
0.628571
4
35
5.5
1
0
0
0
0
0
0
0
0
0
0
0
0.171429
35
2
19
17.5
0.758621
0
0
0
0
0
0.166667
0
0
0
0
0
0
1
0.5
true
0
0
0
0.5
0.5
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
1
1
0
0
0
0
1
0
6
594258bfc74a9198da848394264f3ce2783faed4
18
py
Python
src/bnn/inference/__init__.py
beauCoker/variable_selection
174278c81192940a3faea76b43384f25c4ba2c13
[ "MIT" ]
null
null
null
src/bnn/inference/__init__.py
beauCoker/variable_selection
174278c81192940a3faea76b43384f25c4ba2c13
[ "MIT" ]
null
null
null
src/bnn/inference/__init__.py
beauCoker/variable_selection
174278c81192940a3faea76b43384f25c4ba2c13
[ "MIT" ]
1
2021-03-09T18:09:31.000Z
2021-03-09T18:09:31.000Z
from . import mcmc
18
18
0.777778
3
18
4.666667
1
0
0
0
0
0
0
0
0
0
0
0
0.166667
18
1
18
18
0.933333
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
3cf892237c320c61ccd7f51376f30b1e58d07a30
32
py
Python
src/ftp_himawari8_hsd/__init__.py
gSasikala/ftp-himawari8-hsd
c83c2e0579ec592d982858c599bd392ea24935f5
[ "MIT" ]
5
2021-11-20T07:37:49.000Z
2022-03-18T02:56:02.000Z
src/ftp_himawari8_hsd/__init__.py
gSasikala/ftp-himawari8-hsd
c83c2e0579ec592d982858c599bd392ea24935f5
[ "MIT" ]
null
null
null
src/ftp_himawari8_hsd/__init__.py
gSasikala/ftp-himawari8-hsd
c83c2e0579ec592d982858c599bd392ea24935f5
[ "MIT" ]
1
2021-07-05T09:13:13.000Z
2021-07-05T09:13:13.000Z
from .ftp_himawari8_hsd import *
32
32
0.84375
5
32
5
1
0
0
0
0
0
0
0
0
0
0
0.034483
0.09375
32
1
32
32
0.827586
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
a72f370291f1d121e59b9569baa39f942d4ad8fc
142
py
Python
pyleecan/Methods/Machine/WindingCW1L/__init__.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
null
null
null
pyleecan/Methods/Machine/WindingCW1L/__init__.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
null
null
null
pyleecan/Methods/Machine/WindingCW1L/__init__.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from ....Methods.Machine.Winding import WindingError class WindingT2DefNtError(WindingError): """ """ pass
15.777778
52
0.65493
13
142
7.153846
0.923077
0
0
0
0
0
0
0
0
0
0
0.017094
0.176056
142
8
53
17.75
0.777778
0.147887
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.333333
0.333333
0
0.666667
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
1
1
0
1
0
0
6
59a69126470ee61c9fe0a47cc3f3ef0d0ccfb68b
70
py
Python
test.py
saninstein/test
cae28125d611224e45408221735a14b38d21c727
[ "MIT" ]
1
2021-02-11T12:19:12.000Z
2021-02-11T12:19:12.000Z
test.py
saninstein/test
cae28125d611224e45408221735a14b38d21c727
[ "MIT" ]
1
2020-05-21T01:40:21.000Z
2020-05-21T14:52:01.000Z
test.py
saninstein/test
cae28125d611224e45408221735a14b38d21c727
[ "MIT" ]
null
null
null
from simplesum import ssum def test(): assert ssum([0, 1]) == 1
11.666667
28
0.614286
11
70
3.909091
0.818182
0
0
0
0
0
0
0
0
0
0
0.056604
0.242857
70
5
29
14
0.754717
0
0
0
0
0
0
0
0
0
0
0
0.333333
1
0.333333
true
0
0.333333
0
0.666667
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
1
0
1
0
1
0
0
6
59c36e5729cd3d9da44a0604c7b278c759ff175b
25
py
Python
scf_add/__init__.py
duyixian1234/scf_add
ec7c1ee4f93c4997b4406c82d5c0ce28a0b09988
[ "MIT" ]
1
2020-02-21T07:27:58.000Z
2020-02-21T07:27:58.000Z
scf_add/__init__.py
duyixian1234/scf_add
ec7c1ee4f93c4997b4406c82d5c0ce28a0b09988
[ "MIT" ]
null
null
null
scf_add/__init__.py
duyixian1234/scf_add
ec7c1ee4f93c4997b4406c82d5c0ce28a0b09988
[ "MIT" ]
null
null
null
from .command import main
25
25
0.84
4
25
5.25
1
0
0
0
0
0
0
0
0
0
0
0
0.12
25
1
25
25
0.954545
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
abb8ec320cdf70e6557337a6b9e25805651cc198
42
py
Python
__init__.py
obtitus/pysiprefix
2f7f5ba073baf486242b5ea3b9a984e03ab60981
[ "Unlicense" ]
null
null
null
__init__.py
obtitus/pysiprefix
2f7f5ba073baf486242b5ea3b9a984e03ab60981
[ "Unlicense" ]
null
null
null
__init__.py
obtitus/pysiprefix
2f7f5ba073baf486242b5ea3b9a984e03ab60981
[ "Unlicense" ]
null
null
null
from eUnit import * from siunitx import *
14
21
0.761905
6
42
5.333333
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.190476
42
2
22
21
0.941176
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
f9eeb74bc0d7439aef50c194ae2530a92923f464
8,370
py
Python
tests/cli/test_show_tree.py
EddLabs/eddington-static
cdd1d9514c4eea1bd06c24894b3922e6cc3fb1f5
[ "Apache-2.0" ]
null
null
null
tests/cli/test_show_tree.py
EddLabs/eddington-static
cdd1d9514c4eea1bd06c24894b3922e6cc3fb1f5
[ "Apache-2.0" ]
null
null
null
tests/cli/test_show_tree.py
EddLabs/eddington-static
cdd1d9514c4eea1bd06c24894b3922e6cc3fb1f5
[ "Apache-2.0" ]
null
null
null
from pathlib import Path from pytest_cases import THIS_MODULE, parametrize_with_cases from statue.cli import statue_cli from statue.commands_filter import CommandsFilter from statue.context import Context from tests.constants import ( COMMAND1, COMMAND2, COMMAND3, CONTEXT1, CONTEXT2, CONTEXT_HELP_STRING1, CONTEXT_HELP_STRING2, SOURCE1, SOURCE2, ) from tests.util import command_mock def case_no_sources(): commands_lists = [] printed_tree = "No sources configuration is specified.\n" additional_args = [] return commands_lists, printed_tree, additional_args def case_one_source_empty_configuration(mock_build_configuration_from_file): configuration = mock_build_configuration_from_file.return_value configuration.sources_repository[Path(SOURCE1)] = CommandsFilter() commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} (contexts: empty, allowed: empty, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = [] return commands_lists, printed_tree, additional_args def case_one_source_with_configuration(mock_build_configuration_from_file): context = Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter( contexts=[context], allowed_commands=[COMMAND1] ) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} (contexts: {CONTEXT1}, allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = [] return commands_lists, printed_tree, additional_args def case_one_source_with_multiple_contexts(mock_build_configuration_from_file): context1, context2 = ( Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1), Context(name=CONTEXT2, help=CONTEXT_HELP_STRING2), ) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context1, context2) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter( contexts=[context1, context2], allowed_commands=[COMMAND1] ) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} (contexts: {CONTEXT1}, {CONTEXT2}, " f"allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = [] return commands_lists, printed_tree, additional_args def case_multiple_sources(mock_build_configuration_from_file): context1, context2 = ( Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1), Context(name=CONTEXT2, help=CONTEXT_HELP_STRING2), ) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context1, context2) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter( contexts=[context1, context2], allowed_commands=[COMMAND1] ) configuration.sources_repository[Path(SOURCE2)] = CommandsFilter( denied_commands=[COMMAND2, COMMAND3] ) commands_lists = [ [command_mock(name=COMMAND1)], [command_mock(name=COMMAND2), command_mock(name=COMMAND3)], ] printed_tree = ( f"{SOURCE1} (contexts: {CONTEXT1}, {CONTEXT2}, " f"allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" f"{SOURCE2} (contexts: empty, " f"allowed: empty, denied: {COMMAND2}, {COMMAND3}):\n" f"\t{COMMAND2}, {COMMAND3}\n" ) additional_args = [] return commands_lists, printed_tree, additional_args def case_with_context(mock_build_configuration_from_file): configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts( Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) ) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter( allowed_commands=[COMMAND1] ) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} (contexts: {CONTEXT1}, allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = ["-c", CONTEXT1] return commands_lists, printed_tree, additional_args def case_with_two_contexts(mock_build_configuration_from_file): configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts( Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1), Context(name=CONTEXT2, help=CONTEXT_HELP_STRING2), ) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter( allowed_commands=[COMMAND1] ) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} " f"(contexts: {CONTEXT1}, {CONTEXT2}, allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = ["-c", CONTEXT1, "-c", CONTEXT2] return commands_lists, printed_tree, additional_args def case_with_allowed_command(mock_build_configuration_from_file): context = Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter(contexts=[context]) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} " f"(contexts: {CONTEXT1}, allowed: {COMMAND1}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = ["-a", COMMAND1] return commands_lists, printed_tree, additional_args def case_with_two_allowed_commands(mock_build_configuration_from_file): context = Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter(contexts=[context]) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} " f"(contexts: {CONTEXT1}, allowed: {COMMAND1}, {COMMAND2}, denied: empty):\n" f"\t{COMMAND1}\n" ) additional_args = ["-a", COMMAND1, "-a", COMMAND2] return commands_lists, printed_tree, additional_args def case_with_denied_command(mock_build_configuration_from_file): context = Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter(contexts=[context]) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} " f"(contexts: {CONTEXT1}, allowed: empty, denied: {COMMAND1}):\n" f"\t{COMMAND1}\n" ) additional_args = ["-d", COMMAND1] return commands_lists, printed_tree, additional_args def case_with_two_denied_commands(mock_build_configuration_from_file): context = Context(name=CONTEXT1, help=CONTEXT_HELP_STRING1) configuration = mock_build_configuration_from_file.return_value configuration.contexts_repository.add_contexts(context) configuration.sources_repository[Path(SOURCE1)] = CommandsFilter(contexts=[context]) commands_lists = [[command_mock(name=COMMAND1)]] printed_tree = ( f"{SOURCE1} " f"(contexts: {CONTEXT1}, allowed: empty, denied: {COMMAND1}, {COMMAND2}):\n" f"\t{COMMAND1}\n" ) additional_args = ["-d", COMMAND1, "-d", COMMAND2] return commands_lists, printed_tree, additional_args @parametrize_with_cases( argnames=["commands_lists", "printed_tree", "additional_args"], cases=THIS_MODULE ) def test_config_show_tree( commands_lists, printed_tree, additional_args, cli_runner, mock_build_configuration_from_file, ): configuration = mock_build_configuration_from_file.return_value configuration.build_commands.side_effect = commands_lists result = cli_runner.invoke(statue_cli, ["show-tree", *additional_args]) assert ( result.exit_code == 0 ), f"Exited with error code. exception: {result.exception}" assert result.output == printed_tree
38.219178
88
0.726882
936
8,370
6.175214
0.086538
0.056228
0.083737
0.098962
0.833045
0.833045
0.799135
0.799135
0.788754
0.778028
0
0.019087
0.167503
8,370
218
89
38.394495
0.810419
0
0
0.53125
0
0
0.139188
0
0
0
0
0
0.010417
1
0.0625
false
0
0.036458
0
0.15625
0.130208
0
0
0
null
0
0
0
1
1
1
1
1
1
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
6
f9f4d6d3bdb526b4117ada26d91a3918a7add5b3
49
py
Python
utils/src/main.py
wangzhefeng/data-analysis
e502ac49ae1bc8287243e1faf51c467cc4d4187c
[ "MIT" ]
null
null
null
utils/src/main.py
wangzhefeng/data-analysis
e502ac49ae1bc8287243e1faf51c467cc4d4187c
[ "MIT" ]
null
null
null
utils/src/main.py
wangzhefeng/data-analysis
e502ac49ae1bc8287243e1faf51c467cc4d4187c
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd
7
20
0.632653
8
49
3.875
0.75
0
0
0
0
0
0
0
0
0
0
0
0.367347
49
6
21
8.166667
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
f9fe9fc59ceada91915aa8316b236b87c1bc78e9
96
py
Python
src/huggingmolecules/featurization/__init__.py
chrislybaer/huggingmolecules
210239ac46b467e900a47e8f4520054636744ca6
[ "Apache-2.0" ]
60
2021-05-07T16:07:26.000Z
2022-03-26T19:23:54.000Z
src/huggingmolecules/featurization/__init__.py
gabegomes/huggingmolecules
adc581c97fbc21d9967dd9334afa94b22fb77651
[ "Apache-2.0" ]
11
2021-05-07T16:01:35.000Z
2022-03-09T13:06:05.000Z
src/huggingmolecules/featurization/__init__.py
gabegomes/huggingmolecules
adc581c97fbc21d9967dd9334afa94b22fb77651
[ "Apache-2.0" ]
12
2021-05-20T08:02:25.000Z
2022-03-10T14:11:36.000Z
from .featurization_grover import GroverFeaturizer from .featurization_mat import MatFeaturizer
32
50
0.895833
10
96
8.4
0.7
0.404762
0
0
0
0
0
0
0
0
0
0
0.083333
96
2
51
48
0.954545
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
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
1
0
1
0
1
0
0
6
e607261fe95832a23a77be467f4e6bd16ce68cfd
107
py
Python
src/circulation_import/__main__.py
vbessonov/circulation-import
f9e2a9112133d5bdcee2d937c70f511c8979702b
[ "MIT" ]
null
null
null
src/circulation_import/__main__.py
vbessonov/circulation-import
f9e2a9112133d5bdcee2d937c70f511c8979702b
[ "MIT" ]
null
null
null
src/circulation_import/__main__.py
vbessonov/circulation-import
f9e2a9112133d5bdcee2d937c70f511c8979702b
[ "MIT" ]
null
null
null
from circulation_import.cli import cli if __name__ == "__main__": cli(prog_name="circulation-import")
21.4
39
0.757009
14
107
5.071429
0.571429
0.478873
0
0
0
0
0
0
0
0
0
0
0.130841
107
4
40
26.75
0.763441
0
0
0
0
0
0.242991
0
0
0
0
0
0
1
0
true
0
0.666667
0
0.666667
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
1
0
1
0
1
0
0
6
e62817278662e26624cc5aa0f89d4cb9e4dc87b1
165
py
Python
reprobench/task_sources/doi/base.py
gorczyca/reprobench
915c729eec488ce85ff8c65b8b36851c43b1b345
[ "MIT" ]
1
2019-05-18T12:18:02.000Z
2019-05-18T12:18:02.000Z
reprobench/task_sources/doi/base.py
gorczyca/reprobench
915c729eec488ce85ff8c65b8b36851c43b1b345
[ "MIT" ]
19
2019-03-11T13:35:12.000Z
2019-07-26T06:54:39.000Z
reprobench/task_sources/doi/base.py
gorczyca/reprobench
915c729eec488ce85ff8c65b8b36851c43b1b345
[ "MIT" ]
4
2020-09-28T09:24:38.000Z
2022-03-18T12:55:20.000Z
class BaseDOIHandler(object): @classmethod def is_compatible(cls, doi): return False @classmethod def get_urls(cls, doi): return []
18.333333
32
0.624242
18
165
5.611111
0.722222
0.277228
0.237624
0
0
0
0
0
0
0
0
0
0.284848
165
8
33
20.625
0.855932
0
0
0.285714
0
0
0
0
0
0
0
0
0
1
0.285714
false
0
0
0.285714
0.714286
0
1
0
0
null
1
1
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
1
0
0
0
6