hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
248
max_stars_repo_name
stringlengths
5
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
3
248
max_issues_repo_name
stringlengths
5
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
3
248
max_forks_repo_name
stringlengths
5
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
5
2.06M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.03M
alphanum_fraction
float64
0
1
count_classes
int64
0
1.6M
score_classes
float64
0
1
count_generators
int64
0
651k
score_generators
float64
0
1
count_decorators
int64
0
990k
score_decorators
float64
0
1
count_async_functions
int64
0
235k
score_async_functions
float64
0
1
count_documentation
int64
0
1.04M
score_documentation
float64
0
1
69d1cd005aaaf49ee063eaef4256019e28e73ab2
4,880
py
Python
ml_editor/explanation_generation.py
johanjun/Building_ML_Powered_Applications
bcdcc769f4407ec9fbc729794ba84e8214d29027
[ "MIT" ]
18
2021-09-11T05:04:09.000Z
2022-03-20T23:41:42.000Z
ml_editor/explanation_generation.py
johanjun/Building_ML_Powered_Applications
bcdcc769f4407ec9fbc729794ba84e8214d29027
[ "MIT" ]
null
null
null
ml_editor/explanation_generation.py
johanjun/Building_ML_Powered_Applications
bcdcc769f4407ec9fbc729794ba84e8214d29027
[ "MIT" ]
7
2021-09-30T11:22:12.000Z
2022-03-20T23:49:43.000Z
import os from pathlib import Path import pandas as pd from lime.lime_tabular import LimeTabularExplainer from ml_editor.data_processing import get_split_by_author FEATURE_DISPLAY_NAMES = { "num_questions": "๋ฌผ์Œํ‘œ ๋นˆ๋„", "num_periods": "๋งˆ์นจํ‘œ ๋นˆ๋„", "num_commas": "์‰ผํ‘œ ๋นˆ๋„", "num_exclam": "๋А๋‚Œํ‘œ ๋นˆ๋„", "num_quotes": "๋”ฐ์˜ดํ‘œ ๋นˆ๋„", "num_colon": "์ฝœ๋ก  ๋นˆ๋„", "num_semicolon": "์„ธ๋ฏธ์ฝœ๋ก  ๋นˆ๋„", "num_stops": "๋ถˆ์šฉ์–ด ๋นˆ๋„", "num_words": "๋‹จ์–ด ๊ฐœ์ˆ˜", "num_chars": "๋ฌธ์ž ๊ฐœ์ˆ˜", "num_diff_words": "์–ดํœ˜ ๋‹ค์–‘์„ฑ", "avg_word_len": "ํ‰๊ท  ๋‹จ์–ด ๊ธธ์ด", "polarity": "๊ธ์ •์ ์ธ ๊ฐ์„ฑ", "ADJ": "ํ˜•์šฉ์‚ฌ ๋นˆ๋„", "ADP": "์ „์น˜์‚ฌ ๋นˆ๋„", "ADV": "๋ถ€์‚ฌ ๋นˆ๋„", "AUX": "์กฐ๋™์‚ฌ ๋นˆ๋„", "CONJ": "์ ‘์†์‚ฌ ๋นˆ๋„", "DET": "ํ•œ์ •์‚ฌ ๋นˆ๋„", "INTJ": "๊ฐํƒ„์‚ฌ ๋นˆ๋„", "NOUN": "๋ช…์‚ฌ ๋นˆ๋„", "NUM": "์ˆซ์ž ๋นˆ๋„", "PART": "๋ถˆ๋ณ€ํ™”์‚ฌ ๋นˆ๋„", "PRON": "๋Œ€๋ช…์‚ฌ ๋นˆ๋„", "PROPN": "๊ณ ์œ  ๋ช…์‚ฌ ๋นˆ๋„", "PUNCT": "๊ตฌ๋‘์  ๋นˆ๋„", "SCONJ": "์ข…์† ์ ‘์†์‚ฌ ๋นˆ๋„", "SYM": "๊ธฐํ˜ธ ๋นˆ๋„", "VERB": "๋™์‚ฌ ๋นˆ๋„", "X": "๋‹ค๋ฅธ ๋‹จ์–ด์˜ ๋นˆ๋„", } POS_NAMES = { "ADJ": "adjective", "ADP": "adposition", "ADV": "adverb", "AUX": "auxiliary verb", "CONJ": "coordinating conjunction", "DET": "determiner", "INTJ": "interjection", "NOUN": "noun", "NUM": "numeral", "PART": "particle", "PRON": "pronoun", "PROPN": "proper noun", "PUNCT": "punctuation", "SCONJ": "subordinating conjunction", "SYM": "symbol", "VERB": "verb", "X": "other", } FEATURE_ARR = [ "num_questions", "num_periods", "num_commas", "num_exclam", "num_quotes", "num_colon", "num_stops", "num_semicolon", "num_words", "num_chars", "num_diff_words", "avg_word_len", "polarity", ] FEATURE_ARR.extend(POS_NAMES.keys()) def get_explainer(): """ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด LIME ์„ค๋ช… ๋„๊ตฌ๋ฅผ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. ์ง๋ ฌํ™”ํ•˜์ง€ ์•Š์•„๋„ ๋ ๋งŒํผ ์ถฉ๋ถ„ํžˆ ๋น ๋ฆ…๋‹ˆ๋‹ค. :return: LIME ์„ค๋ช… ๋„๊ตฌ ๊ฐ์ฒด """ curr_path = Path(os.path.dirname(__file__)) data_path = Path("../data/writers_with_features.csv") df = pd.read_csv(curr_path / data_path) train_df, test_df = get_split_by_author(df, test_size=0.2, random_state=40) explainer = LimeTabularExplainer( train_df[FEATURE_ARR].values, feature_names=FEATURE_ARR, class_names=["low", "high"], ) return explainer EXPLAINER = get_explainer() def simplify_order_sign(order_sign): """ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ช…ํ™•ํ•œ ์ถœ๋ ฅ์„ ์œ„ํ•ด ๊ธฐํ˜ธ๋ฅผ ๋‹จ์ˆœํ™”ํ•ฉ๋‹ˆ๋‹ค. :param order_sign: ๋น„๊ต ์—ฐ์‚ฐ์ž ์ž…๋ ฅ :return: ๋‹จ์ˆœํ™”๋œ ์—ฐ์‚ฐ์ž """ if order_sign in ["<=", "<"]: return "<" if order_sign in [">=", ">"]: return ">" return order_sign def get_recommended_modification(simple_order, impact): """ ์—ฐ์‚ฐ์ž์™€ ์˜ํ–ฅ ํƒ€์ž…์— ๋”ฐ๋ผ ์ถ”์ฒœ ๋ฌธ์žฅ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. :param simple_order: ๋‹จ์ˆœํ™”๋œ ์—ฐ์‚ฐ์ž :param impact: ๋ณ€ํ™”๊ฐ€ ๊ธ์ •์ ์ธ์ง€ ๋ถ€์ •์ ์ธ์ง€ ์—ฌ๋ถ€ :return: ์ถ”์ฒœ ๋ฌธ์ž์—ด """ bigger_than_threshold = simple_order == ">" has_positive_impact = impact > 0 if bigger_than_threshold and has_positive_impact: return "๋†’์ผ ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค" if not bigger_than_threshold and not has_positive_impact: return "๋†’์ด์„ธ์š”" if bigger_than_threshold and not has_positive_impact: return "๋‚ฎ์ถ”์„ธ์š”" if not bigger_than_threshold and has_positive_impact: return "๋‚ฎ์ถœ ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค" def parse_explanations(exp_list): """ LIME์ด ๋ฐ˜ํ™˜ํ•œ ์„ค๋ช…์„ ์‚ฌ์šฉ์ž๊ฐ€ ์ฝ์„ ์ˆ˜ ์žˆ๋„๋ก ํŒŒ์‹ฑํ•ฉ๋‹ˆ๋‹ค. :param exp_list: LIME ์„ค๋ช… ๋„๊ตฌ๊ฐ€ ๋ฐ˜ํ™˜ํ•œ ์„ค๋ช… :return: ์‚ฌ์šฉ์ž์—๊ฒŒ ์ „๋‹ฌํ•œ ๋ฌธ์ž์—ด์„ ๋‹ด์€ ๋”•์…”๋„ˆ๋ฆฌ ๋ฐฐ์—ด """ parsed_exps = [] for feat_bound, impact in exp_list: conditions = feat_bound.split(" ") # ์ถ”์ฒœ์œผ๋กœ ํ‘œํ˜„ํ•˜๊ธฐ ํž˜๋“ค๊ธฐ ๋•Œ๋ฌธ์— # 1 <= a < 3 ์™€ ๊ฐ™์€ ์ด์ค‘ ๊ฒฝ๊ณ„ ์กฐ๊ฑด์€ ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค if len(conditions) == 3: feat_name, order, threshold = conditions simple_order = simplify_order_sign(order) recommended_mod = get_recommended_modification(simple_order, impact) parsed_exps.append( { "feature": feat_name, "feature_display_name": FEATURE_DISPLAY_NAMES[feat_name], "order": simple_order, "threshold": threshold, "impact": impact, "recommendation": recommended_mod, } ) return parsed_exps def get_recommendation_string_from_parsed_exps(exp_list): """ ํ”Œ๋ž˜์Šคํฌ ์•ฑ์—์„œ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋Š” ์ถ”์ฒœ ํ…์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. :param exp_list: ์„ค๋ช…์„ ๋‹ด์€ ๋”•์…”๋„ˆ๋ฆฌ์˜ ๋ฐฐ์—ด :return: HTML ์ถ”์ฒœ ํ…์ŠคํŠธ """ recommendations = [] for i, feature_exp in enumerate(exp_list): recommendation = "%s %s" % ( feature_exp["recommendation"], feature_exp["feature_display_name"], ) font_color = "green" if feature_exp["recommendation"] in ["Increase", "Decrease"]: font_color = "red" rec_str = """<font color="%s">%s) %s</font>""" % ( font_color, i + 1, recommendation, ) recommendations.append(rec_str) rec_string = "<br/>".join(recommendations) return rec_string
26.096257
80
0.582172
0
0
0
0
0
0
0
0
2,763
0.482199
69d1dab7f54ca1ad815eec0feddd2d80d74004a4
912
py
Python
straitlets/tests/test_test_utils.py
quantopian/serializable-traitlets
f7de75507978e08446a15894a8417997940ea7a6
[ "Apache-2.0" ]
13
2016-01-27T01:55:18.000Z
2022-02-10T12:09:46.000Z
straitlets/tests/test_test_utils.py
quantopian/serializable-traitlets
f7de75507978e08446a15894a8417997940ea7a6
[ "Apache-2.0" ]
5
2016-02-17T13:52:50.000Z
2018-12-13T21:30:26.000Z
straitlets/tests/test_test_utils.py
quantopian/serializable-traitlets
f7de75507978e08446a15894a8417997940ea7a6
[ "Apache-2.0" ]
10
2017-07-21T14:27:17.000Z
2022-03-16T11:19:47.000Z
""" Tests for the test utils. """ import pytest from straitlets import Serializable, Integer from straitlets.test_utils import assert_serializables_equal def test_assert_serializables_equal(): class Foo(Serializable): x = Integer() y = Integer() class Bar(Serializable): x = Integer() y = Integer() assert_serializables_equal(Foo(x=1, y=1), Foo(x=1, y=1)) with pytest.raises(AssertionError): assert_serializables_equal(Foo(x=1, y=1), Bar(x=1, y=1)) with pytest.raises(AssertionError): assert_serializables_equal(Foo(x=1, y=1), Foo(x=1, y=2)) with pytest.raises(AssertionError): assert_serializables_equal( Foo(x=1, y=1), Foo(x=1, y=2), skip=('x',), ) assert_serializables_equal(Foo(x=1), Foo(x=1), skip=('y',)) assert_serializables_equal(Foo(y=1), Foo(y=1), skip=('x',))
25.333333
64
0.625
136
0.149123
0
0
0
0
0
0
42
0.046053
69d291496a5d3377d9958e730dccf8026bc852c8
6,458
py
Python
projects/microphysics/docs/wandb_report_figures/non_limited_num_nonzero.py
ai2cm/fv3net
e62038aee0a97d6207e66baabd8938467838cf51
[ "MIT" ]
1
2021-12-14T23:43:35.000Z
2021-12-14T23:43:35.000Z
projects/microphysics/docs/wandb_report_figures/non_limited_num_nonzero.py
ai2cm/fv3net
e62038aee0a97d6207e66baabd8938467838cf51
[ "MIT" ]
195
2021-09-16T05:47:18.000Z
2022-03-31T22:03:15.000Z
projects/microphysics/docs/wandb_report_figures/non_limited_num_nonzero.py
ai2cm/fv3net
e62038aee0a97d6207e66baabd8938467838cf51
[ "MIT" ]
null
null
null
""" In the last report, "bias_categories.py" I showed that offline bias of the limited RNN cannot be improved by thresholding large relative decreases of cloud to 0. Doing so increased the bias. What about the non-limited RNNS? It turns out that these RNNs have approximately 10x smaller bias. However, they produce negative clouds very quickly, which is not good. Perhaps we can limit negative clouds online by using a post-hoc classifier. Even though it is posthoc, the bias may be smaller than an RNN with a limiter applied during training. """ # %% import xarray as xr import numpy as np from fv3fit.emulation.data.load import nc_dir_to_tfdataset from fv3fit.train_microphysics import TransformConfig import tensorflow as tf import matplotlib.pyplot as plt from matplotlib.ticker import Locator from sklearn.metrics import roc_curve, roc_auc_score, RocCurveDisplay class MinorSymLogLocator(Locator): """ Dynamically find minor tick positions based on the positions of major ticks for a symlog scaling. from https://stackoverflow.com/a/45696768 """ def __init__(self, linthresh): """ Ticks will be placed between the major ticks. The placement is linear for x between -linthresh and linthresh, otherwise its logarithmically """ self.linthresh = linthresh def __call__(self): "Return the locations of the ticks" majorlocs = self.axis.get_majorticklocs() # iterate through minor locs minorlocs = [] # handle the lowest part for i in range(1, len(majorlocs)): majorstep = majorlocs[i] - majorlocs[i - 1] if abs(majorlocs[i - 1] + majorstep / 2) < self.linthresh: ndivs = 10 else: ndivs = 9 minorstep = majorstep / ndivs locs = np.arange(majorlocs[i - 1], majorlocs[i], minorstep)[1:] minorlocs.extend(locs) return self.raise_if_exceeds(np.array(minorlocs)) def tick_values(self, vmin, vmax): raise NotImplementedError( "Cannot get tick locations for a " "%s type." % type(self) ) def tensordict_to_dataset(x): """convert a tensor dict into a xarray dataset and flip the vertical coordinate""" def _get_dims(val): n, feat = val.shape if feat == 1: return (["sample"], val[:, 0].numpy()) else: return (["sample", "z"], val[:, ::-1].numpy()) return xr.Dataset({key: _get_dims(val) for key, val in x.items()}) def open_data(url: str) -> tf.data.Dataset: variables = [ "latitude", "longitude", "pressure_thickness_of_atmospheric_layer", "air_pressure", "surface_air_pressure", "air_temperature_input", "specific_humidity_input", "cloud_water_mixing_ratio_input", "air_temperature_after_last_gscond", "specific_humidity_after_last_gscond", "surface_air_pressure_after_last_gscond", "specific_humidity_after_gscond", "air_temperature_after_gscond", "air_temperature_after_precpd", "specific_humidity_after_precpd", "cloud_water_mixing_ratio_after_precpd", "total_precipitation", "ratio_of_snowfall_to_rainfall", "tendency_of_rain_water_mixing_ratio_due_to_microphysics", "time", ] data_transform = TransformConfig( antarctic_only=False, use_tensors=True, vertical_subselections=None, derived_microphys_timestep=900, ) # TODO change default of get_pipeline to get all the variables # will allow deleting the code above return nc_dir_to_tfdataset(url, data_transform.get_pipeline(variables)) test_url = "/Users/noahb/data/vcm-ml-experiments/microphysics-emulation/2021-11-24/microphysics-training-data-v3-training_netcdfs/test" # noqa model_path = "gs://vcm-ml-experiments/microphysics-emulation/2022-03-02/limit-tests-all-loss-rnn-7ef273/model.tf" # noqa model = tf.keras.models.load_model(model_path) tfds = open_data(test_url) truth_pred = tfds.map(lambda x: (x, model(x))) truth_dict, pred_dict = next(iter(truth_pred.unbatch().batch(50_000))) truth = tensordict_to_dataset(truth_dict) pred = tensordict_to_dataset(pred_dict) # %% truth_tend = ( truth.cloud_water_mixing_ratio_after_precpd - truth.cloud_water_mixing_ratio_input ) pred_tend = ( pred.cloud_water_mixing_ratio_after_precpd - truth.cloud_water_mixing_ratio_input ) x = truth.cloud_water_mixing_ratio_input x_0 = np.abs(x) <= 1e-20 y = pred.cloud_water_mixing_ratio_after_precpd y_true = truth.cloud_water_mixing_ratio_after_precpd # %% # ROC of cloud after precpd = 0 y = np.ravel(pred.cloud_water_mixing_ratio_after_precpd) y_true = np.ravel(truth.cloud_water_mixing_ratio_after_precpd) class_true = y_true >= 1e-20 fpr, tpr, t = roc_curve(class_true, y) fig, (ax, ax_tresh) = plt.subplots(2, 1, figsize=(6, 8), sharex=True) (p,) = ax.plot(fpr, tpr, label="true positive rate") ax.tick_params(axis="y", colors=p.get_color()) ax.yaxis.label.set_color(p.get_color()) ax.set_xlabel("false positive rate") ax.set_ylabel("true positive rate") ax.set_title( "ROC Analysis (cloud after precpd >= 0): AUC={:.2f}".format( roc_auc_score(class_true, y) ) ) ax.set_xscale("log") fpr_regular = np.logspace(-7, 0, 100) thresholds = np.interp(fpr_regular, fpr, t) bias = [np.mean(np.where(y > thresh, y, 0) - y_true) / 900 for thresh in thresholds] ax1 = ax.twinx() (p2,) = ax1.plot(fpr_regular, bias, label="bias", color="red") ax1.tick_params(axis="y", colors=p2.get_color()) ax1.yaxis.label.set_color(p2.get_color()) ax1.set_ylabel("bias (kg/kg/s)") ax.grid() ax1.set_yscale("symlog", linthreshy=1e-11) ax1.set_xscale("log") ax1.yaxis.set_minor_locator(MinorSymLogLocator(linthresh=1e-11)) ax_tresh.loglog(fpr_regular[:-1], thresholds[:-1], "-") ax_tresh.set_xlabel("false positive rate") ax_tresh.set_ylabel("threshold (kg/kg)") ax_tresh.grid() # %% ROC cloud in = glcoud gscond out y_true = -np.ravel(truth.specific_humidity_after_gscond - truth.specific_humidity_input) y = -np.ravel(pred.specific_humidity_after_gscond - truth.specific_humidity_input) fpr, tpr, t = roc_curve(np.abs(y_true) >= 1e-20, np.abs(y)) auc = roc_auc_score(np.abs(y_true) >= 1e-20, np.abs(y)) ax = plt.subplot() RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=auc).plot(ax=ax) ax.set_title("ROC (cloud after gscond = cloud in)")
34.351064
143
0.702694
1,286
0.199133
0
0
0
0
0
0
2,352
0.364199
69d2955809d68e17f8be812fa27e25216fd7813e
4,026
py
Python
fdm/analysis/tools.py
szajek/FDM
6270b0eb2bf3ef80f2ed87d0f39cf39ab82ae02b
[ "MIT" ]
1
2017-11-12T09:57:52.000Z
2017-11-12T09:57:52.000Z
fdm/analysis/tools.py
szajek/FDM
6270b0eb2bf3ef80f2ed87d0f39cf39ab82ae02b
[ "MIT" ]
null
null
null
fdm/analysis/tools.py
szajek/FDM
6270b0eb2bf3ef80f2ed87d0f39cf39ab82ae02b
[ "MIT" ]
null
null
null
import numpy from fdm.geometry import create_close_point_finder def create_weights_distributor(close_point_finder): def distribute(point, value): close_points = close_point_finder(point) distance_sum = sum(close_points.values()) return dict( {p: (1. - distance/distance_sum)*value for p, distance in close_points.items()}, ) return distribute def apply_statics_bc(variables, matrix, vector, bcs): extra_bcs = extract_extra_bcs(bcs) replace_bcs = extract_replace_bcs(bcs) extra_bcs_number = len(extra_bcs) _matrix = numpy.copy(matrix) _vector = numpy.copy(vector) assert (_rows_number(_matrix) == len(variables), 'Number of BCs must be equal "vars_number" - "real_nodes_number"') points = list(variables) matrix_bc_applicator = create_matrix_bc_applicator(_matrix, points, variables) vector_bc_applicator = create_vector_bc_applicator(_vector) for i, (scheme, value, replace) in enumerate(replace_bcs): matrix_bc_applicator(variables[replace], scheme) vector_bc_applicator(variables[replace], value) initial_idx = _rows_number(matrix) - extra_bcs_number for i, (scheme, value, _) in enumerate(extra_bcs): matrix_bc_applicator(initial_idx + i, scheme) vector_bc_applicator(initial_idx + i, value) return _matrix, _vector def apply_dynamics_bc(variables, matrix_a, matrix_b, bcs): extra_bcs = extract_extra_bcs(bcs) replace_bcs = extract_replace_bcs(bcs) extra_bcs_number = len(extra_bcs) _matrix_a = numpy.copy(matrix_a) _matrix_b = numpy.copy(matrix_b) assert _rows_number(_matrix_a) == len(variables), 'Number of BCs must be equal "vars_number" - "real_nodes_number"' points = list(variables) matrix_a_bc_applicator = create_matrix_bc_applicator(_matrix_a, points, variables) matrix_b_bc_applicator = create_matrix_bc_applicator(_matrix_b, points, variables) for i, (scheme_a, scheme_b, replace) in enumerate(replace_bcs): matrix_a_bc_applicator(variables[replace], scheme_a) matrix_b_bc_applicator(variables[replace], scheme_b) initial_idx = _rows_number(_matrix_a) - extra_bcs_number for i, (scheme_a, scheme_b, _) in enumerate(extra_bcs): matrix_a_bc_applicator(initial_idx + i, scheme_a) matrix_b_bc_applicator(initial_idx + i, scheme_b) return _matrix_a, _matrix_b def extract_extra_bcs(bcs): return [bc for bc in bcs if bc.replace is None] def extract_replace_bcs(bcs): return [bc for bc in bcs if bc.replace is not None] def create_matrix_bc_applicator(matrix, points, variables, tol=1e-6): def apply(row_idx, scheme): matrix[row_idx, :] = 0. if len(scheme): distributor = SchemeToNodesDistributor(points) scheme = distributor(scheme) scheme = scheme.drop(tol) for p, weight in scheme.items(): col_idx = variables[p] matrix[row_idx, col_idx] = weight return apply def create_vector_bc_applicator(vector): def apply(row_idx, value): vector[row_idx] = value return apply def _zero_vector_last_rows(vector, number): _vector = numpy.zeros(vector.shape) _vector[:-number] = vector[:-number] return _vector def _zero_matrix_last_rows(matrix, number): _matrix = numpy.zeros(matrix.shape) _matrix[:-number, :] = matrix[:-number, :] return _matrix def _rows_number(matrix): return matrix.shape[0] def _cols_number(matrix): return matrix.shape[1] class SchemeToNodesDistributor(object): def __init__(self, nodes): self._distributor = WeightsDistributor(nodes) def __call__(self, scheme): return scheme.distribute(self._distributor) class WeightsDistributor(object): def __init__(self, nodes): self._distributor = create_weights_distributor( create_close_point_finder(nodes) ) def __call__(self, point, weight): return self._distributor(point, weight)
30.5
119
0.709389
472
0.117238
0
0
0
0
0
0
130
0.03229
69d2cf747c7a7036f97b7f91f7789d9373964e1b
1,300
py
Python
src/tests/sounds_test.py
dvsantoalla/atmospheres
f31bb636170dd8711e398b321a6416025bbd4de8
[ "Apache-2.0" ]
null
null
null
src/tests/sounds_test.py
dvsantoalla/atmospheres
f31bb636170dd8711e398b321a6416025bbd4de8
[ "Apache-2.0" ]
null
null
null
src/tests/sounds_test.py
dvsantoalla/atmospheres
f31bb636170dd8711e398b321a6416025bbd4de8
[ "Apache-2.0" ]
null
null
null
import unittest from csound import output, orchestra from csound.orchestra import gen08 from data import constants as c from data import get class TestSounds(unittest.TestCase): def test_simple_soundwaves(self): # Get all data place = "Madrid" mad2t = get(c.T, location=place) madp = get(c.P, location=place) madw = get(c.W, location=place) madc = get(c.C, location=place) # write orchestra + score duration = 30 points = 16777216 oscillator = orchestra.oscillator1(points) score = ["f1 0 8192 10 1 ; Table containing a sine wave.", gen08(2, mad2t, number_of_points=points, comment="Weather parameter table 2"), gen08(3, madp, number_of_points=points, comment="Weather parameter table 3", ), gen08(4, madw, number_of_points=points, comment="Weather parameter table 4"), gen08(5, madc, number_of_points=points, comment="Weather parameter table 5"), "i1 0 %s 10000 2 ; " % duration, "i1 0 %s 5000 3 ; " % duration, "i1 0 %s 5000 4 ; " % duration, "i1 0 %s 5000 5 ; " % duration ] output.write_and_play(output.get_csd([oscillator], score))
34.210526
96
0.590769
1,155
0.888462
0
0
0
0
0
0
281
0.216154
69d3674b80e0407aa5556ee4e06d257e26cbc733
1,058
py
Python
dht22.py
trihatmaja/dht22-raspi
7bce4b1c35d9eed9e4913caa6f3b9b3aed5c3219
[ "MIT" ]
null
null
null
dht22.py
trihatmaja/dht22-raspi
7bce4b1c35d9eed9e4913caa6f3b9b3aed5c3219
[ "MIT" ]
null
null
null
dht22.py
trihatmaja/dht22-raspi
7bce4b1c35d9eed9e4913caa6f3b9b3aed5c3219
[ "MIT" ]
null
null
null
import Adafruit_DHT as dht import time from influxdb import InfluxDBClient def get_serial(): cpu_serial = "0000000000000000" try: f = open('/proc/cpuinfo', 'r') for line in f: if line[0:6] == 'Serial': cpu_serial = line[10:26] f.close() except: cpu_serial = "ERROR000000000" return cpu_serial def write_db(tmp, hum, device_id): json_body = [ { "measurement": "temperature", "tags": { "device_id": str(device_id), }, "fields": { "celcius": str('{0:0.2f}'.format(tmp)), "humidity": str('{0:0.2f}'.format(hum)), } } ] client = InfluxDBClient('localhost', 8086, "", "", "raspi_temp") client.write_points(json_body) def main(): device_id = get_serial() while True: h,t = dht.read_retry(dht.DHT22, 4) write_db(t, h, device_id) print ('Temp={0:0.2f}*C Humidity={1:0.2f}%'.format(t, h)) time.sleep(5) if __name__ == '__main__': main()
23.511111
66
0.535917
0
0
0
0
0
0
0
0
224
0.21172
69d3ae6f2c3de09735086e056c7ecbd05c224a46
9,319
py
Python
quapy/data/base.py
pglez82/QuaPy
986e61620c7882e97245bd82d323e7615699d7b1
[ "BSD-3-Clause" ]
34
2021-01-06T14:01:06.000Z
2022-03-08T06:59:04.000Z
quapy/data/base.py
pglez82/QuaPy
986e61620c7882e97245bd82d323e7615699d7b1
[ "BSD-3-Clause" ]
4
2021-06-07T07:45:57.000Z
2021-06-21T11:16:10.000Z
quapy/data/base.py
pglez82/QuaPy
986e61620c7882e97245bd82d323e7615699d7b1
[ "BSD-3-Clause" ]
6
2021-06-07T10:08:17.000Z
2022-03-07T13:42:15.000Z
import numpy as np from scipy.sparse import issparse from scipy.sparse import vstack from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold from quapy.functional import artificial_prevalence_sampling, strprev class LabelledCollection: ''' A LabelledCollection is a set of objects each with a label associated to it. ''' def __init__(self, instances, labels, classes_=None): """ :param instances: list of objects :param labels: list of labels, same length of instances :param classes_: optional, list of classes from which labels are taken. When used, must contain the set of values used in labels. """ if issparse(instances): self.instances = instances elif isinstance(instances, list) and len(instances) > 0 and isinstance(instances[0], str): # lists of strings occupy too much as ndarrays (although python-objects add a heavy overload) self.instances = np.asarray(instances, dtype=object) else: self.instances = np.asarray(instances) self.labels = np.asarray(labels) n_docs = len(self) if classes_ is None: self.classes_ = np.unique(self.labels) self.classes_.sort() else: self.classes_ = np.unique(np.asarray(classes_)) self.classes_.sort() if len(set(self.labels).difference(set(classes_))) > 0: raise ValueError('labels contains values not included in classes_') self.index = {class_: np.arange(n_docs)[self.labels == class_] for class_ in self.classes_} @classmethod def load(cls, path: str, loader_func: callable): return LabelledCollection(*loader_func(path)) def __len__(self): return self.instances.shape[0] def prevalence(self): return self.counts() / len(self) def counts(self): return np.asarray([len(self.index[class_]) for class_ in self.classes_]) @property def n_classes(self): return len(self.classes_) @property def binary(self): return self.n_classes == 2 def sampling_index(self, size, *prevs, shuffle=True): if len(prevs) == 0: # no prevalence was indicated; returns an index for uniform sampling return np.random.choice(len(self), size, replace=False) if len(prevs) == self.n_classes - 1: prevs = prevs + (1 - sum(prevs),) assert len(prevs) == self.n_classes, 'unexpected number of prevalences' assert sum(prevs) == 1, f'prevalences ({prevs}) wrong range (sum={sum(prevs)})' taken = 0 indexes_sample = [] for i, class_ in enumerate(self.classes_): if i == self.n_classes - 1: n_requested = size - taken else: n_requested = int(size * prevs[i]) n_candidates = len(self.index[class_]) index_sample = self.index[class_][ np.random.choice(n_candidates, size=n_requested, replace=(n_requested > n_candidates)) ] if n_requested > 0 else [] indexes_sample.append(index_sample) taken += n_requested indexes_sample = np.concatenate(indexes_sample).astype(int) if shuffle: indexes_sample = np.random.permutation(indexes_sample) return indexes_sample def uniform_sampling_index(self, size): return np.random.choice(len(self), size, replace=False) def uniform_sampling(self, size): unif_index = self.uniform_sampling_index(size) return self.sampling_from_index(unif_index) def sampling(self, size, *prevs, shuffle=True): prev_index = self.sampling_index(size, *prevs, shuffle=shuffle) return self.sampling_from_index(prev_index) def sampling_from_index(self, index): documents = self.instances[index] labels = self.labels[index] return LabelledCollection(documents, labels, classes_=self.classes_) def split_stratified(self, train_prop=0.6, random_state=None): # with temp_seed(42): tr_docs, te_docs, tr_labels, te_labels = \ train_test_split(self.instances, self.labels, train_size=train_prop, stratify=self.labels, random_state=random_state) return LabelledCollection(tr_docs, tr_labels), LabelledCollection(te_docs, te_labels) def artificial_sampling_generator(self, sample_size, n_prevalences=101, repeats=1): dimensions = self.n_classes for prevs in artificial_prevalence_sampling(dimensions, n_prevalences, repeats): yield self.sampling(sample_size, *prevs) def artificial_sampling_index_generator(self, sample_size, n_prevalences=101, repeats=1): dimensions = self.n_classes for prevs in artificial_prevalence_sampling(dimensions, n_prevalences, repeats): yield self.sampling_index(sample_size, *prevs) def natural_sampling_generator(self, sample_size, repeats=100): for _ in range(repeats): yield self.uniform_sampling(sample_size) def natural_sampling_index_generator(self, sample_size, repeats=100): for _ in range(repeats): yield self.uniform_sampling_index(sample_size) def __add__(self, other): if other is None: return self elif issparse(self.instances) and issparse(other.instances): join_instances = vstack([self.instances, other.instances]) elif isinstance(self.instances, list) and isinstance(other.instances, list): join_instances = self.instances + other.instances elif isinstance(self.instances, np.ndarray) and isinstance(other.instances, np.ndarray): join_instances = np.concatenate([self.instances, other.instances]) else: raise NotImplementedError('unsupported operation for collection types') labels = np.concatenate([self.labels, other.labels]) return LabelledCollection(join_instances, labels) @property def Xy(self): return self.instances, self.labels def stats(self, show=True): ninstances = len(self) instance_type = type(self.instances[0]) if instance_type == list: nfeats = len(self.instances[0]) elif instance_type == np.ndarray or issparse(self.instances): nfeats = self.instances.shape[1] else: nfeats = '?' stats_ = {'instances': ninstances, 'type': instance_type, 'features': nfeats, 'classes': self.classes_, 'prevs': strprev(self.prevalence())} if show: print(f'#instances={stats_["instances"]}, type={stats_["type"]}, #features={stats_["features"]}, ' f'#classes={stats_["classes"]}, prevs={stats_["prevs"]}') return stats_ def kFCV(self, nfolds=5, nrepeats=1, random_state=0): kf = RepeatedStratifiedKFold(n_splits=nfolds, n_repeats=nrepeats, random_state=random_state) for train_index, test_index in kf.split(*self.Xy): train = self.sampling_from_index(train_index) test = self.sampling_from_index(test_index) yield train, test class Dataset: def __init__(self, training: LabelledCollection, test: LabelledCollection, vocabulary: dict = None, name=''): assert set(training.classes_) == set(test.classes_), 'incompatible labels in training and test collections' self.training = training self.test = test self.vocabulary = vocabulary self.name = name @classmethod def SplitStratified(cls, collection: LabelledCollection, train_size=0.6): return Dataset(*collection.split_stratified(train_prop=train_size)) @property def classes_(self): return self.training.classes_ @property def n_classes(self): return self.training.n_classes @property def binary(self): return self.training.binary @classmethod def load(cls, train_path, test_path, loader_func: callable): training = LabelledCollection.load(train_path, loader_func) test = LabelledCollection.load(test_path, loader_func) return Dataset(training, test) @property def vocabulary_size(self): return len(self.vocabulary) def stats(self): tr_stats = self.training.stats(show=False) te_stats = self.test.stats(show=False) print(f'Dataset={self.name} #tr-instances={tr_stats["instances"]}, #te-instances={te_stats["instances"]}, ' f'type={tr_stats["type"]}, #features={tr_stats["features"]}, #classes={tr_stats["classes"]}, ' f'tr-prevs={tr_stats["prevs"]}, te-prevs={te_stats["prevs"]}') return {'train': tr_stats, 'test': te_stats} @classmethod def kFCV(cls, data: LabelledCollection, nfolds=5, nrepeats=1, random_state=0): for i, (train, test) in enumerate(data.kFCV(nfolds=nfolds, nrepeats=nrepeats, random_state=random_state)): yield Dataset(train, test, name=f'fold {(i % nfolds) + 1}/{nfolds} (round={(i // nfolds) + 1})') def isbinary(data): if isinstance(data, Dataset) or isinstance(data, LabelledCollection): return data.binary return False
40.517391
137
0.653504
8,940
0.95933
1,503
0.161283
1,342
0.144007
0
0
1,297
0.139178
69d7a315854c9efb1fc746e30bff79237346d088
381
py
Python
corehq/apps/fixtures/exceptions.py
SEL-Columbia/commcare-hq
992ee34a679c37f063f86200e6df5a197d5e3ff6
[ "BSD-3-Clause" ]
1
2015-02-10T23:26:39.000Z
2015-02-10T23:26:39.000Z
corehq/apps/fixtures/exceptions.py
SEL-Columbia/commcare-hq
992ee34a679c37f063f86200e6df5a197d5e3ff6
[ "BSD-3-Clause" ]
null
null
null
corehq/apps/fixtures/exceptions.py
SEL-Columbia/commcare-hq
992ee34a679c37f063f86200e6df5a197d5e3ff6
[ "BSD-3-Clause" ]
null
null
null
class FixtureException(Exception): pass class FixtureUploadError(FixtureException): pass class DuplicateFixtureTagException(FixtureUploadError): pass class ExcelMalformatException(FixtureUploadError): pass class FixtureAPIException(Exception): pass class FixtureTypeCheckError(Exception): pass class FixtureVersionError(Exception): pass
12.290323
55
0.774278
358
0.939633
0
0
0
0
0
0
0
0
69dcbd043965a22c5729ce122aacb8d9478b59fe
55,763
py
Python
feature_extractors.py
Askinkaty/text-readability
4d9d7c6cd3a07c7443ca24c67db981b4b4c9fff4
[ "MIT" ]
null
null
null
feature_extractors.py
Askinkaty/text-readability
4d9d7c6cd3a07c7443ca24c67db981b4b4c9fff4
[ "MIT" ]
null
null
null
feature_extractors.py
Askinkaty/text-readability
4d9d7c6cd3a07c7443ca24c67db981b4b4c9fff4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from process_gram import process_grammar import codecs first_pp = ['ะผั‹', 'ั', 'ะฝะฐัˆ', 'ะผะพะน'] second_pp = ['ั‚ั‹', 'ะฒั‹', 'ะฒะฐัˆ', 'ั‚ะฒะพะน'] third_pp = ['ะพะฝ', 'ะพะฝะฐ', 'ะพะฝะธ', 'ะพะฝะพ', 'ะธั…', 'ee', 'ะตะณะพ', 'ะธั…ะฝะธะน', 'ะธั…ะฝะธะผ', 'ะธั…ะฝะตะผ'] indef_pron = ['ะฝะตะบั‚ะพ', 'ะฝะตะบะพะณะพ', 'ะฝะตะบะพะผัƒ', 'ะฝะตะบะตะผ', 'ะฝะตั‡ั‚ะพ', 'ะฝะตั‡ะตะณะพ', 'ะฝะตั‡ะตะผัƒ', 'ะฝะตั‡ะตะผ', 'ะฝะตะบะพั‚ะพั€ั‹ะน', 'ะฝะตะบะธะน', 'ะปัŽะฑะพะน', 'ะฝะธะบั‚ะพ', 'ะฝะธั‡ั‚ะพ', 'ะฝะธะบะฐะบะพะน', 'ะฝะธัะบะพะปัŒะบะพ', 'ะฝะธะณะดะต', 'ะฝะตะณะดะต', 'ะฝะตะบัƒะดะฐ', 'ะฝะธะบัƒะดะฐ', 'ะฝะตะพั‚ะบัƒะดะฐ', 'ะฝะธะพั‚ะบัƒะดะฐ', 'ะฝะตะบะพะณะดะฐ', 'ะฝะธะบะพะณะดะฐ', 'ะฝะธะบะฐะบ', 'ะฝะตะทะฐั‡ะตะผ', 'ะฝะตะทะฐั‡ะตะผ'] place_adverbs = ['ะฑะปะธะทะบะพ', 'ะฑะปะธะถะต', 'ะฒะฑะปะธะทะธ', 'ะฒะฒะตั€ั…', 'ะฒะฒะตั€ั…ัƒ', 'ะฒะฒั‹ััŒ', 'ะฒะณะปัƒะฑัŒ', 'ะฒะดะฐะปะธ', 'ะฒะดะฐะปัŒ', 'ะฒะตะทะดะต', 'ะฒะทะฐะด', 'ะฒะปะตะฒะพ', 'ะฒะฝะต', 'ะฒะฝะธะท', 'ะฒะฝะธะทัƒ', 'ะฒะฝัƒั‚ั€ะธ', 'ะฒะฝัƒั‚ั€ัŒ', 'ะฒะพะฒะฝะต', 'ะฒะพะฒะฝัƒั‚ั€ัŒ', 'ะฒะพะบั€ัƒะณ', 'ะฒะฟะตั€ะตะด', 'ะฒะฟะตั€ะตะดะธ', 'ะฒะฟั€ะฐะฒะพ', 'ะฒััŽะดัƒ', 'ะฒั‹ัะพะบะพ', 'ะฒั‹ัˆะต', 'ะณะปัƒะฑะพะบะพ', 'ะณะปัƒะฑะถะต', 'ะดะฐะปะตะบะพ', 'ะดะฐะปัŒัˆะต', 'ะดะพะฝะธะทัƒ', 'ะดะพะผะฐ', 'ะทะดะตััŒ', 'ะธะทะดะฐะปะตะบะฐ', 'ะธะทะดะฐะปะตั‡ะต', 'ะธะทะดะฐะปะธ', 'ะธะทะฝัƒั‚ั€ะธ', 'ะบะฒะตั€ั…ัƒ', 'ะบะฝะธะทัƒ', 'ะบั€ัƒะณะพะผ', 'ะปะตะฒะตะต', 'ะฝะฐะฒะตั€ั…', 'ะฝะฐะฒะตั€ั…ัƒ', 'ะฝะฐะธัะบะพัะพะบ', 'ะฝะฐะปะตะฒะพ', 'ะฝะฐะฟั€ะฐะฒะพ', 'ะฝะฐะฟั€ะพั‚ะธะฒ', 'ะฝะฐั€ัƒะถะฝะพ', 'ะฝะฐั€ัƒะถัƒ', 'ะฝะตะฒั‹ัะพะบะพ', 'ะฝะตะณะปัƒะฑะพะบะพ', 'ะฝะตะดะฐะปะตะบะพ', 'ะฝะตะฟะพะดะฐะปะตะบัƒ', 'ะฝะธะทะบะพ', 'ะฝะธะถะต', 'ะพะดะฐะปัŒ', 'ะพะบะพะปะพ', 'ะพะบั€ะตัั‚', 'ะพัะพะฑะฝัะบะพะผ', 'ะพั‚ะดะตะปัŒะฝะพ', 'ะพั‚ะบัƒะดะฐ', 'ะพั‚ััŽะดะฐ', 'ะฟะพะฑะปะธะถะต', 'ะฟะพะฒะตั€ั…', 'ะฟะพะฒัะตะผะตัั‚ะฝะพ', 'ะฟะพะฒััŽะดัƒ', 'ะฟะพะฒั‹ัˆะต', 'ะฟะพะณะปัƒะฑะถะต', 'ะฟะพะดะฐะปัŒัˆะต', 'ะฟะพะทะฐะดะธ', 'ะฟะพะฝะธะถะต', 'ะฟะพะฝะธะทัƒ', 'ะฟะพัะตั€ะตะดะบะต', 'ะฟะพัะตั€ะตะดะธะฝะต', 'ะฟะพัั€ะตะดะธ', 'ะฟะพัั€ะตะดะธะฝะต', 'ะฟะพะพะดะฐะปัŒ', 'ะฟั€ะฐะฒะตะต', 'ั€ัะดะพะผ', 'ัะฑะพะบัƒ', 'ัะฒะตั€ั…ัƒ', 'ัะฒั‹ัˆะต', 'ัะทะฐะดะธ', 'ัะปะตะฒะฐ', 'ัะฝะธะทัƒ', 'ัะฝะฐั€ัƒะถะธ', 'ัะฟะตั€ะตะดะธ', 'ัะฟั€ะฐะฒะฐ', 'ัั‚ะพั€ะพะฝะพะน', 'ััƒะฟั€ะพั‚ะธะฒ'] time_adverbs = ['ะฑะตัะบะพะฝะตั‡ะฝะพ', 'ะฑะตัะฟั€ะตั€ั‹ะฒะฝะพ', 'ะฒะฒะตะบ', 'ะฒะตัะฝะพะน', 'ะฒะตั‡ะฝะพ', 'ะฒะผะธะณ', 'ะฒะฝะฐั‡ะฐะปะต', 'ะฒะพะฒะตะบ', 'ะฒะพะฒั€ะตะผั', 'ะฒะฟะพั€ัƒ', 'ะฒะฟะพัะปะตะดัั‚ะฒะธะธ', 'ะฒะฟั€ะตะดัŒ', 'ะฒั€ะฐะท', 'ะฒั€ะตะผะตะฝะฝะพ', 'ะฒัะตั‡ะฐัะฝะพ', 'ะฒัะบะพั€ะต', 'ะฒัั‚ะฐั€ัŒ', 'ะฒั‡ะตั€ะฐ', 'ะฒั‡ะตั€ะฐััŒ', 'ะดะฐะฒะตั‡ะฐ', 'ะดะฐะฒะฝะพ', 'ะดะฐะฒะฝะตะฝัŒะบะพ', 'ะดะตะฝะฝะพ', 'ะดะปะธั‚ะตะปัŒะฝะพ', 'ะดะฝะตััŒ', 'ะดะพะบะพะปะต', 'ะดะพะปะณะพ', 'ะดะพะปัŒัˆะต', 'ะดะพะฝั‹ะฝะต', 'ะดะพัะฒะตั‚ะปะฐ', 'ะดะพัะตะปะต', 'ะดะพัั€ะพั‡ะฝะพ', 'ะดะพั‚ะตะผะฝะฐ', 'ะดะพัƒั‚ั€ะฐ', 'ะตะดะธะฝะพะฒั€ะตะผะตะฝะฝะพ', 'ะตะถะตะบะฒะฐั€ั‚ะฐะปัŒะฝะพ', 'ะตะถะตะผะธะฝัƒั‚ะฝะพ', 'ะตะถะตะฝะพั‰ะฝะพ', 'ะตะถะตัะตะบัƒะฝะดะฝะพ', 'ะตะถะตั‡ะฐัะฝะพ', 'ะตั‰ะต', 'ะทะฐะฑะปะฐะณะพะฒั€ะตะผะตะฝะฝะพ', 'ะทะฐะฒัะตะณะดะฐ', 'ะทะฐะฒั‚ั€ะฐ', 'ะทะฐะดะพะปะณะพ', 'ะทะฐะณะพะดั', 'ะทะฐั€ะฐะฝะตะต', 'ะทะฐั€ะฐะท', 'ะทะฐัะธะผ', 'ะทะฐั‚ะตะผ', 'ะทะธะผะพะน', 'ะธะทะฒะตั‡ะฝะพ', 'ะธะทะดั€ะตะฒะปะต', 'ะธะทะฝะฐั‡ะฐะปัŒะฝะพ', 'ะธะฝะพะณะดะฐ', 'ะธัะบะพะฝะฝะพ', 'ะธัะฟะพะบะพะฝ', 'ะธััั‚ะฐั€ะธ', 'ะบั€ัƒะณะปะพััƒั‚ะพั‡ะฝะพ', 'ะบั€ัะดัƒ', 'ะปะตั‚ะพะผ', 'ะผะธะผะพะปะตั‚ะฝะพ', 'ะฝะฐะฒะตะบ', 'ะฝะฐะฒะตะบะธ', 'ะฝะฐะฒัะตะณะดะฐ', 'ะฝะฐะดะพะปะณะพ', 'ะฝะฐะทะฐะฒั‚ั€ะฐ', 'ะฝะฐะบะฐะฝัƒะฝะต', 'ะฝะฐะบะพะฝะตั†', 'ะฝะฐะผะตะดะฝะธ', 'ะฝะฐะฟะตั€ะตะด', 'ะฝะฐะฟะพัะปะตะดะพะบ', 'ะฝะฐะฟั€ะพะปะตั‚', 'ะฝะฐัะพะฒัะตะผ', 'ะฝะฐัƒั‚ั€ะพ', 'ะฝะตะดะฐะฒะฝะพ', 'ะฝะตะดะพะปะณะพ', 'ะฝะตะทะฐะดะพะปะณะพ', 'ะฝะตะทะฐะผะตะดะปะธั‚ะตะปัŒะฝะพ', 'ะฝะตะฝะฐะดะพะปะณะพ', 'ะฝะตัะบะพั€ะพ', 'ะฝะตะพะดะฝะพะบั€ะฐั‚ะฝะพ', 'ะฝะพะฝั‡ะต', 'ะฝะตะฟั€ะตั€ั‹ะฒะฝะพ', 'ะฝะตะฟั€ะพะดะพะปะถะธั‚ะตะปัŒะฝะพ', 'ะฝะพั‰ะฝะพ', 'ะฝั‹ะฝะต', 'ะฝั‹ะฝั‡ะต', 'ะพะดะฝะฐะถะดั‹', 'ะพะดะฝะพะฒั€ะตะผะตะฝะฝะพ', 'ะพัะตะฝัŒัŽ', 'ะพั‚ะบะพะปะต', 'ะพั‚ะฝั‹ะฝะต', 'ะพั‚ั€ะพะดัััŒ', 'ะฟะตั€ะฒะพะฝะฐั‡ะฐะปัŒะฝะพ', 'ะฟะพะทะฐะฒั‡ะตั€ะฐ', 'ะฟะพะทะดะฝะตะต', 'ะฟะพะทะดะฝะพ', 'ะฟะพะทะดะฝะพะฒะฐั‚ะพ', 'ะฟะพะทะถะต', 'ะฟะพะดะพะปะณัƒ', 'ะฟะพะดั€ัะด', 'ะฟะพะถะธะทะฝะตะฝะฝะพ', 'ะฟะพะบะฐ', 'ะฟะพะบะฐะผะตัั‚', 'ะฟะพะฝั‹ะฝะต', 'ะฟะพะฝะฐั‡ะฐะปัƒ', 'ะฟะพะฟะพะทะถะต', 'ะฟะพั€ะฐะฝัŒัˆะต', 'ะฟะพัะปะต', 'ะฟะพัะปะตะทะฐะฒั‚ั€ะฐ', 'ะฟะพัะฟะตัˆะฝะพ', 'ะฟะพัะบะพั€ะตะต', 'ะฟะพัั‚ะพัะฝะฝะพ', 'ะฟะพัƒั‚ั€ัƒ', 'ะฟั€ะตะถะดะต', 'ะฟั€ะตะถะดะตะฒั€ะตะผะตะฝะฝะพ', 'ะฟั€ะธัะฝะพ', 'ะฟั€ะพะดะพะปะถะธั‚ะตะปัŒะฝะพ', 'ั€ะตะดะบะพ', 'ั€ะตะถะต', 'ั€ะฐะฝะตะต', 'ั€ะฐะฝะพ', 'ั€ะฐะฝะพะฒะฐั‚ะพ', 'ั€ะฐะฝัŒัˆะต', 'ั€ะตะดะบะพ', 'ัะฒะพะตะฒั€ะตะผะตะฝะฝะพ', 'ัะตะณะพะดะฝั', 'ัะบะพั€ะตะต', 'ัะบะพั€ะตะน', 'ัะบะพั€ะพ', 'ัะผะพะปะพะดัƒ', 'ัะฝะฐั‡ะฐะปะฐ', 'ัะฟะตั€ะฒะฐ', 'ัั€ะฐะทัƒ', 'ัั€ะพั‡ะฝะพ', 'ัั€ะพะดัƒ', 'ั‚ะตะฟะตั€ะธั‡ะฐ', 'ั‡ะฐัั‚ะพ', 'ัƒะถะต', 'ัƒะถะพ'] interrogative_pronoun = ['ะบั‚ะพ', 'ั‡ั‚ะพ', 'ะบะฐะบะพะน', 'ะบะฐะบะพะฒ', 'ั‡ะตะน', 'ะบะพั‚ะพั€ั‹ะน', 'ะฟะพั‡ะตะผัƒ', 'ะทะฐั‡ะตะผ', 'ะณะดะต', 'ะบัƒะดะฐ', 'ะพั‚ะบัƒะดะฐ', 'ะพั‚ั‡ะตะณะพ'] def is_have_grammar(e): # try: return e[1] != '' # except KeyError as ke: # print("Key error:" + str(e)) # raise ke # 1 # test that the current word is a first person pronoun def first_person_pronoun(t): fpp1 = 0 for el in t: if el[2] in first_pp: fpp1 += 1 return fpp1 # 2 # test that the current word is a second person pronoun def second_person_pronoun(t): spp2 = 0 for el in t: if el[2] in second_pp: spp2 += 1 return spp2 # 3 # test that the current word is a third person pronoun def third_person_pronoun(t): tpp3 = 0 for el in t: if el[2] in third_pp: tpp3 += 1 return tpp3 # 4 # test that the current word is a pronoun def is_pronoun(t): pron = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'P': pron += 1 else: continue return pron # 5 # test that the current word is a finite verb def is_finite_verb(t): finite = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('vform') == 'i': finite += 1 else: continue return finite # 6 # test that the current word is an adjective or a participle # may be we should leave only test for adjectives and add a test that they are modifiers and not parts of predicates def is_modifier(t): mod = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'A' or (d_el.get('pos') == 'V' and d_el.get('vform') == 'p'): mod += 1 else: continue return mod # 7 # test that the current word has a past tense form def past_tense(t): past = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('tense') == 's': past += 1 else: continue return past # 8 # test that the current word has a perfect aspect form def perf_aspect(t): perf = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('aspect') == 'p': perf += 1 else: continue return perf # 9 # test that the current word has a present tense form def present_tense(t): pres = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('tense') == 'p': pres += 1 else: continue return pres # 10 # test that the current word is an adverb def total_adverb(t): total_adv = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'R': total_adv += 1 else: continue return total_adv # nouns # 11 # 12 # test that the current word a verbal noun (ะพั‚ะณะปะฐะณะพะปัŒะฝะพะต ััƒั‰.) or not verbal noun def is_nominalization(t): nomz = 0 nouns = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'N': with codecs.open('dictionaries/final_lemmas_nominalizations.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip() for s in f.readlines()]) if el[2].lower() in read_lines: nomz += 1 else: nouns += 1 else: continue return nomz, nouns # 13 # test that the current word has a genitive case form def is_genitive(t): gen = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if (d_el.get('pos') == 'N' or d_el.get('pos') == 'P' or d_el.get('pos') == 'A') and d_el.get('case') == 'g': gen += 1 else: continue return gen # 14 # test that the current word has a neuter gender form def is_neuter(t): neuter = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if ((d_el.get('pos') == 'N' or d_el.get('pos') == 'P' or d_el.get('pos') == 'A') and d_el.get('gender') == 'n'): neuter += 1 else: continue return neuter # 15 # test that the current word has a passive form def is_passive(t): passive = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and 'p' == d_el.get('voice'): passive += 1 else: continue return passive # 16 # test that the current verb is an infinitive def infinitives(t): infin = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('vform') == 'n': infin += 1 else: continue return infin # 17 # test that the current word is a speech verb def speech_verb(t): sp_verb = 0 with codecs.open(r'dictionaries/all_lemmas_verb_speech.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip() for s in f.readlines()]) for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V': if el[2].lower() in read_lines: sp_verb += 1 else: continue return sp_verb # 18 # test that the current word is a mental verb def mental_verb(t): mntl_verb = 0 with codecs.open(r'dictionaries/all_lemmas_verb_mental.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip() for s in f.readlines()]) for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V': if el[2].lower() in read_lines: mntl_verb += 1 else: continue return mntl_verb # 19 # test that the current sentence includes that-complement clause def that_complement(t): that_compl = 0 l = len(t) for i, el in enumerate(t): if is_have_grammar(el): if t[l - 1][0] != '?': d_el = process_grammar(el) d_next_el = {} if i + 1 < len(t): next_el = t[i + 1] d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} # test that current word is verb or short-form adjective and the next word is not a verb or # short-form adjective because of sentences like 'ะฏ ะฑั‹ะป ัั‡ะฐัั‚ะปะธะฒ, ั‡ั‚ะพ ะพะฝะฐ ะฟั€ะธัˆะปะฐ'. if d_el.get('pos') == 'V' or (d_el.get('pos') == 'A' and d_el.get('definiteness') == 's'): if is_have_grammar(next_el): if (d_next_el.get('pos') != 'V' and (d_next_el.get('pos') != 'A' or d_next_el.get('definiteness') != 's')): for j in range(4): # test that there's no pronouns like 'ั‚ะพ, ัั‚ะพ, ั‚ะฐะบะพะน' between the current word and comma # because of sentences like 'ะฏ ะฝะต ะฟั€ะตะดะฒะธะดะตะป ั‚ะพะณะพ, ั‡ั‚ะพ ะฒั‹ ะฟั€ะธะตะดะตั‚ะต', # which has relative meaning. # test that conjunction like 'ั‡ั‚ะพ', 'ั‡ั‚ะพะฑั‹' directly follow after comma if (i + j + 1 < len(t) and t[i + j][2] not in ['ะฒะตััŒ', 'ะฒัะต', 'ั‚ะฐะบะพะน', 'ั‚ะพ', 'ัั‚ะพ', 'ั‚ะพั‚', 'ัั‚ะพั‚'] and t[i + j + 1][0] == ',' and i + j + 2 < len(t) and t[i + j + 2][2] in ['ั‡ั‚ะพ', 'ั‡ั‚ะพะฑั‹']): if i + j + 3 < len(t): # test that if the conjunction is 'ั‡ั‚ะพะฑั‹', there's no infinitive verb after it # to check that it's not an infinitive clause if t[i + j + 2][2] == 'ั‡ั‚ะพะฑั‹': if is_have_grammar(t[i + j + 3]): d_is_inf_el = process_grammar(t[i + j + 3]) if d_is_inf_el.get('pos') == 'V' and d_is_inf_el.get( 'vform') == 'n': continue else: that_compl += 1 else: that_compl += 1 else: continue else: continue return that_compl # 20 # test that the current sentence includes wh-relative clause (ะพั‚ะฝะพัะธั‚ะตะปัŒะฝะพะต ะฟั€ะธะดะฐั‚ะพั‡ะฝะพะต) def wh_relatives(t): wh_relative = 0 l = len(t) # test that sentence is not interrogative if t[l - 1][0] != '?': for i, el in enumerate(t): # test that pronoun is in the left periphery of the sentence and preceded by comma if el[2] in ['ะบะฐะบะพะน', 'ั‡ะตะน', 'ะบะพั‚ะพั€ั‹ะน', 'ะฟะพั‡ะตะผัƒ', 'ะทะฐั‡ะตะผ', 'ะณะดะต', 'ะบัƒะดะฐ', 'ะพั‚ะบัƒะดะฐ', 'ะพั‚ั‡ะตะณะพ']: d_prev_el = {} if i - 1 > 0: prev_el = t[i - 1] if prev_el[0] == ',': wh_relative += 1 # test that there's the example of relative clause structure like "ะญั‚ะพ ะฑั‹ะป ั‚ะพั‚, ะบะพะณะพ ั ะฝะต ะฑะพัŽััŒ". if el[2] in ['ะบั‚ะพ']: if i - 1 > 0: prev_el = t[i - 1] if prev_el[0] == ',': if i - 2 > 0 and t[i - 2][2] in ['ั‚ะพั‚', 'ั‚ะพ', 'ะฒัะต', 'ะฒะตััŒ', 'ั‚ะฐะบะพะน']: wh_relative += 1 else: continue return wh_relative # 21 # test that the current word is preposition # (we count all prepositional phrases in the sentence by counting prepositions) def total_PP(t): prep_phrase = 0 with codecs.open(r'dictionaries/all_lemmas_prepositions.txt', mode='r', encoding='utf-8') as f: prepositions = set([s.strip() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in prepositions: prep_phrase += 1 else: if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'S' and el[0] != '.': prep_phrase += 1 else: continue return prep_phrase # 22 # function for counting mean word length # it is possibly better to count median word length def word_length(t): words = 0 letters = 0 for el in t: if el[0] not in ['.', ',', '!', '?', ':', ';', '"', '-', 'โ€”', 'โ€“']: words += 1 for let in el[0]: letters += 1 else: continue return letters, words # 23 # function for counting all syllables in the sentence def syllables(t): syll = 0 complex_w = 0 for el in t: for ch in el[0]: if ch in ['ะฐ', 'ะพ', 'ัƒ', 'ะธ', 'ั‹', 'ะต', 'ั‘', 'ั', 'ั', 'ัŽ']: syll += 1 if syll > 4: complex_w += 1 return syll, complex_w # 24 # interval between punctuation marks def text_span(t): result = 0 sent_span = 0 p = 0 list_of_spans = [] for i, el in enumerate(t): if el[0] in ['.', ',', '!', '?', ':', ';', '"', '-', 'โ€”', 'โ€“']: sent_span = i - p list_of_spans.append(sent_span) p = i if len(list_of_spans) == 0: result = 0 else: result = sum(list_of_spans) / len(list_of_spans) return result # 25 # function for counting mean sentence length def sentence_length(t): sent_words = 0 for el in t: if el[0] not in ['.', ',', '!', '?', ':', ';', '"', '-', 'โ€”', 'โ€“'] and el[1] != 'SENT': sent_words += 1 return sent_words # 26 # function for counting relation between lemmas and tokens (how many original words does the text include?) def type_token_ratio(t): types = set() tokens = 0 for el in t: if el[0] not in ['.', ',', '!', '?', ':', ';', '"', '-', 'โ€”', 'โ€“', '@', '#', '"', '$', '%', '*', '+', ')', '(', '[', ']', '{', '}', '&']: types.add(el[2]) tokens += 1 else: continue return types, tokens # 27 # test that the current word is a verbal adverb (ะดะตะตะฟั€ะธั‡ะฐัั‚ะธะต) def is_verbal_adverb(t): gerund = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('vform') == 'g': gerund += 1 else: continue return gerund # 28 # test that the sentence includes passive participles not in predicate position def passive_participial_clauses(t): pas_part_clauses = 0 for i, el in enumerate(t): if is_have_grammar(el): flag_predicate = False d_el = process_grammar(el) # test that current word is past participle if d_el.get('pos') == 'V' and d_el.get('vform') == 'p' and d_el.get('voice') == 'p': d_prev_el = {} d_prev_prev_el = {} if i > 0: prev_el = t[i - 1] d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} # test that the word is not a part of predicate like 'ะฑั‹ั‚ัŒ ัƒัั‚ะฐะฒัˆะธะผ', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั ั€ะฐะทะดั€ะฐะถะตะฝะฝั‹ะผ' if d_prev_el.get('pos') == 'V' and prev_el[2].lower() in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: flag_predicate = True if i - 1 > 0: prev_el = t[i - 1] prev_prev_el = t[i - 2] d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} d_prev_prev_el = process_grammar(prev_prev_el) d_prev_prev_el = d_prev_prev_el if d_prev_prev_el is not None else {} # test that the word is not a part of predicate separated by adverb or patricles from the list if d_prev_prev_el.get('pos') == 'V' and prev_prev_el[2].lower() in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: if d_prev_el.get('pos') == 'R' or prev_el[0].lower() in ['ะปะธ', 'ะฑั‹', 'ะฝะต']: flag_predicate = True if not flag_predicate: pas_part_clauses += 1 else: continue return pas_part_clauses # 29 # test that the sentence includes active participles not in predicate position def active_participial_clauses(t): act_part_clauses = 0 for i, el in enumerate(t): if is_have_grammar(el): flag_predicate = False d_el = process_grammar(el) # test that current word is active/medial participle if d_el.get('pos') == 'V' and d_el.get('vform') == 'p' and d_el.get('voice') != 'p': d_prev_el = {} d_prev_prev_el = {} if i > 0: prev_el = t[i - 1] d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} # test that the word is not a part of predicate like 'ะฑั‹ั‚ัŒ ะฟะพั‚ั€ััะฐัŽั‰ะธะผ' if d_prev_el.get('pos') == 'V' and prev_el[2].lower() in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: flag_predicate = True if i - 1 > 0: prev_el = t[i - 1] prev_prev_el = t[i - 2] d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} d_prev_prev_el = process_grammar(prev_prev_el) d_prev_prev_el = d_prev_prev_el if d_prev_prev_el is not None else {} # test that the word is not a part of predicate separated by adverb or patricles from the list if d_prev_prev_el.get('pos') == 'V' and prev_prev_el[2].lower() in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: if d_prev_el.get('pos') == 'R' or prev_el[0].lower() in ['ะปะธ', 'ะฑั‹', 'ะฝะต']: flag_predicate = True if not flag_predicate: act_part_clauses += 1 else: continue return act_part_clauses # 30 # test that the current word has an imperative mood form def imperative_mood(t): imp_mood = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) d_prev = {} d_next_el = {} # test that catch constructions like "ะดะฐะฒะฐะนั‚ะต ะฟะธัˆะธั‚ะต" to assign only one mark of imperative mood if d_el.get('pos') == 'V' and d_el.get('vform') == 'm': if el[0].lower() == 'ะดะฐะฒะฐะนั‚ะต' or el[0].lower() == 'ะดะฐะฒะฐะน': pass else: imp_mood += 1 # test that catch only "ะดะฐะฒะฐะน/ั‚ะต" without any verb after it if el[0].lower() == 'ะดะฐะฒะฐะนั‚ะต' or el[0].lower() == 'ะดะฐะฒะฐะน': if i + 1 < len(t): next_el = t[i + 1] if is_have_grammar(next_el): d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} if d_next_el.get('pos') != 'V': imp_mood += 1 elif d_next_el.get('vform') != 'm': imp_mood += 1 else: continue if i > 0: prev_el = t[i - 1] if d_el.get('pos') == 'V' and d_el.get('vform') == 'i' and d_el.get('person') == '3': if prev_el[0].lower() in ['ะดะฐ', 'ะฟัƒัั‚ัŒ', 'ะฟัƒัะบะฐะน']: imp_mood += 1 else: continue return imp_mood # 31 # test that the current word is an adjective in predicative position def predicative_adjectives(t): pred_adj = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'A' and d_el.get('definiteness') == 's': pred_adj += 1 if d_el.get('pos') == 'A' and d_el.get('definiteness') == 'f': d_prev_el = {} if i > 0: prev_el = t[i - 1] if is_have_grammar(prev_el): d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} if d_prev_el.get('pos') == 'V' and prev_el[2] in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: pred_adj += 1 else: continue else: continue return pred_adj # 32 # test that the current word is an adjective in attributive position def attributive_adjective(t): attr_adj = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) flag_predicate = False if d_el.get('pos') == 'A' and d_el.get('definiteness') == 'f': d_prev_el = {} if i > 0: prev_el = t[i - 1] if is_have_grammar(prev_el): d_prev_el = process_grammar(prev_el) d_prev_el = d_prev_el if d_prev_el is not None else {} if d_prev_el.get('pos') == 'V' and prev_el[2] in ['ะฑั‹ั‚ัŒ', 'ะดะตะปะฐั‚ัŒัั', 'ัะดะตะปะฐั‚ัŒัั', 'ะบะฐะทะฐั‚ัŒัั', 'ะฝะฐะทั‹ะฒะฐั‚ัŒัั', 'ัั‚ะฐะฝะพะฒะธั‚ัŒัั', 'ัะฒะปัั‚ัŒัั']: flag_predicate = True if not flag_predicate: attr_adj += 1 else: continue else: continue return attr_adj # 33 # test that the sentence includes causative subordinate clause def causative_subordinate(t): causative_sub = 0 for i, el in enumerate(t): if el[0] in ['ะฟะพัะบะพะปัŒะบัƒ', 'ะธะฑะพ']: causative_sub += 1 else: if i > 0: prev_el = t[i - 1] # test that conjunction is 'ั‚ะฐะบ ะบะฐะบ' if prev_el[0] == 'ั‚ะฐะบ' and el[0] == 'ะบะฐะบ': causative_sub += 1 if i + 1 < len(t): next_el = t[i + 1] # test that conjunction is 'ะทะฐั‚ะตะผ ั‡ั‚ะพ', 'ะฟะพั‚ะพะผัƒ ั‡ั‚ะพ', 'ะพั‚ั‚ะพะณะพ ั‡ั‚ะพ' if el[0] in ['ะทะฐั‚ะตะผ', 'ะฟะพั‚ะพะผัƒ', 'ะพั‚ั‚ะพะณะพ'] and next_el[0] == 'ั‡ั‚ะพ': causative_sub += 1 if i + 2 < len(t): next_el = t[i + 1] next_next_el = t[i + 2] # test that conjunction is 'ะทะฐั‚ะตะผ ั‡ั‚ะพ', 'ะฟะพั‚ะพะผัƒ ั‡ั‚ะพ', 'ะพั‚ั‚ะพะณะพ ั‡ั‚ะพ' separated by comma ('ะฟะพั‚ะพะผัƒ, ั‡ั‚ะพ') if el[0] in ['ะทะฐั‚ะตะผ', 'ะฟะพั‚ะพะผัƒ', 'ะพั‚ั‚ะพะณะพ'] and next_el[0] == ',' and next_next_el[0] == 'ั‡ั‚ะพ': causative_sub += 1 # test that conjunction is 'ะฒะฒะธะดัƒ ั‚ะพะณะพ ั‡ั‚ะพ', 'ะฒัะปะตะดัั‚ะฒะธะต ั‚ะพะณะพ ั‡ั‚ะพ', 'ะฑะปะฐะณะพะดะฐั€ั ั‚ะพะผัƒ ั‡ั‚ะพ' if el[0] in ['ะฒะฒะธะดัƒ', 'ะฒัะปะตะดัั‚ะฒะธะต', 'ะฑะปะฐะณะพะดะฐั€ั'] and next_el[2] == 'ั‚ะพ' and next_next_el[0] == 'ั‡ั‚ะพ': causative_sub += 1 if i + 3 < len(t): next_el = t[i + 1] next_next_el = t[i + 2] next_next_next_el = t[i + 3] # test that conjunction is 'ะฒะฒะธะดัƒ ั‚ะพะณะพ, ั‡ั‚ะพ', 'ะฒัะปะตะดัั‚ะฒะธะต ั‚ะพะณะพ, ั‡ั‚ะพ', 'ะฑะปะฐะณะพะดะฐั€ั ั‚ะพะผัƒ, ั‡ั‚ะพ' if (el[0] in ['ะฒะฒะธะดัƒ', 'ะฒัะปะตะดัั‚ะฒะธะต', 'ะฑะปะฐะณะพะดะฐั€ั'] and next_el[2] == 'ั‚ะพ' and next_next_el[0] == ',' and next_next_next_el[0] == 'ั‡ั‚ะพ'): causative_sub += 1 if i + 2 < len(t) and i > 0: prev_el = t[i - 1] next_el = t[i + 1] next_next_el = t[i + 2] # test that conjunction is 'ะฒ ัะธะปัƒ ั‚ะพะณะพ ั‡ั‚ะพ' if el[0] == 'ัะธะปัƒ' and prev_el[0] == 'ะฒ' and next_el[2] == 'ั‚ะพ' and next_next_el[0] == 'ั‡ั‚ะพ': causative_sub += 1 if i + 3 < len(t) and i > 0: prev_el = t[i - 1] next_el = t[i + 1] next_next_el = t[i + 2] next_next_next_el = t[i + 3] # test that conjunction is 'ะฒ ัะธะปัƒ ั‚ะพะณะพ, ั‡ั‚ะพ' if (el[0] == 'ัะธะปัƒ' and prev_el[0] == 'ะฒ' and next_el[2] == 'ั‚ะพ' and next_next_el[0] == ',' and next_next_next_el[0] == 'ั‡ั‚ะพ'): causative_sub += 1 # test that conjunction is 'ะฒ ัะฒัะทะธ ั ั‚ะตะผ ั‡ั‚ะพ' if (el[0] == 'ัะฒัะทะธ' and prev_el[0] == 'ะฒ' and next_el[0] == 'ั' and next_next_el[2] == 'ั‚ะพ' and next_next_next_el[0] == 'ั‡ั‚ะพ'): causative_sub += 1 if i + 4 < len(t) and i > 0: prev_el = t[i - 1] next_el = t[i + 1] next_next_el = t[i + 2] next_next_next_el = t[i + 3] next_next_next_next_el = t[i + 4] # test that conjunction is 'ะฒ ัะฒัะทะธ ั ั‚ะตะผ, ั‡ั‚ะพ' if (el[0] == 'ัะฒัะทะธ' and prev_el[0] == 'ะฒ' and next_el[0] == 'ั' and next_next_el[2] == 'ั‚ะพ' and next_next_next_el[0] == ',' and next_next_next_next_el[0] == 'ั‡ั‚ะพ'): causative_sub += 1 else: continue return causative_sub # 34 # test that the sentence includes concessive subordinate clause def concessive_subordinate(t): concessive_sub = 0 for i, el in enumerate(t): d_next_el = {} if el[0] == 'ั…ะพั‚ัŒ': concessive_sub += 1 if i + 1 < len(t): next_el = t[i + 1] if el[0] == 'ะดะฐั€ะพะผ' and next_el[0] == 'ั‡ั‚ะพ': concessive_sub += 1 if el[0] in ['ะฝะตัะผะพั‚ั€ั', 'ะฝะตะฒะทะธั€ะฐั'] and next_el[0] == 'ะฝะฐ': concessive_sub += 1 if el[0] in ['ั‚ะพะปัŒะบะพ', 'ะปะธัˆัŒ', 'ะดะพะฑั€ะพ'] and next_el[0] == 'ะฑั‹': concessive_sub += 1 if is_have_grammar(next_el): d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} if el[0] in ['ะฟัƒัั‚ัŒ', 'ะฟัƒัะบะฐะน'] and not ( d_next_el.get('pos') == 'V' and d_next_el.get('person') == '3'): concessive_sub += 1 if is_have_grammar(el): d_el = process_grammar(el) if el[0] == 'ั…ะพั‚ั' and d_el.get('pos') == 'C': concessive_sub += 1 else: continue return concessive_sub # 35 # test that the sentence includes conditional subordinate clause def conditional_subordinate(t): conditional_sub = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if el[0] in ['ะตัะปะธ', 'ะตะถะตะปะธ', 'ะบะฐะฑั‹', 'ะบะพะปัŒ', 'ะบะพะปะธ', 'ั€ะฐะท'] and d_el.get('pos') == 'C': conditional_sub += 1 else: continue return conditional_sub # 36 # test that the sentence includes purpose subordinate clause def purpose_subordinate(t): purpose_sub = 0 for i, el in enumerate(t): if el[0] == 'ะดะฐะฑั‹': purpose_sub += 1 if el[0] in ['ั‡ั‚ะพะฑั‹', 'ั‡ั‚ะพะฑ']: if i == 0: purpose_sub += 1 else: flag_not_purpose = False if i > 0: prev_el = t[i - 1] if prev_el[2] in ['ัะพะผะฝะตะฒะฐั‚ัŒัั', 'ั…ะพั‚ะตั‚ัŒ', 'ะทะฐั…ะพั‚ะตั‚ัŒ', 'ั‚ั€ะตะฑะพะฒะฐั‚ัŒ', 'ะฟั€ะพัะธั‚ัŒ', 'ะถะตะปะฐั‚ัŒ', 'ะถะดะฐั‚ัŒ', 'ะผะตั‡ั‚ะฐั‚ัŒ', 'ะปัŽะฑะธั‚ัŒ', 'ะทะฐะณะฐะดะฐั‚ัŒ', 'ะทะฐั…ะพั‚ะตั‚ัŒัั', 'ั…ะพั‚ะตั‚ัŒัั']: flag_not_purpose = True if i - 1 > 0: prev_el = t[i - 1] prev_prev_el = t[i - 2] if prev_el[0] == ',' and prev_prev_el[2] in ['ัะพะผะฝะตะฒะฐั‚ัŒัั', 'ั…ะพั‚ะตั‚ัŒ', 'ะทะฐั…ะพั‚ะตั‚ัŒ', 'ั‚ั€ะตะฑะพะฒะฐั‚ัŒ', 'ะฟั€ะพัะธั‚ัŒ', 'ะถะตะปะฐั‚ัŒ', 'ะถะดะฐั‚ัŒ', 'ะผะตั‡ั‚ะฐั‚ัŒ', 'ะปัŽะฑะธั‚ัŒ', 'ะทะฐะณะฐะดะฐั‚ัŒ', 'ะทะฐั…ะพั‚ะตั‚ัŒัั', 'ั…ะพั‚ะตั‚ัŒัั']: flag_not_purpose = True if (prev_el[2] in ['ัƒะฒะตั€ะธั‚ัŒ', 'ัƒะฒะตั€ะตะฝ', 'ัƒะฒะตั€ะตะฝะฝั‹ะน', 'ะฒะตั€ะธั‚ัŒ', 'ัะบะฐะทะฐั‚ัŒ', 'ั‚ะพ'] and prev_prev_el[0] == 'ะฝะต'): flag_not_purpose = True if i - 2 > 0: prev_el = t[i - 1] prev_prev_el = t[i - 2] prev_prev_prev_el = t[i - 3] if (prev_el[0] == ',' and prev_prev_el[2] in ['ัƒะฒะตั€ะตะฝะฝั‹ะน', 'ัƒะฒะตั€ะตะฝ', 'ัƒะฒะตั€ะธั‚ัŒ', 'ะฒะตั€ะธั‚ัŒ', 'ัะบะฐะทะฐั‚ัŒ', 'ั‚ะพ'] and prev_prev_prev_el[0] == 'ะฝะต'): flag_not_purpose = True if prev_el[2] == 'ัะบะฐะทะฐั‚ัŒ' and prev_prev_el[2] == 'ะผะพั‡ัŒ' and prev_prev_prev_el[0] == 'ะฝะต': flag_not_purpose = True if i - 3 > 0: prev_el = t[i - 1] prev_prev_el = t[i - 2] prev_prev_prev_el = t[i - 3] prev_prev_prev_prev_el = t[i - 4] if (prev_el[0] == ',' and prev_prev_el[2] == 'ัะบะฐะทะฐั‚ัŒ' and prev_prev_prev_el[2] == 'ะผะพั‡ัŒ' and prev_prev_prev_prev_el[0] == 'ะฝะต'): flag_not_purpose = True if not flag_not_purpose: purpose_sub += 1 else: continue return purpose_sub # 37 # test that the current word has a conditional mood form def conditional_mood(t): cond = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and d_el.get('vform') == 'c' or el[0] == 'ะฑั‹': cond += 1 else: continue return cond # 38 # test that the current word is a modal word (possibility) def modal_possibility(t): mod_pos = 0 for i, el in enumerate(t): if el[2] in ['ะผะพั‡ัŒ'] or el[0] in ['ะฟะพ-ะฒะธะดะธะผะพะผัƒ']: mod_pos += 1 if is_have_grammar(el): d_el = process_grammar(el) if i + 1 < len(t): next_el = t[i + 1] if ((el[0] == 'ะผะพะถะฝะพ' and next_el[0] == 'ะฑั‹ั‚ัŒ') or (el[0] == 'ะฒัะตะน' and next_el[0] == 'ะฒะตั€ะพัั‚ะฝะพัั‚ะธ') or (el[0] == 'ะตะดะฒะฐ' and next_el[0] == 'ะปะธ') or (el[0] == 'ั‡ัƒั‚ัŒ' and next_el[0] == 'ะปะธ') or (el[0] == 'ะฒั€ัะด' and next_el[0] == 'ะปะธ')): mod_pos += 1 if d_el.get('pos') == 'R' and el[2] in ['ะฝะฐะฒะตั€ะฝะพะต', 'ะฝะฐะฒะตั€ะฝะพ', 'ะฒะพะทะผะพะถะฝะพ', 'ะฒะธะดะธะผะพ', 'ะฒะตั€ะฝะพ', 'ะฒะตั€ะพัั‚ะฝะพ', 'ะฟะพะถะฐะปัƒะน', 'ะผะพะถะฝะพ']: mod_pos += 1 return mod_pos # 39 # test that the current word is a modal word (necessity) def modal_necessity(t): mod_nec = 0 for i, el in enumerate(t): d_el = process_grammar(el) if el[0] == 'ั‚ั€ะตะฑัƒะตั‚ัั': mod_nec += 1 if i + 1 < len(t): next_el = t[i + 1] if is_have_grammar(next_el): d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} if el[0] in ['ัะปะตะดัƒะตั‚', 'ะฝะฐะดะปะตะถะธั‚'] and d_next_el.get('pos') == 'V' and d_next_el.get('vform') == 'n': mod_nec += 1 if is_have_grammar(el): if d_el.get('pos') == 'R' and el[2] in ['ะฝัƒะถะฝะพ', 'ะฝะฐะดะพ', 'ะฝะตะพะฑั…ะพะดะธะผะพ', 'ะฝะตะปัŒะทั', 'ะพะฑัะทะฐั‚ะตะปัŒะฝะพ', 'ะฝะตะธะทะฑะตะถะฝะพ', 'ะฝะตะฟั€ะตะผะตะฝะฝะพ']: mod_nec += 1 if el[2] in ['ะดะพะปะถะฝั‹ะน', 'ะพะฑัะทะฐะฝะฝั‹ะน'] and d_el.get('pos') == 'A' and d_el.get('definiteness') == 's': mod_nec += 1 return mod_nec # 40 # test that the current word is evaluative def evaluative_vocabulary(t): eval = 0 with codecs.open(r'dictionaries/evaluative_vocab.txt', mode='r', encoding='utf-8') as f: evaluative_words = set([s.strip() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in evaluative_words: eval += 1 return eval # 41 # test that the current word is academic def academic_vocabulary(t): acad = 0 with codecs.open(r'dictionaries/academic_words.txt', mode='r', encoding='utf-8') as f: academic_words = set([s.strip() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in academic_words: acad += 1 return acad # 42 # test that the sentence includes parenthesis with the meaning of attitude or evaluation def parenthesis_attitude_evaluation(t): parent = 0 for i, el in enumerate(t): flag = False if el[0] in ['ัƒะฒั‹', 'ัั‚ั€ะฐะฝะฝะพ', 'ัƒะดะธะฒะธั‚ะตะปัŒะฝะพ', 'ะฝะฐะดะตัŽััŒ', 'ะดัƒะผะฐัŽ', 'ะฟะพะปะฐะณะฐัŽ', 'ะฟะพะถะฐะปัƒะน', 'ะดัƒะผะฐะตั‚ัั', 'ะบะพะฝะตั‡ะฝะพ', 'ั€ะฐะทัƒะผะตะตั‚ัั', 'ะฑะตััะฟะพั€ะฝะพ', 'ะดะตะนัั‚ะฒะธั‚ะตะปัŒะฝะพ', 'ะฟะพะปะพะถะธะผ', 'ะฟั€ะตะดะฟะพะปะพะถะธะผ', 'ะดะพะฟัƒัั‚ะธะผ', 'ะฟั€ะธะทะฝะฐัŽััŒ']: if i + 1 < len(t): next_el = t[i + 1] if i == 0 and next_el[0] == ',': flag = True if i > 0: prev_el = t[i - 1] if prev_el[0] == ',': flag = True if el[0] in ['ัั‡ะฐัั‚ัŒัŽ', 'ั€ะฐะดะพัั‚ะธ', 'ัƒะดะพะฒะพะปัŒัั‚ะฒะธัŽ', 'ะฝะตัั‡ะฐัั‚ัŒัŽ', 'ัƒะดะธะฒะปะตะฝะธัŽ', 'ัะพะถะฐะปะตะฝะธัŽ', 'ะธะทัƒะผะปะตะฝะธัŽ', 'ัั‚ั‹ะดัƒ', 'ะดะพัะฐะดะต', 'ะฝะตัƒะดะพะฒะพะปัŒัั‚ะฒัŽ', 'ะฟั€ะธัะบะพั€ะฑะธัŽ', 'ะพะณะพั€ั‡ะตะฝะธัŽ']: if i > 0: prev_el = t[i - 1] if prev_el[0] == 'ะบ': flag = True if i - 1 > 0: prev_prev_el = t[i - 2] if prev_prev_el[0] == 'ะบ': flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 1 or (i - 1 > 0 and t[i - 2][0] == ','): prev_el = t[i - 1] if (el[0] in ['ั…ะพั€ะพัˆะพ', 'ั…ัƒะถะต', 'ะฟะปะพั…ะพ', 'ั…ัƒะถะต', 'ะพะฑะธะดะฝะพ'] and prev_el[0] == 'ั‡ั‚ะพ' or el[0] in ['ะฝะตัั‡ะฐัั‚ัŒัŽ', 'ะฟั€ะฐะฒะดะต', 'ััƒั‰ะตัั‚ะฒัƒ', 'ััƒั‚ะธ'] and prev_el[0] == 'ะฟะพ' or el[0] == 'ะดะตะปะพ' and prev_el[0] in ['ัั‚ั€ะฐะฝะฝะพะต', 'ัƒะดะธะฒะธั‚ะตะปัŒะฝะพะต', 'ะฝะตะฟะพะฝัั‚ะฝะพะต'] or el[0] == 'ะดะพะฑั€ะพะณะพ' and prev_el[0] == 'ั‡ะตะณะพ' or el[0] == 'ะฟะพะปะฐะณะฐั‚ัŒ' and prev_el[ 0] == 'ะฝะฐะดะพ' or el[0] == 'ัะพะผะฝะตะฝะธั' and prev_el[0] == 'ะฑะตะท' or el[0] == 'ัะพะฑะพะน' and prev_el[ 0] == 'ัะฐะผะพ' or el[0] == 'ะพะฑั€ะฐะทะพะผ' and prev_el[0] == 'ะฝะตะบะพั‚ะพั€ั‹ะผ' or el[0] == 'ั…ะพั‚ะธั‚ะต' and prev_el[ 0] == 'ะตัะปะธ' or el[0] == 'ัˆัƒั‚ะพะบ' and prev_el[0] == 'ะบั€ะพะผะต' or el[0] == 'ัะบะฐะถัƒ' and prev_el[ 0] == 'ะฟั€ัะผะพ' or el[0] == 'ะฑะตะดัƒ' and prev_el[0] == 'ะฝะฐ' or el[0] == 'ะดะตะปะพะผ' and prev_el[ 0] == 'ะณั€ะตัˆะฝั‹ะผ' or el[0] == 'ั‡ะฐั' and prev_el[0] in ['ะฝะตั€ะพะฒะตะฝ', 'ะฝะตั€ะพะฒั‘ะฝ'] or el[0] == 'ะฝะฐั€ะพั‡ะฝะพ' and prev_el[0] == 'ะบะฐะบ'): if next_el[0] in [',', '.']: flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 2 or (i - 2 > 0 and t[i - 3][0] == ','): prev_el = t[i - 1] prev_prev_el = t[i - 2] if (el[0] == 'ะฑะพะณ' and prev_el[0] == 'ะดะฐะน' and prev_prev_el[0] == 'ะฝะต' or el[0] == 'ั€ะฐะทัƒะผะตะตั‚ัั' and prev_el[0] == 'ัะพะฑะพะน' and prev_prev_el[0] == 'ัะฐะผะพ' or el[0] == 'ัะผั‹ัะปะต' and prev_el[0] == 'ะบะฐะบะพะผ-ั‚ะพ' and prev_prev_el[0] == 'ะฒ' or el[0] == 'ัะพะฒะตัั‚ะธ' and prev_el[0] == 'ะฟะพ' and prev_prev_el[0] == 'ะณะพะฒะพั€ั' or el[0] == 'ั‡ะตัั‚ะธ' and prev_el[0] == 'ะฟะพ' and prev_prev_el[0] == 'ัะบะฐะทะฐั‚ัŒ' or el[0] == 'ะณะพะฒะพั€ั' and prev_el[0] == 'ะฝะฐะผะธ' and prev_prev_el[0] == 'ะผะตะถะดัƒ' or el[0] == 'ัะบะฐะทะฐั‚ัŒ' and prev_el[0] == 'ะฟั€ะฐะฒะดัƒ' and prev_prev_el[0] == 'ะตัะปะธ' or el[0] == 'ะณะพะฒะพั€ั' and prev_el[0] == 'ะฟั€ะฐะฒะดะต' and prev_prev_el[0] == 'ะฟะพ' or el[0] == 'ะณะพะฒะพั€ั' and prev_el[0] == 'ััƒั‰ะฝะพัั‚ะธ' and prev_prev_el[0] == 'ะฒ' or el[0] == 'ะณะพะฒะพั€ะธั‚ัŒ' and prev_el[0] == 'ะทั€ั' and prev_prev_el[0] == 'ะฝะตั‡ะตะณะพ' or el[0] in ['ั…ะพั€ะพัˆะพ', 'ะปัƒั‡ัˆะต', 'ะฟะปะพั…ะพ', 'ั…ัƒะถะต'] and prev_el[0] == 'ะตั‰ะต' and prev_prev_el[0] == 'ั‡ั‚ะพ'): if next_el[0] in [',', '.']: flag = True if flag: parent += 1 return parent # 43 # test that the current word is an animate noun def animate_nouns(t): anim_nouns = 0 with codecs.open('dictionaries/all_lemmas_animate_nouns.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in read_lines: anim_nouns += 1 return anim_nouns # 44 # test that the sentence includes parenthesis with the meaning of accentuation def parenthesis_accentuation(t): parent = 0 for i, el in enumerate(t): flag = False if el[0] in ['ะฟะพะฒั‚ะพั€ััŽ', 'ะฟะพะฒั‚ะพั€ัะตะผ', 'ะฟะพะดั‡ะตั€ะบะธะฒะฐัŽ', 'ะฟะพะดั‡ะตั€ะบะธะฒะฐะตะผ', 'ะฟั€ะตะดัั‚ะฐะฒัŒ', 'ะฟั€ะตะดัั‚ะฐะฒัŒั‚ะต', 'ะฟะพะฒะตั€ะธัˆัŒ', 'ะฟะพะฒะตั€ะธั‚ะต', 'ะฒะพะพะฑั€ะฐะทะธ', 'ะฒะพะพะฑั€ะฐะทะธั‚ะต', 'ัะพะณะปะฐัะธััŒ', 'ัะพะณะปะฐัะธั‚ะตััŒ', 'ะทะฐะผะตั‚ัŒ', 'ะทะฐะผะตั‚ัŒั‚ะต', 'ะทะฐะผะตั‡ัƒ', 'ะทะฐะผะตั‚ะธะผ', 'ะฝะฐะฟั€ะธะผะตั€', 'ะทะฝะฐะตัˆัŒ', 'ะทะฝะฐะตั‚ะต', 'ะทะฝะฐั‡ะธั‚', 'ะฟะพะฝะธะผะฐะตัˆัŒ', 'ะฟะพะฝะธะผะฐะตั‚ะต', 'ะณะปะฐะฒะฝะพะต', 'ัะพะฑัั‚ะฒะตะฝะฝะพ', 'ะฟะพะฒะตั€ัŒ', 'ะฟะพะฒะตั€ัŒั‚ะต']: if i + 1 < len(t): next_el = t[i + 1] if i == 0 and next_el[0] == ',': flag = True if i > 0: prev_el = t[i - 1] if prev_el[0] == ',': flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 1 or (i - 1 > 0 and t[i - 2][0] == ','): prev_el = t[i - 1] if (el[0] in ['ะฒะฐะถะฝะพ', 'ััƒั‰ะตัั‚ะฒะตะฝะฝะพ'] and prev_el[0] == 'ั‡ั‚ะพ' or el[0] in ['ะฟะพะฒะตั€ะธัˆัŒ', 'ะฟะพะฒะตั€ะธั‚ะต'] and prev_el[0] == 'ะฝะต' or el[0] == 'ะดะตะปะพ' and prev_el[0] == 'ะณะปะฐะฒะฝะพะต' or el[0] in ['ะฝะฐะฟะพะผะธะฝะฐัŽ', 'ะฝะฐะฟะพะผะธะฝะฐะตะผ'] and prev_el[0] == 'ะบะฐะบ' or el[0] == 'ะฟั€ะธะผะตั€ัƒ' and prev_el[0] == 'ะบ' or el[0] == 'ัะบะฐะทะฐั‚ัŒ' and prev_el[0] == 'ั‚ะฐะบ' or el[0] in ['ะฒะฐะผ', 'ั‚ะตะฑะต'] and prev_el[0] == 'ัะบะฐะถัƒ' or el[0] == 'ัะบะฐะทะฐั‚ัŒ' and prev_el[0] == 'ะฝะฐะดะพ' or el[0] == 'ะพะฑั‰ะตะผ' and prev_el[0] == 'ะฒ' or el[0] == 'ะณะพะฒะพั€ั' and prev_el[0] == 'ัะพะฑัั‚ะฒะตะฝะฝะพ'): if next_el[0] in [',', '.']: flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 2 or (i - 2 > 0 and t[i - 3][0] == ','): prev_el = t[i - 1] prev_prev_el = t[i - 2] if (el[0] in ['ะฒะฐะถะฝะตะต', 'ััƒั‰ะตัั‚ะฒะตะฝะฝะตะต'] and prev_el[0] == 'ะตั‰ะต' and prev_prev_el[0] == 'ั‡ั‚ะพ' or el[0] == 'ะฟั€ะตะดัั‚ะฐะฒะธั‚ัŒ' and prev_el[0] == 'ัะตะฑะต' and prev_prev_el[0] in ['ะผะพะถะตัˆัŒ', 'ะผะพะถะตั‚ะต']): if next_el[0] in [',', '.']: flag = True if flag: parent += 1 return parent # 45 # test that the sentence includes parenthesis with the meaning of relation def parenthesis_relation(t): parent = 0 for i, el in enumerate(t): flag = False if el[0] in ['ะฒะดะพะฑะฐะฒะพะบ', 'ะฟั€ะธั‚ะพะผ', 'ัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพ', 'ะฝะฐะฟั€ะพั‚ะธะฒ', 'ะฝะฐะพะฑะพั€ะพั‚', 'ะฒะพ-ะฟะตั€ะฒั‹ั…', 'ะฒะพ-ะฒั‚ะพั€ั‹ั…', 'ะฒ-ั‚ั€ะตั‚ัŒะธั…', 'ะฒ-ั‡ะตั‚ะฒะตั€ั‚ั‹ั…', 'ะฒ-ะฟัั‚ั‹ั…', 'ะฒ-ัˆะตัั‚ั‹ั…', 'ะฒ-ัะตะดัŒะผั‹ั…', 'ะฒ-ะฒะพััŒะผั‹ั…', 'ะฒ-ะดะตะฒัั‚ั‹ั…', 'ะฒ-ะดะตััั‚ั‹ั…', 'ะทะฝะฐั‡ะธั‚', 'ะบัั‚ะฐั‚ะธ', 'ะณะปะฐะฒะฝะพะต']: if i + 1 < len(t): next_el = t[i + 1] if i == 0 and next_el[0] == ',': flag = True if i > 0: prev_el = t[i - 1] if prev_el[0] == ',': flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 1 or (i - 1 > 0 and t[i - 2][0] == ','): prev_el = t[i - 1] if (el[0] == 'ั‚ะพะณะพ' and prev_el[0] in ['ะบั€ะพะผะต', 'ัะฒะตั€ั…'] or el[0] == 'ะฑั‹ั‚ัŒ' and prev_el[0] == 'ัั‚ะฐะปะพ' or el[0] == 'ะฑะพะปะตะต' and prev_el[0] == 'ั‚ะตะผ' or el[0] in ['ะฒะพะดะธั‚ัั', 'ะฟะพะฒะตะปะพััŒ', 'ะฒัะตะณะดะฐ'] and prev_el[0] == 'ะบะฐะบ' or el[0] in ['ะพะฑั‹ั‡ะฐัŽ', 'ะพะฑั‹ะบะฝะพะฒะตะฝะธัŽ'] and prev_el[0] == 'ะฟะพ' or el[0] in ['ั‚ะฒะพั', 'ะฒะฐัˆะฐ'] and prev_el[0] == 'ะฒะพะปั' or el[0] == 'ะฒะพะปั' and prev_el[0] in ['ั‚ะฒะพั', 'ะฒะฐัˆะฐ'] or el[0] == 'ะฑั‹ั‚ัŒ' and prev_el[0] == 'ัั‚ะฐะปะพ' or el[0] == 'ั‚ะพะณะพ' and prev_el[0] in ['ะผะฐะปะพ', 'ัะฒะตั€ั…', 'ะฟะพะผะธะผะพ']): if next_el[0] in [',', '.']: flag = True if i + 1 < len(t): next_el = t[i + 1] if i == 2 or (i - 2 > 0 and t[i - 3][0] == ','): prev_el = t[i - 1] prev_prev_el = t[i - 2] if (el[0] == 'ะถะต' and prev_el[0] == 'ั‚ะพะผัƒ' and prev_prev_el[0] == 'ะบ' or el[0] == 'ะฒัะตะณะพ' and prev_el[0] == 'ะดะพะฒะตั€ัˆะตะฝะธะต' and prev_prev_el[0] == 'ะฒ' or el[0] == 'ั…ะพั‡ะตัˆัŒ' and prev_el[0] == 'ั‚ั‹' and prev_prev_el[0] == 'ะบะฐะบ' or el[0] == 'ะถะต' and prev_el[0] == 'ั‚ะพะผัƒ' and prev_prev_el[0] == 'ะถะต' or el[0] == 'ะบะพะฝั†ะพะฒ' and prev_el[0] == 'ะบะพะฝั†ะต' and prev_prev_el[0] == 'ะฒ'): if next_el[0] in [',', '.']: flag = True if flag: parent += 1 return parent # 46 # test that the current word is an adverb with the meaning of degree def degree_adverb(t): degree = 0 for i, el in enumerate(t): if el[0] in ['ั‡ะตั€ะตัั‡ัƒั€', 'ะฒั‚ั€ะพะต', 'ะฒั‡ะตั‚ะฒะตั€ะพ', 'ะฒะฟัั‚ะตั€ะพ', 'ะฒัˆะตัั‚ะตั€ะพ', 'ะฒัะตะผะตั€ะพ', 'ะฒะดะตััั‚ะตั€ะพ', 'ั‡ัƒั‚ัŒ-ั‡ัƒั‚ัŒ', 'ะฝะตะฒั‹ั€ะฐะทะธะผะพ', 'ะฝะตัะบะฐะทะฐะฝะฝะพ', 'ะฑะตัะฟั€ะตะดะตะปัŒะฝะพ', 'ะฑะตะทะผะตั€ะฝะพ', 'ะฝะตะฒั‹ะฝะพัะธะผะพ', 'ั„ะตะฝะพะผะตะฝะฐะปัŒะฝะพ', 'ัะฒะตั€ั…ัŠะตัั‚ะตัั‚ะฒะตะฝะฝะพ', 'ะตะดะฒะฐ-ะตะดะฒะฐ']: degree += 1 if i + 1 < len(t): next_el = t[i + 1] if is_have_grammar(next_el): d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} if el[0] == 'ะฝะตัะบะพะปัŒะบะพ' and d_next_el.get('pos') == 'A': degree += 1 if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'R' and el[0] in ['ะบั€ะฐะนะฝะต', 'ะพั‡ะตะฝัŒ', 'ัั‚ั€ะฐัˆะฝะพ', 'ัƒะดะธะฒะธั‚ะตะปัŒะฝะพ', 'ะธัะบะปัŽั‡ะธั‚ะตะปัŒะฝะพ', 'ัะปะธัˆะบะพะผ', 'ะณะพั€ะฐะทะดะพ', 'ะฐะฑัะพะปัŽั‚ะฝะพ', 'ัะพะฒะตั€ัˆะตะฝะฝะพ', 'ะฝะตะพะฑั‹ั‡ะฝะพ', 'ะฒะตััŒะผะฐ', 'ัะพะฒัะตะผ', 'ะฝะฐัั‚ะพะปัŒะบะพ', 'ะฒะดะฒะพะต', 'ะตะปะต', 'ะตะปะต-ะตะปะต', 'ะฝะตะผะฝะพะณะพ', 'ะฝะตะพะฑั‹ะบะฝะพะฒะตะฝะฝะพ', 'ะฝะตะพะฑั‹ั‡ะฐะนะฝะพ', 'ั„ะฐะฝั‚ะฐัั‚ะธั‡ะตัะบะธ', 'ั‡ั€ะตะทะฒั‹ั‡ะฐะนะฝะพ', 'ะฑะตัˆะตะฝะพ', 'ั‡ัƒะดะพะฒะธั‰ะฝะพ', 'ะฝะตัะปั‹ั…ะฐะฝะฝะพ', 'ะฑะพะถะตัั‚ะฒะตะฝะฝะพ', 'ะฑะตัะบะพะฝะตั‡ะฝะพ', 'ะฑะตะทัƒะผะฝะพ', 'ัะผะตั€ั‚ะตะปัŒะฝะพ', 'ะพัะปะตะฟะธั‚ะตะปัŒะฝะพ', 'ะฝะตัั‚ะตั€ะฟะธะผะพ', 'ะฑะปะตัั‚ัั‰ะต', 'ะณะตะฝะธะฐะปัŒะฝะพ', 'ัั€ะฐะฒะฝะธั‚ะตะปัŒะฝะพ', 'ะพั‚ะฝะพัะธั‚ะตะปัŒะฝะพ', 'ะฝะตะฒะตั€ะพัั‚ะฝะพ', 'ะตะดะฒะฐ', 'ะบะฐะฟะตะปัŒะบัƒ']: degree += 1 return degree # 47 # test that the current word is a particle def particles(t): particle = 0 for i, el in enumerate(t): flag = False if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'Q' and el[0] in ['ะถะต', 'ะฝัƒ', 'ะฟั€ัะผะพ', 'ัƒะถ', 'ะฒะพั‚', 'ั‚ะฐะผ', 'ั€ะฐะทะฒะต', 'ะปะธ', 'ะฒั€ะพะดะต', 'ะถ', 'ะดะฐะน', 'ั‚ะพะปัŒะบะพ', 'ะฒะตะดัŒ', 'ะดะฐะถะต', 'ะปะธัˆัŒ']: flag = True if el[0] in ['ั‚ะฐะบะธ', 'ะบะฐ', 'ั‚ะพ-ั‚ะพ']: flag = True if i + 1 < len(t): next_el = t[i + 1] if is_have_grammar(next_el): d_next_el = process_grammar(next_el) d_next_el = d_next_el if d_next_el is not None else {} if ((el[0] == 'ั‚ะฐะบ' and next_el[0] == 'ะธ') or (el[2] in ['ะบะฐะบะพะน', 'ะบัƒะดะฐ', 'ะณะดะต'] and next_el[0] == 'ั‚ะฐะผ' and d_next_el.get('pos') == 'Q') or (el[0] == 'ะบะฐะบ' and next_el[0] == 'ะตัั‚ัŒ') or (el[0] == 'ะทะฝะฐะน' and next_el[0] == 'ัะตะฑะต') or (el[0] == 'ะตะดะฒะฐ' and next_el[0] == 'ะฝะต') or (el[0] == 'ะบะฐะบ' and next_el[0] == 'ั€ะฐะท') or (el[0] == 'ั‡ัƒั‚ัŒ' and next_el[0] == 'ะฝะต') or (el[0] == 'ะฝะตั‚-ะฝะตั‚' and next_el[0] == 'ะธ')): flag = True if i + 2 < len(t): next_el = t[i + 1] next_next_el = t[i + 2] if ((el[0] == 'ะฝะต' and next_el[0] == 'ั‚ะพ' and next_next_el[0] in ['ั‡ั‚ะพะฑ', 'ั‡ั‚ะพะฑั‹']) or (el[0] == 'ะฝะต' and next_el[0] == 'ะธะฝะฐั‡ะต' and next_next_el[0] in ['ะบะฐะบ', 'ั‡ั‚ะพะฑั‹']) or (el[0] == 'ั‡ัƒั‚ัŒ' and next_el[0] == 'ะฑั‹ะปะพ' and next_next_el[0] == 'ะฝะต') or (el[0] == 'ั‚ะพะณะพ' and next_el[0] == 'ะธ' and next_next_el[0] in ['ะณะปัะดะธ', 'ะถะดะธ']) or (el[0] == 'ะฝะตั‚-ะฝะตั‚' and next_el[0] == 'ะดะฐ' and next_next_el[0] == 'ะธ') or (el[0] == 'ะฝะธ' and next_el[0] == 'ะฝะฐ' and next_next_el[0] == 'ะตัั‚ัŒ')): flag = True if flag: particle += 1 return particle # 48 # test that the current word is a numeral def numeral(t): num = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'M': num += 1 return num # 49 # test that the current word in or not in the list of top 100 most frequent nouns def top_100_nouns(t): top_nouns = 0 not_top = 0 with codecs.open('frequency_dict/frequent_nouns_top_100.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in read_lines: top_nouns += 1 else: not_top += 1 return top_nouns, not_top # 50 # test that the current word in or not in the list of top 1000 most frequent nouns (without the first top 100) def top_1000_nouns_minus_head(t): nouns_minus_head = 0 not_top = 0 with codecs.open('frequency_dict/frequent_nouns_minus_head_100.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in read_lines: nouns_minus_head += 1 else: not_top += 1 return nouns_minus_head, not_top # 51 # test that the current word in or not in the list of top 100 most frequent verbs def top_100_verbs(t): top_verbs = 0 not_top = 0 with codecs.open('frequency_dict/frequent_verbs_top_100.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in read_lines: top_verbs += 1 else: not_top += 1 return top_verbs, not_top # 52 # test that the current word in or not in the list of top 100 most frequent verbs (without 100 top verbs) def top_1000_verbs_minus_head(t): verbs_minus_head = 0 not_top = 0 with codecs.open('frequency_dict/frequent_verbs_minus_head_100.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] in read_lines: verbs_minus_head += 1 else: not_top += 1 return verbs_minus_head, not_top # 53 # test that the current not in the list of top 100 most frequent words def top_100(t): top_100 = 0 with codecs.open('frequency_dict/top_100_freq.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] not in read_lines: top_100 += 1 return top_100 # 54 # test that the current not in the list of top 300 most frequent words def top_300(t): top_300 = 0 with codecs.open('frequency_dict/top_300_freq.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] not in read_lines: top_300 += 1 return top_300 # 55 # test that the current not in the list of top 500 most frequent words def top_500(t): top_500 = 0 with codecs.open('frequency_dict/top_500_freq.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] not in read_lines: top_500 += 1 return top_500 # 56 # test that the current not in the list of top 10000 most frequent words def top_10000(t): top_10000 = 0 with codecs.open('frequency_dict/top_10000.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] not in read_lines: top_10000 += 1 return top_10000 # 57 # test that the current not in the list of top 5000 most frequent words def top_5000(t): top_5000 = 0 with codecs.open('frequency_dict/top_5000.txt', mode='r', encoding='utf-8') as f: read_lines = set([s.strip().lower() for s in f.readlines()]) for i, el in enumerate(t): if el[2] not in read_lines: top_5000 += 1 return top_5000 # 58 # test that the current word has a complex ending (like ะฟั€ะธะฑะพั€ะพัั‚ั€ะพ-ะตะฝะธะต) def complex_endings(t): end = 0 for el in t: lemma = el[2] if len(lemma) > 5: if lemma[-5:] in ['ัั‚ะฒะธะต', 'ะตะฝะฝั‹ะน', 'ะฒะฐะฝะธะต', 'ะปัŒะฝั‹ะน', 'ะฝะพัั‚ัŒ', 'ะตัะบะธะน', 'ะฝะตะฝะธะต', 'ัˆะตะฝะธะต', 'ะปะตะฝะธะต', 'ะพัั‰ะธะน', 'ะถะตะฝะธะต']: end += 1 elif lemma[-4:] in ['ะตะฝะธะต', 'ะฐะฝะธะต', 'ัŒะฝั‹ะน', 'ะพัั‚ัŒ', 'ะฝะฝั‹ะน', 'ะฐั†ะธั', 'ัะบะธะน', 'ั‚ะฒะธะต', 'ัั‰ะธะน']: end += 1 elif lemma[-3:] in ['ะฝะธะต', 'ะฝั‹ะน', 'ัั‚ัŒ', 'ั†ะธั', 'ะฒะธะต']: end += 1 elif lemma[-2:] in ['ะธะต', 'ั‹ะน', 'ะธั']: end += 1 return end # 59 # test that it is a finite verb of 1st or 2nd person def is_12person_verb(t): verb = 0 for i, el in enumerate(t): if is_have_grammar(el): d_el = process_grammar(el) if d_el.get('pos') == 'V' and (d_el.get('person') == '1' or d_el.get('person') == '2'): verb += 1 else: continue return verb
42.053544
124
0.469451
0
0
0
0
0
0
0
0
20,675
0.336354
69e1d274afce02fe0eb56c0874758437df337b90
134
py
Python
graphs/__init__.py
kateshostak/expander-lib
c1c7c0bec977fdc6492e4e08a1d1757783462c76
[ "MIT" ]
null
null
null
graphs/__init__.py
kateshostak/expander-lib
c1c7c0bec977fdc6492e4e08a1d1757783462c76
[ "MIT" ]
null
null
null
graphs/__init__.py
kateshostak/expander-lib
c1c7c0bec977fdc6492e4e08a1d1757783462c76
[ "MIT" ]
null
null
null
from .abstract_graph import AbstractGraph from .matrix_graph import MatrixGraph __all__ = [ "AbstractGraph", "MatrixGraph", ]
19.142857
41
0.753731
0
0
0
0
0
0
0
0
28
0.208955
69e260f9ca6210cf18c090c8a49bc65255c0f206
856
py
Python
03-datatypes/examples/07-tuples.py
luxwarp/python-course
d6ec4961ef43bd9d99954cffaea837220638e83f
[ "0BSD" ]
null
null
null
03-datatypes/examples/07-tuples.py
luxwarp/python-course
d6ec4961ef43bd9d99954cffaea837220638e83f
[ "0BSD" ]
null
null
null
03-datatypes/examples/07-tuples.py
luxwarp/python-course
d6ec4961ef43bd9d99954cffaea837220638e83f
[ "0BSD" ]
null
null
null
#!/usr/bin/env python3 # tuples is a type of list. # tuples is immutable. # the structure of a tuple: (1, "nice work", 2.3, [1,2,"hey"]) my_tuple = ("hey", 1, 2, "hey ho!", "hey", "hey") print("My tuple:", my_tuple) # to get a tuple value use it's index print("Second item in my_tuple:", my_tuple[1]) # to count how many times a values appears in a tuple: tuple.count(value) # returns 0 if no values exists. print("How many 'hey' in my_tuple:", my_tuple.count("hey")) # go get the index value of a tuple item. tuple.index(value) # if value does not exist you will get an error like "ValueError: tuple.index(x): x not in tuple" print("Index position of 'hey ho!' in my_tuple:", my_tuple.index("hey ho!")) # tuples are immutable so you cannot reassign a value like # my_tuple[2] = "wop wop" # TypeError: 'tuple' object does not support item assignment
35.666667
97
0.693925
0
0
0
0
0
0
0
0
721
0.84229
69e2f9e47e947283eba6f71f70baad174d0962cb
7,048
py
Python
retraction_synda.py
meteorologist15/synda_retraction
4a9174d2bc5d3573b5cdd39636380607120d586c
[ "CC0-1.0" ]
null
null
null
retraction_synda.py
meteorologist15/synda_retraction
4a9174d2bc5d3573b5cdd39636380607120d586c
[ "CC0-1.0" ]
null
null
null
retraction_synda.py
meteorologist15/synda_retraction
4a9174d2bc5d3573b5cdd39636380607120d586c
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/env python3 import subprocess import requests import json import os import re import argparse import logging import csv import shutil retracted_exps = "retracted_exps.csv" #Generic info list from file here. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') handle_api = "https://hdl.handle.net/api/handles/" def get_tracking_ids(pid): # All pid's begin with 'hdl:'. Start at index 4 for api pid = pid[4:] web_output = requests.get(handle_api + pid) json_output = web_output.json() tracking_ids = json_output['values'][4]['data']['value'] # A semicolon-separated string is returned return tracking_ids def set_synda_path(): synda_home = "/path/to/synda/sdt" synda_execdir = synda_home + "/bin:" if not os.getenv("ST_HOME", default=0): os.environ["ST_HOME"] = synda_home if not synda_execdir in os.getenv("PATH"): os.environ["PATH"] = synda_execdir + os.getenv("PATH") def write_pid_json(retraction_list): pid_file = "pid_retractions.csv" success_count = 0 failure_count = 0 with open(pid_file, 'ab') as f: for line in retraction_list: # Dump metadata for each dataset using Synda to retrieve the PID meta_cmd = ["synda", "dump", line.rstrip("\n")] meta_dump = subprocess.run(meta_cmd, stdout=subprocess.PIPE) meta_json = meta_dump.stdout.decode("utf-8") if len(meta_json) > 0: meta_json = json.loads(meta_json) try: pid_output = meta_json[0]["pid"] except (IndexError, KeyError) as err: logging.error("Problems reading JSON. Skipping.\n%s\n" % err) failure_count += 1 continue tracking_ids = get_tracking_ids(pid_output) # Write the dataset PID, dataset ID, and semicolon separated tracking_id's to file final_output_line = "%s,%s,%s\n" % (pid_output, line.replace("\n", ""), tracking_ids) f.write(bytes(final_output_line, "UTF-8")) success_count += 1 logging.info("%s/%s dataset pid's written" % (str(success_count), str(len(retraction_list)))) else: logging.warning("The dataset %s was not processed. Did not find metadata dump from Synda. Skipping." % line) class Retractor(object): def __init__(self, institutions=None, project=None): self.project = "CMIP6" if project is None else ','.join(project) def clean_list(self, synda_search): # Some preprocess cleaning here # for i in range(len(synda_search)): synda_search[i] = re.search('[A-Z].*', synda_search[i]).group() + "\n" return synda_search def finalize_list(self, search_command): search_proc = subprocess.run(search_command, stdout=subprocess.PIPE) search_output = search_proc.stdout.decode("utf-8").splitlines() retract_list = self.clean_list(search_output) # Without the extra text in the beginning return retract_list def get_processed_retractions(self): # This is if you have run the script before. pid_retractions.csv is an already completed set of retractions, i.e. already "processed". Read this into memory for eventual comparison with new retraction list. pid_retracted_file = "pid_retractions.csv" already_processed = [] if os.path.exists(pid_retracted_file): with open(pid_retracted_file, 'r') as f: already_processed = f.readlines() return already_processed def refine_list(self, retraction_list): # Compare with those already processed from beforehand/previous as retracted. This cancels out some redundancy. processed_list = self.get_processed_retractions() for line in processed_list: comparison = re.search(',(.*),', line).group(1) + "\n" if comparison in retraction_list: try: retraction_list.remove(comparison) except ValueError as err: logging.warning("Something went terribly wrong. Skipping.") continue return retraction_list def get_retraction_list(self): main_list = [] memory_list = [] # Read generic retraction info into memory try: with open(retracted_exps, newline='') as f: esgf_reader = csv.reader(f, quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in esgf_reader: memory_list.append(row) except OSError as e: logging.error("The file %s doesn't exist. Quitting." % retracted_exps) raise # Use Synda to search by experiment_id, refine the list, and add continually add retractions to main list for sublist in memory_list: search_cmd = ["synda", "search", "project=CMIP6", "retracted=true", "experiment_id=%s" % sublist[0], "-l", "8999"] if sublist[2] == 'no_overflow': logging.info("Getting data from experiment %s" % sublist[0]) refined_list = self.refine_list(self.finalize_list(search_cmd)) if len(refined_list) > 0: main_list.extend(refined_list) logging.info("Added %s entries from this experiment. Total to add: %s" % (str(len(refined_list)), str(len(main_list)))) else: logging.info("No entries to add for this experiment") # Execute searches using variant label instead of simply experiment_id if retractions >= 9000 else: logging.info("Getting data from experiment %s. Over 9000 retractions." % sublist[0]) ensemble_dict = json.loads(sublist[2].replace('|', ',')) for variant_label in ensemble_dict.keys(): logging.info("Getting data from variant label (ensemble) %s" % variant_label) search_cmd = ["synda", "search", "project=CMIP6", "retracted=true", "experiment_id=%s" % sublist[0], "variant_label=%s" % variant_label, "-l", "8999"] refined_list = self.refine_list(self.finalize_list(search_cmd)) if len(refined_list) > 0: main_list.extend(refined_list) logging.info("Added %s entries from this variant_label. Total to add: %s" % (str(len(refined_list)), str(len(main_list)))) else: logging.info("No entries to add for this variant_label") return main_list # These are the retractions we care to add if __name__ == "__main__": set_synda_path() logging.info("Creating PID backup...") shutil.copy2("pid_retractions.csv", "pid_retractions.csv.prev") ret = Retractor() myretractlist = ret.get_retraction_list() write_pid_json(myretractlist)
36.518135
214
0.614784
4,355
0.617906
0
0
0
0
0
0
2,125
0.301504
69e335c70218134a69c091bf1b6b675a74eec632
9,485
py
Python
tests/integration/cqlengine/management/test_management.py
fatelei/python-driver
3bddef6185f2691e1713dfe51d1fa26d1555724c
[ "Apache-2.0" ]
null
null
null
tests/integration/cqlengine/management/test_management.py
fatelei/python-driver
3bddef6185f2691e1713dfe51d1fa26d1555724c
[ "Apache-2.0" ]
null
null
null
tests/integration/cqlengine/management/test_management.py
fatelei/python-driver
3bddef6185f2691e1713dfe51d1fa26d1555724c
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import mock import warnings from cassandra.cqlengine import CACHING_ALL, CACHING_NONE from cassandra.cqlengine.connection import get_session, get_cluster from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine import management from cassandra.cqlengine.management import _get_non_pk_field_names, _get_table_metadata, sync_table, drop_table from cassandra.cqlengine.models import Model from cassandra.cqlengine import columns from tests.integration import CASSANDRA_VERSION, PROTOCOL_VERSION from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine.query.test_queryset import TestModel class KeyspaceManagementTest(BaseCassEngTestCase): def test_create_drop_succeeeds(self): cluster = get_cluster() keyspace_ss = 'test_ks_ss' self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) management.create_keyspace_simple(keyspace_ss, 2) self.assertIn(keyspace_ss, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_ss) self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) keyspace_nts = 'test_ks_nts' self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) management.create_keyspace_network_topology(keyspace_nts, {'dc1': 1}) self.assertIn(keyspace_nts, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_nts) self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) class DropTableTest(BaseCassEngTestCase): def test_multiple_deletes_dont_fail(self): sync_table(TestModel) drop_table(TestModel) drop_table(TestModel) class LowercaseKeyModel(Model): first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) some_data = columns.Text() class CapitalizedKeyModel(Model): firstKey = columns.Integer(primary_key=True) secondKey = columns.Integer(primary_key=True) someData = columns.Text() class PrimaryKeysOnlyModel(Model): __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} first_ey = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) class CapitalizedKeyTest(BaseCassEngTestCase): def test_table_definition(self): """ Tests that creating a table with capitalized column names succeeds """ sync_table(LowercaseKeyModel) sync_table(CapitalizedKeyModel) drop_table(LowercaseKeyModel) drop_table(CapitalizedKeyModel) class FirstModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() class SecondModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() fourth_key = columns.Text() class ThirdModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # removed fourth key, but it should stay in the DB blah = columns.Map(columns.Text, columns.Text) class FourthModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # removed fourth key, but it should stay in the DB renamed = columns.Map(columns.Text, columns.Text, db_field='blah') class AddColumnTest(BaseCassEngTestCase): def setUp(self): drop_table(FirstModel) def test_add_column(self): sync_table(FirstModel) fields = _get_non_pk_field_names(_get_table_metadata(FirstModel)) # this should contain the second key self.assertEqual(len(fields), 2) # get schema sync_table(SecondModel) fields = _get_non_pk_field_names(_get_table_metadata(FirstModel)) self.assertEqual(len(fields), 3) sync_table(ThirdModel) fields = _get_non_pk_field_names(_get_table_metadata(FirstModel)) self.assertEqual(len(fields), 4) sync_table(FourthModel) fields = _get_non_pk_field_names(_get_table_metadata(FirstModel)) self.assertEqual(len(fields), 4) class ModelWithTableProperties(Model): __options__ = {'bloom_filter_fp_chance': '0.76328', 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', 'gc_grace_seconds': '2063', 'read_repair_chance': '0.17985', 'dclocal_read_repair_chance': '0.50811'} key = columns.UUID(primary_key=True) class TablePropertiesTests(BaseCassEngTestCase): def setUp(self): drop_table(ModelWithTableProperties) def test_set_table_properties(self): sync_table(ModelWithTableProperties) expected = {'bloom_filter_fp_chance': 0.76328, 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', 'gc_grace_seconds': 2063, 'read_repair_chance': 0.17985, # For some reason 'dclocal_read_repair_chance' in CQL is called # just 'local_read_repair_chance' in the schema table. # Source: https://issues.apache.org/jira/browse/CASSANDRA-6717 # TODO: due to a bug in the native driver i'm not seeing the local read repair chance show up # 'local_read_repair_chance': 0.50811, } options = management._get_table_metadata(ModelWithTableProperties).options self.assertEqual(dict([(k, options.get(k)) for k in expected.keys()]), expected) def test_table_property_update(self): ModelWithTableProperties.__options__['bloom_filter_fp_chance'] = 0.66778 ModelWithTableProperties.__options__['comment'] = 'xirAkRWZVVvsmzRvXamiEcQkshkUIDINVJZgLYSdnGHweiBrAiJdLJkVohdRy' ModelWithTableProperties.__options__['gc_grace_seconds'] = 96362 ModelWithTableProperties.__options__['read_repair_chance'] = 0.2989 ModelWithTableProperties.__options__['dclocal_read_repair_chance'] = 0.12732 sync_table(ModelWithTableProperties) table_options = management._get_table_metadata(ModelWithTableProperties).options self.assertDictContainsSubset(ModelWithTableProperties.__options__, table_options) def test_bogus_option_update(self): sync_table(ModelWithTableProperties) option = 'no way will this ever be an option' try: ModelWithTableProperties.__options__[option] = 'what was I thinking?' self.assertRaisesRegexp(KeyError, "Invalid table option.*%s.*" % option, sync_table, ModelWithTableProperties) finally: ModelWithTableProperties.__options__.pop(option, None) class SyncTableTests(BaseCassEngTestCase): def setUp(self): drop_table(PrimaryKeysOnlyModel) def test_sync_table_works_with_primary_keys_only_tables(self): sync_table(PrimaryKeysOnlyModel) # blows up with DoesNotExist if table does not exist table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('LeveledCompactionStrategy', table_meta.as_cql_query()) PrimaryKeysOnlyModel.__options__['compaction']['class'] = 'SizeTieredCompactionStrategy' sync_table(PrimaryKeysOnlyModel) table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('SizeTieredCompactionStrategy', table_meta.as_cql_query()) class NonModelFailureTest(BaseCassEngTestCase): class FakeModel(object): pass def test_failure(self): with self.assertRaises(CQLEngineException): sync_table(self.FakeModel) class StaticColumnTests(BaseCassEngTestCase): def test_static_columns(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest("Native protocol 2+ required, currently using: {0}".format(PROTOCOL_VERSION)) class StaticModel(Model): id = columns.Integer(primary_key=True) c = columns.Integer(primary_key=True) name = columns.Text(static=True) drop_table(StaticModel) session = get_session() with mock.patch.object(session, "execute", wraps=session.execute) as m: sync_table(StaticModel) self.assertGreater(m.call_count, 0) statement = m.call_args[0][0].query_string self.assertIn('"name" text static', statement) # if we sync again, we should not apply an alter w/ a static sync_table(StaticModel) with mock.patch.object(session, "execute", wraps=session.execute) as m2: sync_table(StaticModel) self.assertEqual(len(m2.call_args_list), 0)
34.616788
122
0.714391
8,129
0.857037
0
0
0
0
0
0
2,076
0.218872
69e3ad1eebd1e1fccdf1e001090572086c5c45ba
366
py
Python
theboss/network_simulation_strategy/network_simulation_strategy.py
Tomev/BoSS
45db090345650741c85b39b47cbc7b391d6daa33
[ "Apache-2.0" ]
null
null
null
theboss/network_simulation_strategy/network_simulation_strategy.py
Tomev/BoSS
45db090345650741c85b39b47cbc7b391d6daa33
[ "Apache-2.0" ]
4
2020-07-10T00:28:43.000Z
2020-10-12T11:51:38.000Z
theboss/network_simulation_strategy/network_simulation_strategy.py
Tomev/BoSS
45db090345650741c85b39b47cbc7b391d6daa33
[ "Apache-2.0" ]
1
2020-09-12T15:35:09.000Z
2020-09-12T15:35:09.000Z
__author__ = "Tomasz Rybotycki" import abc from numpy import ndarray class NetworkSimulationStrategy(abc.ABC): @classmethod def __subclasshook__(cls, subclass): return hasattr(subclass, "simulate") and callable(subclass.simulate) @abc.abstractmethod def simulate(self, input_state: ndarray) -> ndarray: raise NotImplementedError
22.875
76
0.737705
292
0.797814
0
0
240
0.655738
0
0
28
0.076503
69e3ea4c1c7c901fc078c30d615b40492cfe71fd
769
py
Python
ecommerce/core/migrations/0020_auto_20200923_1948.py
berrondo/ecommerce
daa0fa3c336d7e1e9816cc187f858bab7122fb1b
[ "MIT" ]
1
2020-09-04T02:23:02.000Z
2020-09-04T02:23:02.000Z
ecommerce/core/migrations/0020_auto_20200923_1948.py
berrondo/ecommerce
daa0fa3c336d7e1e9816cc187f858bab7122fb1b
[ "MIT" ]
null
null
null
ecommerce/core/migrations/0020_auto_20200923_1948.py
berrondo/ecommerce
daa0fa3c336d7e1e9816cc187f858bab7122fb1b
[ "MIT" ]
null
null
null
# Generated by Django 3.1.1 on 2020-09-23 19:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0019_auto_20200923_1942'), ] operations = [ migrations.AlterField( model_name='orderitem', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='core.order', verbose_name='pedido'), ), migrations.AlterField( model_name='orderitem', name='product', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='order_item', to='core.product', verbose_name='produto'), ), ]
30.76
151
0.642393
643
0.836151
0
0
0
0
0
0
178
0.231469
69e536b2f665710fad652d1507cbb967f6b032a2
1,989
py
Python
framework.py
w1rtp/USMAnywhereAPI
d239fde894e085cfe5350800225ebe88297f922f
[ "MIT" ]
3
2019-02-04T18:15:00.000Z
2021-06-22T21:03:22.000Z
framework.py
w1rtp/USMAnywhereAPI
d239fde894e085cfe5350800225ebe88297f922f
[ "MIT" ]
1
2018-10-04T21:51:50.000Z
2018-10-06T18:17:00.000Z
framework.py
w1rtp/USMAnywhereAPI
d239fde894e085cfe5350800225ebe88297f922f
[ "MIT" ]
2
2019-12-23T16:03:01.000Z
2022-03-17T01:13:17.000Z
#!/usr/bin/env python """ Nicholas' Example API code for interacting with Alienvault API. This is just Example code written by NMA.IO. There isn't really much you can do with the API just yet, so this will be a work in progress. Grab your API key here: https://www.alienvault.com/documentation/usm-anywhere/api/alienvault-api.htm?cshid=1182 That said, you could use this to write an alerter bot. * Note, this isn't an SDK, just some example code to get people started... """ # import json # uncomment if you want pretty printing. import base64 import requests URL = "alienvault.cloud/api/2.0" HOST = "" # put your subdomain here. def Auth(apiuser, apikey): """Our Authentication Code. :params apiuser :params apikey :returns oauth_token """ headers = {"Authorization": "Basic {}".format(base64.b64encode("%s:%s" % (apiuser, apikey)))} r = requests.post("https://{}.{}/oauth/token?grant_type=client_credentials".format(HOST, URL), headers=headers) if r.status_code is 200: return r.json()["access_token"] else: print("Authentication failed. Check username/Password") exit(1) def Alarms(token): """Pull Alarms from the API Console.""" headers = {"Authorization": "Bearer {}".format(token)} r = requests.get("https://{}.{}/alarms/?page=1&size=20&suppressed=false&status=open".format(HOST, URL), headers=headers) if r.status_code is not 200: print("Something went wrong. \n{}".format(r.content)) exit(1) else: return (r.json()) def Events(): """Nothing yet.""" pass if __name__ == "__main__": print("Simple API Integration with Alienvault USM Anywhere - 2018 NMA.IO") token = Auth("username", "password") jdata = Alarms(token) for item in jdata["_embedded"]["alarms"]: # print(json.dumps(item, indent=2)) # uncomment if you want a pretty version of the whole block. print(item["rule_method"] + ": " + " ".join(item["alarm_sources"]))
31.078125
124
0.667672
0
0
0
0
0
0
0
0
1,269
0.638009
69e53fa5b831cecebc7667ff2b84745654c3a1c0
2,768
py
Python
Facility/Loader/loader_base.py
EVOLVED-5G/ELCM
07d07a114b667e8c6915ee3ef125dd4864dd2247
[ "Apache-2.0" ]
null
null
null
Facility/Loader/loader_base.py
EVOLVED-5G/ELCM
07d07a114b667e8c6915ee3ef125dd4864dd2247
[ "Apache-2.0" ]
null
null
null
Facility/Loader/loader_base.py
EVOLVED-5G/ELCM
07d07a114b667e8c6915ee3ef125dd4864dd2247
[ "Apache-2.0" ]
null
null
null
import yaml from Helper import Level from typing import List, Dict from os.path import join from ..action_information import ActionInformation class Loader: @classmethod def EnsureFolder(cls, path: str) -> [(Level, str)]: from Helper import IO validation = [] if not IO.EnsureFolder(path): validation.append((Level.INFO, f'Auto-generated folder: {path}')) return validation @classmethod def LoadFolder(cls, path: str, kind: str) -> [(Level, str)]: from Helper import IO ignored = [] validation = [] for file in IO.ListFiles(path): if file.endswith('.yml'): filePath = join(path, file) try: validation.append((Level.INFO, f'Loading {kind}: {file}')) data, v = cls.LoadFile(filePath) validation.extend(v) validation.extend(cls.ProcessData(data)) except Exception as e: validation.append((Level.ERROR, f"Exception loading {kind} file '{filePath}': {e}")) else: ignored.append(file) if len(ignored) != 0: validation.append((Level.WARNING, f'Ignored the following files on the {kind}s folder: {(", ".join(ignored))}')) return validation @classmethod def LoadFile(cls, path: str) -> ((Dict | None), [(Level, str)]): try: with open(path, 'r', encoding='utf-8') as file: raw = yaml.safe_load(file) return raw, [] except Exception as e: return None, [(Level.ERROR, f"Unable to load file '{path}': {e}")] @classmethod def GetActionList(cls, data: List[Dict]) -> ([ActionInformation], [(Level, str)]): actionList = [] validation = [] for action in data: actionInfo = ActionInformation.FromMapping(action) if actionInfo is not None: actionList.append(actionInfo) else: validation.append((Level.ERROR, f'Action not correctly defined for element (data="{action}").')) actionList.append(ActionInformation.MessageAction( 'ERROR', f'Incorrect Action (data="{action}")' )) if len(actionList) == 0: validation.append((Level.WARNING, 'No actions defined')) else: for action in actionList: validation.append((Level.DEBUG, str(action))) return actionList, validation @classmethod def ProcessData(cls, data: Dict) -> [(Level, str)]: raise NotImplementedError @classmethod def Clear(cls): raise NotImplementedError
35.487179
112
0.556358
2,622
0.947254
0
0
2,574
0.929913
0
0
361
0.130419
69e67f189f337a3cb0820bec91f37c72cf451cb4
2,140
py
Python
timebox/tests/test_timebox_pandas.py
BrianKopp/timebox
302c7f65fa0a2e35aab2412173b9081a1a3c324c
[ "MIT" ]
1
2018-07-09T18:42:57.000Z
2018-07-09T18:42:57.000Z
timebox/tests/test_timebox_pandas.py
BrianKopp/timebox
302c7f65fa0a2e35aab2412173b9081a1a3c324c
[ "MIT" ]
null
null
null
timebox/tests/test_timebox_pandas.py
BrianKopp/timebox
302c7f65fa0a2e35aab2412173b9081a1a3c324c
[ "MIT" ]
null
null
null
from timebox.timebox import TimeBox from timebox.utils.exceptions import InvalidPandasIndexError import pandas as pd import numpy as np import unittest import os import logging class TestTimeBoxPandas(unittest.TestCase): def test_save_pandas(self): file_name = 'save_pandas.npb' df = pd.read_csv('timebox/tests/data/ETH-USD_combined_utc.csv', index_col=0) tb = TimeBox.save_pandas(df, file_name) self.assertTrue(os.path.exists(file_name)) tb_read = TimeBox(file_name) df2 = tb_read.to_pandas() df_columns = list(df) df_columns.sort() df2_columns = list(df2) df2_columns.sort() self.assertListEqual(df_columns, df2_columns) os.remove(file_name) return def test_pandas_errors(self): df = pd.DataFrame.from_dict( { 'value_1': np.array([0, 1, 2], dtype=np.uint8) }, orient='columns' ) with self.assertRaises(InvalidPandasIndexError): TimeBox.save_pandas(df, 'not_going_to_save.npb') return def test_io_pandas(self): file_name = 'save_pandas.npb' df = pd.read_csv('timebox/tests/data/test1.csv').set_index('date') logging.debug('Starting test_io_pandas with df\n{}'.format(df)) tb = TimeBox.save_pandas(df, file_name) tb_read = TimeBox(file_name) df2 = tb_read.to_pandas() self.assertListEqual(list(df.columns.sort_values()), list(df2.columns.sort_values())) df = df.sort_index() # ensure index is same for i in range(0, len(df.index)): self.assertEqual(pd.to_datetime(df.index[i]), pd.to_datetime(df2.index[i])) # ensure each value is the same columns = df.columns for c in columns: logging.debug('Testing column: {}'.format(c)) logging.debug('Original frame:{}'.format(df[c])) logging.debug('TB frame:{}'.format(df2[c])) self.assertEqual(df[c].sum(), df2[c].sum()) os.remove(file_name) return if __name__ == '__main__': unittest.main()
31.940299
93
0.621963
1,912
0.893458
0
0
0
0
0
0
308
0.143925
69e74affdb03ba88f022aa14d7c8af457ff4e082
2,143
py
Python
flaskapp/utils/logs.py
argrecsys/decide-madrid-chatbot
8d44932f15e49902215e17982e5c1f4ffaa7a38b
[ "Apache-2.0" ]
4
2022-01-11T21:57:48.000Z
2022-01-13T21:52:28.000Z
flaskapp/utils/logs.py
argrecsys/decide-madrid-chatbot
8d44932f15e49902215e17982e5c1f4ffaa7a38b
[ "Apache-2.0" ]
null
null
null
flaskapp/utils/logs.py
argrecsys/decide-madrid-chatbot
8d44932f15e49902215e17982e5c1f4ffaa7a38b
[ "Apache-2.0" ]
null
null
null
from typing import Any from flaskapp.models import Activities, Logs, LogsToActivities, db from sqlalchemy.sql.expression import desc, func """ Este modulo contiene funciones para escribir y leer los logs desde el chatbot """ MAX_LOGS_PER_QUERY = 5 MAX_STR_SIZE_LOGS = 128 def write_log( chatid: int, intent: str, activity: set, ts: Any, input: str, response: str, observaciones: str, id: int = -1, withargs: bool = False ): if id == -1: try: idlog = db.session.query(func.max(Logs.id)).scalar() + 1 except: idlog = 1 db.session.add( Logs( id=idlog, chatid=chatid, intent=intent, input=input, ts=ts, response=response, obs=observaciones, withargs=withargs ) ) else: db.session.add( Logs( chatid=chatid, intent=intent, input=input, ts=ts, response=response, obs=observaciones, id=id, withargs=withargs ) ) db.session.commit() print("ACTITVITIES TO LOG: " + str(activity)) for act in activity: if act == intent: continue idactivity = None try: idactivity = Activities.query.filter_by(activity=act).first().id except: db.session.add( Activities( activity=act ) ) db.session.commit() idactivity = db.session.query(func.max(Activities.id)).scalar() db.session.add( LogsToActivities(idlog=idlog, idactivity=idactivity) ) db.session.commit() def get_logs(limit=100): query = Logs.query.order_by(desc(Logs.ts)).limit(limit) return query.all(), query def writer(x: Logs): rep = repr(x) if len(rep) > MAX_STR_SIZE_LOGS: return "{}...".format(rep[0:MAX_STR_SIZE_LOGS]) else: return rep
24.352273
77
0.514232
0
0
0
0
0
0
0
0
114
0.053196
69e7b4ccf59b1c05b1102c31382c3994419c2af7
1,233
py
Python
WEEKS/CD_Sata-Structures/_RESOURCES/DS-n-Algos/hashes/luhn.py
webdevhub42/Lambda
b04b84fb5b82fe7c8b12680149e25ae0d27a0960
[ "MIT" ]
13
2021-03-11T00:25:22.000Z
2022-03-19T00:19:23.000Z
hashes/luhn.py
randomprassanna/Python
bc09ba9abfa220c893b23969a4b8de05f5ced1e1
[ "MIT" ]
279
2020-02-12T20:51:09.000Z
2021-07-20T11:25:19.000Z
hashes/luhn.py
randomprassanna/Python
bc09ba9abfa220c893b23969a4b8de05f5ced1e1
[ "MIT" ]
12
2021-04-26T19:43:01.000Z
2022-01-31T08:36:29.000Z
""" Luhn Algorithm """ from typing import List def is_luhn(string: str) -> bool: """ Perform Luhn validation on input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713, ... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718, ... 79927398719] >>> test_cases = list(map(str, test_cases)) >>> list(map(is_luhn, test_cases)) [False, False, False, True, False, False, False, False, False, False] """ check_digit: int _vector: List[str] = list(string) __vector, check_digit = _vector[:-1], int(_vector[-1]) vector: List[int] = [*map(int, __vector)] vector.reverse() for idx, i in enumerate(vector): if idx & 1 == 0: doubled: int = vector[idx] * 2 if doubled > 9: doubled -= 9 check_digit += doubled else: check_digit += i if (check_digit) % 10 == 0: return True return False if __name__ == "__main__": import doctest doctest.testmod() assert is_luhn("79927398713")
26.234043
76
0.596918
0
0
0
0
0
0
0
0
587
0.476075
69e81c899520bdfc0aa12c011c27b56eb5e31e55
2,477
py
Python
gen_files.py
qbosen/leetcode_file_generator
594d7bb1e5ac5cb3100ddbaecc3f8359c17dbbb8
[ "MIT" ]
null
null
null
gen_files.py
qbosen/leetcode_file_generator
594d7bb1e5ac5cb3100ddbaecc3f8359c17dbbb8
[ "MIT" ]
null
null
null
gen_files.py
qbosen/leetcode_file_generator
594d7bb1e5ac5cb3100ddbaecc3f8359c17dbbb8
[ "MIT" ]
null
null
null
# coding=utf-8 # /usr/bin/python gen_files.py 100 import os import sys import time from settings import * from settings_advanced import * try: import cPickle as pickle except ImportError: import pickle from content_parser import DescriptionParser from content_parser_advance import AdvancedDescriptionParser def main(): num = sys.argv[1] if len(sys.argv) > 1 else '11' level = sys.argv[2] if len(sys.argv) > 2 else None level = int(level) if level else default_format if not num: return info = get_info(num) package_path = make_dir(info) en_level = get_level(info) date = time.strftime('%Y/%m/%d', time.localtime()) if not enable_advance: dp = DescriptionParser().parse(info['path']) md = md_pattern.format(title=dp.title, content=dp.content, date=date, **info) solution = class_pattern.format(en_level=en_level, author=author, date=date, **info) test = test_class_pattern.format(en_level=en_level, author=author, date=date, **info) else: dp = AdvancedDescriptionParser().parse(info['path'], level) dp_data = dp.data # print dp_data md = ad_md_pattern.format(date=date, **dp_data) solution = ad_class_pattern.format(en_level=en_level, author=author, date=date, **dp_data) test = ad_test_class_pattern.format(en_level=en_level, author=author, date=date, **dp_data) generate_file(package_path, 'README.md', md) file_suffix = language_map[language] if language in language_map else '.java' generate_file(package_path, 'Solution%s' % file_suffix, solution) generate_file(package_path, 'SolutionTest%s' % file_suffix, test) def get_info(num): dic = pickle.load(open('dumps.txt', 'r')) return dic[num] if num in dic else {} def generate_file(base_path, file_name, content): full_path = os.path.join(base_path, file_name) with open(full_path, 'w') as f: f.write(content.encode('utf-8')) print 'create file: %s' % full_path def get_level(info_dict): ch_level = info_dict['level'] level_map = {'็ฎ€ๅ•': 'easy', 'ไธญ็ญ‰': 'medium', 'ๅ›ฐ้šพ': 'hard'} return level_map[ch_level] if ch_level in level_map else 'default' def make_dir(info_dict): level = get_level(info_dict) base_path = os.path.join(src_path, level, 'q{:0>3s}'.format(info_dict['index'])) if not os.path.exists(base_path): os.makedirs(base_path) return base_path if __name__ == '__main__': main()
31.75641
99
0.686314
0
0
0
0
0
0
0
0
263
0.105665
69e933da38595f381a40d626b00d56311127794d
1,287
py
Python
interface/exemplos1/05.py
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
interface/exemplos1/05.py
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
interface/exemplos1/05.py
ell3a/estudos-python
09808a462aa3e73ad433501acb11f62217548af8
[ "MIT" ]
null
null
null
from tkinter import * import tkFileDialog root = Tk() menubar = Menu(root) root.config(menu=menubar) root.title('Tk Menu') root.geometry('150x150') filemenu = Menu(menubar) filemenu2 = Menu(menubar) filemenu3 = Menu(menubar) menubar.add_cascade(label='Arquivo', menu=filemenu) menubar.add_cascade(label='Cores', menu=filemenu2) menubar.add_cascade(label='Ajuda', menu=filemenu3) def Open(): tkFileDialog.askopenfilename() def Save(): tkFileDialog.asksaveasfilename() def Quit(): root.destroy() def ColorBlue(): Text(background='blue').pack() def ColorRed(): Text(background='red').pack() def ColorBlack(): Text(background='black').pack() def Help(): text = Text(root) text.pack(); text.insert('insert', 'Ao clicar no botรฃo da\n' 'respectiva cor, o fundo da tela\n' 'aparecerรก na cor escolhida.') filemenu.add_command(label='Abrir...', command=Open) filemenu.add_command(label='Salvar como...', command=Save) filemenu.add_separator() filemenu.add_command(label='Sair', command=Quit) filemenu2.add_command(label='Azul', command=ColorBlue) filemenu2.add_command(label='Vermelho', command=ColorRed) filemenu2.add_command(label='Preto', command=ColorBlack) filemenu3.add_command(label='Ajuda', command=Help) root.mainloop()
33
61
0.724165
0
0
0
0
0
0
0
0
220
0.170675
69e9b7f3b724fc8a84cb33e494ceb8bad87452a5
349
py
Python
public/models.py
level09/yooo
deb8fbdd2d2114a9189e35ee5ab6014876f99438
[ "MIT" ]
6
2015-02-20T17:24:46.000Z
2020-05-21T18:23:25.000Z
public/models.py
level09/yooo
deb8fbdd2d2114a9189e35ee5ab6014876f99438
[ "MIT" ]
null
null
null
public/models.py
level09/yooo
deb8fbdd2d2114a9189e35ee5ab6014876f99438
[ "MIT" ]
null
null
null
from extensions import db import datetime import json class Link(db.Document): lid = db.SequenceField(unique=True) longUrl = db.StringField() shortUrl = db.StringField() date_submitted = db.DateTimeField(default=datetime.datetime.now) usage = db.IntField(default=0) def __unicode__(self): return '%s' % self.longUrl
26.846154
68
0.710602
294
0.842407
0
0
0
0
0
0
4
0.011461
69ea5b5cea2f3bde949a1ce25fc96a75ca9f7638
6,132
py
Python
script/python/lib/exhaust_generation/exhaustive_tpls.py
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
script/python/lib/exhaust_generation/exhaustive_tpls.py
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
null
null
null
script/python/lib/exhaust_generation/exhaustive_tpls.py
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
null
null
null
#! /usr/bin/env python # -*- coding: iso-8859-15 -*- ############################################################################## # Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II # Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI # # Distributed under the Boost Software License, Version 1.0 # See accompanying file LICENSE.txt or copy at # http://www.boost.org/LICENSE_1_0.txt ############################################################################## """generation of an exhaustive test unit """ __author__ = "Lapreste Jean-thierry (lapreste@univ-bpclermont.fr)" __version__ = "$Revision: 1.0 $" __date__ = "$Date: 2011 $" __copyright__ = "Lapreste Jean-thierry" __license__ = "Boost Software License, Version 1.0" class Exhaustive_data(object) : Tpl = { 'scalar' : { }, 'simd' : { 'global_header_txt' : '\n'.join([ '////////////////////////////////////////////////////////////////////////', '// exhaustive test in simd mode for functor $prefix$::$name$', '////////////////////////////////////////////////////////////////////////', '#include <nt2/include/functions/$name$.hpp>', '', '#include <nt2/include/functions/iround.hpp>', '#include <nt2/include/functions/load.hpp>', '#include <nt2/include/functions/min.hpp>', '#include <nt2/include/functions/splat.hpp>', '#include <nt2/include/functions/successor.hpp>', '#include <nt2/include/functions/ulpdist.hpp>', '', '#include <nt2/include/constants/real.hpp>', '', '#include <nt2/sdk/meta/cardinal_of.hpp>', '#include <nt2/sdk/meta/as_integer.hpp>', '', '#include <iostream>', '', 'typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;', ]), 'typ_repfunc_txt' : '\n'.join([ 'static inline ', 'typename nt2::meta::call<nt2::tag::$name$_($typ$)>::type', 'repfunc(const $typ$ & a0)', '{', ' return $repfunc$;', '}', ]), 'test_func_forwarding_txt' : '\n'.join([ 'template <class T>', 'void exhaust_test_$name$(const T& mini,const T& maxi);' ]), 'test_func_call_txt' : '\n'.join([ ' exhaust_test_$name$($mini$,$maxi$);' ]), 'main_beg_txt' : '\n'.join([ 'int main(){', '{', ]), 'main_end_txt' : '\n'.join([ ' return 0;', '}', '', ]), 'test_func_typ_txt' : '\n'.join([ 'template <>', 'void exhaust_test_$name$<$typ$>(const $typ$& mini,const $typ$& maxi)', ' {', ' typedef boost::simd::native<$typ$,ext_t> n_t;', ' typedef typename nt2::meta::as_integer<n_t>::type in_t;', ' typedef typename nt2::meta::call<nt2::tag::$name$_($typ$)>::type r_t;', ' typedef typename nt2::meta::call<nt2::tag::$name$_(n_t)>::type r_t;', ' $typ$ mini = $mini$;', ' $typ$ maxi = $maxi$;', ' const nt2::uint32_t N = nt2::meta::cardinal_of<n_t>::value;', ' const in_t vN = nt2::splat<in_t>(N);', ' const nt2::uint32_t M = 10;', ' nt2::uint32_t histo[M+1];', ' for(nt2::uint32_t i = 0; i < M; i++) histo[i] = 0;', ' float a[N];', ' a[0] = mini;', ' for(nt2::uint32_t i = 1; i < N; i++)', ' a[i] = nt2::successor(a[i-1], 1);', ' n_t a0 = nt2::load<n_t>(&a[0],0);', ' nt2::uint32_t k = 0,j = 0;', ' std::cout << "a line of points to wait for... be patient!" << std::endl;', ' for(; a0[N-1] < maxi; a0 = nt2::successor(a0, vN))', ' {', ' n_t z = nt2::$name$(a0);', ' for(nt2::uint32_t i = 0; i < N; i++)', ' {', ' float v = repfunc(a0[i]);', ' float sz = z[i];', ' ++histo[nt2::min(M, nt2::iround(2*nt2::ulpdist(v, sz)))];', ' ++k;', ' if (k%100000000 == 0){', ' std::cout << "." << std::flush; ++j;', ' if (j == 80){std::cout << std::endl; j = 0;}', ' }', ' }', ' }', ' std::cout << "exhaustive test for " << std::endl;', ' std::cout << " nt2::$name$ versus $repfunc$ " << std::endl;', ' std::cout << " in $mode$ mode and $typ$ type" << std::endl;', ' for(nt2::uint32_t i = 0; i < M; i++)', ' std::cout << i/2.0 << " -> " << histo[i] << std::endl;', ' std::cout << k << " values computed" << std::endl;', ' std::cout << std::endl;', ' std::cout << std::endl;', ' for(nt2::uint32_t i = 0; i < M; i++)', ' std::cout << i/2.0 << " -> "', ' << (histo[i]*100.0/k) << "%" << std::endl;', ' }', '', ]), } } def __init__(self) : self.tpl = Exhaustive_data.Tpl if __name__ == "__main__" : print __doc__ from pprint import PrettyPrinter PrettyPrinter().pprint(Exhaustive_data.Tpl) PrettyPrinter().pprint(Exhaustive_data().tpl)
46.105263
95
0.379485
5,114
0.833986
0
0
0
0
0
0
3,897
0.635519
69ea7259b3d374e9cf30752c6716f0ff14c30c20
1,159
py
Python
automator.py
Mfdsix/GoHugo-Blog-Example
0bdb5396732b2cfcd5e8885a6e2dd65cab416a01
[ "Apache-2.0" ]
1
2021-08-24T13:45:45.000Z
2021-08-24T13:45:45.000Z
automator.py
Mfdsix/GoHugo-Blog-Example
0bdb5396732b2cfcd5e8885a6e2dd65cab416a01
[ "Apache-2.0" ]
null
null
null
automator.py
Mfdsix/GoHugo-Blog-Example
0bdb5396732b2cfcd5e8885a6e2dd65cab416a01
[ "Apache-2.0" ]
null
null
null
import requests import os, shutil import re folder = 'content/post' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) baseUrl = "https://api.currentsapi.services/v1/" key = "youkey" # top headline response = requests.get("%slatest-news?apiKey=%s" % (baseUrl, key)) posts = response.json()['news'] for i in posts: header = '+++\ntitle = "%s"\ndescription = "%s"\ntags = [\n"%s",\n]\ndate = %s\nauthor = "%s"\n+++\n\n''' % (i['title'], i['description'][0:35], i['category'][0], i['published'].replace(" +0000", "Z").replace(" ", "T"), i['author']) content = i['description'] try: filename = "%s/%s.md" % (folder, re.sub(r'[^a-zA-Z0-9]', "-", i['title'].lower().replace(" ", "-"))) file = open(filename, "w") file.write(header + content) except Exception as e: print("failed to generate file", e)
34.088235
236
0.592752
0
0
0
0
0
0
0
0
382
0.329594
69ea995bb78ba1500d77b1d87bab05350042744d
1,530
py
Python
solutions/python/2017/possibleHeights.py
lucifer1198/Codesignal
07d6d6457b8b3a9f1c51118b0e8e44cce66ee039
[ "MIT" ]
2
2020-12-21T22:09:26.000Z
2021-01-01T15:40:01.000Z
solutions/python/2017/possibleHeights.py
nsu1210/Codesignal
07d6d6457b8b3a9f1c51118b0e8e44cce66ee039
[ "MIT" ]
null
null
null
solutions/python/2017/possibleHeights.py
nsu1210/Codesignal
07d6d6457b8b3a9f1c51118b0e8e44cce66ee039
[ "MIT" ]
1
2021-01-28T18:15:02.000Z
2021-01-28T18:15:02.000Z
def possibleHeights(parent): edges = [[] for i in range(len(parent))] height = [0 for i in range(len(parent))] isPossibleHeight = [False for i in range(len(parent))] def initGraph(parent): for i in range(1, len(parent)): edges[parent[i]].append(i) def calcHeight(v): for u in edges[v]: calcHeight(u) height[v] = max(height[v], height[u]+1) countHeights = [[] for i in range(len(edges))] for i in range(len(edges[v])): u = edges[v][i] countHeights[height[u]].append(u) edges[v] = [] for i in range(len(edges) - 1, -1, -1): for j in range(len(countHeights[i])): edges[v].append(countHeights[i][j]) def findNewHeights(v, tailHeight): isPossibleHeight[max(height[v], tailHeight)] = True firstMaxHeight = tailHeight + 1 secondMaxHeight = tailHeight + 1 if len(edges[v]) > 0: firstMaxHeight = max(firstMaxHeight, height[edges[v][0]] + 2) if len(edges[v]) > 1: secondMaxHeight = max(secondMaxHeight, height[edges[v][1]] + 2) if len(edges[v]) > 0: findNewHeights(edges[v][0], secondMaxHeight) for i in range(1, len(edges[v])): findNewHeights(edges[v][i], firstMaxHeight) initGraph(parent) calcHeight(0) findNewHeights(0, 0) heights = [] for i in range(len(parent)): if isPossibleHeight[i]: heights.append(i) return heights
32.553191
75
0.560131
0
0
0
0
0
0
0
0
0
0
69eaf97d49b7fab955a57a6eb5efeed97327c325
21,388
py
Python
geonode/geonode/maps/qgis_server_views.py
ttungbmt/BecaGIS_GeoPortal
6c05f9fc020ec4ccf600ba2503a06c2231443920
[ "MIT" ]
null
null
null
geonode/geonode/maps/qgis_server_views.py
ttungbmt/BecaGIS_GeoPortal
6c05f9fc020ec4ccf600ba2503a06c2231443920
[ "MIT" ]
null
null
null
geonode/geonode/maps/qgis_server_views.py
ttungbmt/BecaGIS_GeoPortal
6c05f9fc020ec4ccf600ba2503a06c2231443920
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### import json import requests import math import logging from django.conf import settings from django.views.generic import CreateView, DetailView, UpdateView from django.core.exceptions import ObjectDoesNotExist from django.core.serializers.json import DjangoJSONEncoder from django.views.decorators.clickjacking import xframe_options_exempt from django.utils.decorators import method_decorator from django.urls import reverse from django.shortcuts import render from django.http import HttpResponse from geonode.maps.views import _PERMISSION_MSG_VIEW, _resolve_map, _resolve_layer from geonode.maps.models import Map, MapLayer from geonode.layers.models import Layer from geonode.utils import default_map_config, forward_mercator, \ llbbox_to_mercator, check_ogc_backend from geonode import geoserver, qgis_server from urllib.parse import urlsplit if check_ogc_backend(geoserver.BACKEND_PACKAGE): # FIXME: The post service providing the map_status object # should be moved to geonode.geoserver. from geonode.geoserver.helpers import ogc_server_settings elif check_ogc_backend(qgis_server.BACKEND_PACKAGE): from geonode.qgis_server.helpers import ogc_server_settings from geonode.qgis_server.tasks.update import create_qgis_server_thumbnail logger = logging.getLogger("geonode.maps.qgis_server_views") class MapCreateView(CreateView): model = Map fields = '__all__' template_name = 'leaflet/maps/map_view.html' context_object_name = 'map' def get_context_data(self, **kwargs): request = self.request if request and 'access_token' in request.session: access_token = request.session['access_token'] else: access_token = None DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) layers = Layer.objects.all() if request.method == 'GET' and 'copy' in request.GET: """Prepare context data.""" request = self.request mapid = self.request.GET['copy'] map_obj = _resolve_map( request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) config = map_obj.viewer_json(request) # list all required layers map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') context = { 'config': json.dumps(config), 'create': False, 'layers': layers, 'map': map_obj, 'map_layers': map_layers, 'preview': getattr( settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } return context else: if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST else: return self.render_to_response(status=405) if 'layer' in params: bbox = None map_obj = Map(projection=getattr( settings, 'DEFAULT_MAP_CRS', 'EPSG:3857')) for layer_name in params.getlist('layer'): try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not request.user.has_perm( 'view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = min(bbox[1], layer_bbox[1]) bbox[2] = max(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) config = layer.attribute_config() # Add required parameters for GXP lazy-loading config["title"] = layer.title config["queryable"] = True config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') config["bbox"] = bbox if config["srs"] != 'EPSG:3857' \ else llbbox_to_mercator( [float(coord) for coord in bbox]) if layer.storeType == "remoteStore": service = layer.remote_service # Probably not a good idea to send the access token to every remote service. # This should never match, so no access token should be sent to remote services. ogc_server_url = urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc service_url = urlsplit( service.base_url).netloc if access_token and ogc_server_url == service_url and \ 'access_token' not in service.base_url: url = f'{service.base_url}?access_token={access_token}' else: url = service.base_url map_layers = MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps({ "ptype": service.ptype, "remote": True, "url": url, "name": service.name, "title": f"[R] {service.title}"})) else: ogc_server_url = urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlsplit(layer.ows_url).netloc if access_token and ogc_server_url == layer_url and \ 'access_token' not in layer.ows_url: url = f"{layer.ows_url}?access_token={access_token}" else: url = layer.ows_url map_layers = MapLayer( map=map_obj, name=layer.typename, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps( config, cls=DjangoJSONEncoder), visibility=True ) if bbox and len(bbox) >= 4: minx, miny, maxx, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) map_obj.handle_moderated_uploads() config = map_obj.viewer_json(request) config['fromLayer'] = True context = { 'config': json.dumps(config), 'create': True, 'layers': layers, 'map': map_obj, 'map_layers': map_layers, 'preview': getattr( settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } else: # list all required layers layers = Layer.objects.all() context = { 'create': True, 'layers': layers } return context def get_success_url(self): pass def get_form_kwargs(self): kwargs = super(MapCreateView, self).get_form_kwargs() return kwargs class MapDetailView(DetailView): model = Map template_name = 'leaflet/maps/map_view.html' context_object_name = 'map' def get_context_data(self, **kwargs): """Prepare context data.""" mapid = self.kwargs.get('mapid') request = self.request map_obj = _resolve_map( request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) config = map_obj.viewer_json(request) # list all required layers layers = Layer.objects.all() map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') context = { 'config': json.dumps(config), 'create': False, 'layers': layers, 'map': map_obj, 'map_layers': map_layers, 'preview': getattr( settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } return context def get_object(self): return Map.objects.get(id=self.kwargs.get("mapid")) class MapEmbedView(DetailView): model = Map template_name = 'leaflet/maps/map_detail.html' context_object_name = 'map' def get_context_data(self, **kwargs): """Prepare context data.""" mapid = self.kwargs.get('mapid') request = self.request map_obj = _resolve_map( request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) config = map_obj.viewer_json(request) # list all required layers map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') context = { 'config': json.dumps(config), 'create': False, 'resource': map_obj, 'layers': map_layers, 'preview': getattr( settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } return context def get_object(self): return Map.objects.get(id=self.kwargs.get("mapid")) @method_decorator(xframe_options_exempt) def dispatch(self, *args, **kwargs): return super(MapEmbedView, self).dispatch(*args, **kwargs) class MapEditView(UpdateView): model = Map fields = '__all__' template_name = 'leaflet/maps/map_edit.html' context_object_name = 'map' def get_context_data(self, **kwargs): # list all required layers mapid = self.kwargs.get('mapid') request = self.request map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) config = map_obj.viewer_json(request) layers = Layer.objects.all() map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') context = { 'create': False, 'config': json.dumps(config), 'layers': layers, 'map_layers': map_layers, 'map': map_obj, 'preview': getattr( settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } return context def get(self, request, **kwargs): self.object = Map.objects.get( id=self.kwargs.get('mapid')) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data( object=self.object, form=form) return self.render_to_response(context) def get_success_url(self): pass def get_form_kwargs(self): kwargs = super(MapEditView, self).get_form_kwargs() return kwargs class MapUpdateView(UpdateView): model = Map fields = '__all__' template_name = 'leaflet/maps/map_edit.html' context_object_name = 'map' def get_context_data(self, **kwargs): mapid = self.kwargs.get('mapid') request = self.request map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) if request.method == 'POST': if not request.user.is_authenticated: return self.render_to_response( 'You must be logged in to save new maps', content_type="text/plain", status=401 ) map_obj.overwrite = True map_obj.save() map_obj.set_default_permissions() map_obj.handle_moderated_uploads() # If the body has been read already, use an empty string. # See https://github.com/django/django/commit/58d555caf527d6f1bdfeab14527484e4cca68648 # for a better exception to catch when we move to Django 1.7. try: body = request.body except Exception: body = '' try: # Call the base implementation first to get a context context = super(MapUpdateView, self).get_context_data(**kwargs) map_obj.update_from_viewer(body, context=context) except ValueError as e: return self.render_to_response(str(e), status=400) else: context = { 'create': False, 'status': 200, 'map': map_obj, 'content_type': 'application/json' } return context else: return self.render_to_response(status=405) def get(self, request, **kwargs): self.object = Map.objects.get( id=self.kwargs.get('mapid')) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(object=self.object, form=form) return self.render_to_response(context) def get_object(self, queryset=None): obj = Map.objects.get( id=self.kwargs.get('mapid')) return obj def map_download_qlr(request, mapid): """Download QLR file to open the maps' layer in QGIS desktop. :param request: The request from the frontend. :type request: HttpRequest :param mapid: The id of the map. :type mapid: String :return: QLR file. """ map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) def perm_filter(layer): return request.user.has_perm( 'base.view_resourcebase', obj=layer.get_self_resource()) mapJson = map_obj.json(perm_filter) # we need to remove duplicate layers j_map = json.loads(mapJson) j_layers = j_map["layers"] for j_layer in j_layers: if j_layer["service"] is None: j_layers.remove(j_layer) continue if (len([_l for _l in j_layers if _l == j_layer])) > 1: j_layers.remove(j_layer) map_layers = [] for layer in j_layers: layer_name = layer["name"].split(":")[1] ogc_url = reverse('qgis_server:layer-request', kwargs={'layername': layer_name}) url = settings.SITEURL + ogc_url.replace("/", "", 1) map_layers.append({ 'type': 'raster', 'display': layer_name, 'driver': 'wms', 'crs': 'EPSG:4326', 'format': 'image/png', 'styles': '', 'layers': layer_name, 'url': url }) json_layers = json.dumps(map_layers) url_server = f"{settings.QGIS_SERVER_URL}?SERVICE=LAYERDEFINITIONS&LAYERS={json_layers}" fwd_request = requests.get(url_server) response = HttpResponse( fwd_request.content, content_type="application/x-qgis-layer-definition", status=fwd_request.status_code) response['Content-Disposition'] = f'attachment; filename={map_obj.title}.qlr' return response def map_download_leaflet(request, mapid, template='leaflet/maps/map_embed.html'): """Download leaflet map as static HTML. :param request: The request from the frontend. :type request: HttpRequest :param mapid: The id of the map. :type mapid: String :return: HTML file. """ map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') layers = [] for layer in map_layers: if layer.group != 'background': layers.append(layer) context = { 'resource': map_obj, 'map_layers': layers, 'for_download': True } the_page = render(request, template, context=context) response = HttpResponse( the_page.content, content_type="html", status=the_page.status_code) response['Content-Disposition'] = f'attachment; filename={map_obj.title}.html' return response def set_thumbnail_map(request, mapid): """Update thumbnail based on map extent :param layername: The layer name in Geonode. :type layername: basestring :return success: true if success, None if fail. :type success: bool """ if request.method != 'POST': return HttpResponse('Bad Request') map_layers = MapLayer.objects.filter(map__id=mapid) local_layers = [_l for _l in map_layers if _l.local] layers = {} for layer in local_layers: try: _l = Layer.objects.get(typename=layer.name) layers[_l.name] = _l except Layer.DoesNotExist: msg = f'No Layer found for typename: {layer.name}' logger.debug(msg) if not layers: # The signal is called too early, or the map has no layer yet. return bbox = _get_bbox_from_layers(layers) # Give thumbnail creation to celery tasks, and exit. create_qgis_server_thumbnail.apply_async( ('maps.map', mapid, True, bbox)) retval = { 'success': True } return HttpResponse( json.dumps(retval), content_type="application/json") def _get_bbox_from_layers(layers): """ Calculate the bbox from a given list of Layer objects """ bbox = None for layer in layers: layer_bbox = layers[layer].bbox_string.split(',') if bbox is None: bbox = [float(key) for key in layer_bbox] else: bbox[0] = float(min(bbox[0], layer_bbox[0])) bbox[1] = float(min(bbox[1], layer_bbox[1])) bbox[2] = float(max(bbox[2], layer_bbox[2])) bbox[3] = float(max(bbox[3], layer_bbox[3])) return bbox
35.119869
104
0.534412
14,442
0.675238
0
0
148
0.00692
0
0
4,803
0.224565
69eb8001ee863674c031e16f1d53ea9d8468e34b
14,203
py
Python
reframe/core/config.py
mboisson/reframe
ebf0141596f19c7df60b59d8ad6211067f55b5e5
[ "BSD-3-Clause" ]
null
null
null
reframe/core/config.py
mboisson/reframe
ebf0141596f19c7df60b59d8ad6211067f55b5e5
[ "BSD-3-Clause" ]
null
null
null
reframe/core/config.py
mboisson/reframe
ebf0141596f19c7df60b59d8ad6211067f55b5e5
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import collections.abc import json import jsonschema import os import re import tempfile import reframe import reframe.core.debug as debug import reframe.core.fields as fields import reframe.utility as util import reframe.utility.os_ext as os_ext import reframe.utility.typecheck as types from reframe.core.exceptions import (ConfigError, ReframeError, ReframeFatalError) _settings = None def load_settings_from_file(filename): global _settings try: _settings = util.import_module_from_file(filename).settings return _settings except Exception as e: raise ConfigError( "could not load configuration file `%s'" % filename) from e def settings(): if _settings is None: raise ReframeFatalError('ReFrame is not configured') return _settings class SiteConfiguration: '''Holds the configuration of systems and environments''' _modes = fields.ScopedDictField('_modes', types.List[str]) def __init__(self, dict_config=None): self._systems = {} self._modes = {} if dict_config is not None: self.load_from_dict(dict_config) def __repr__(self): return debug.repr(self) @property def systems(self): return self._systems @property def modes(self): return self._modes def get_schedsystem_config(self, descr): # Handle the special shortcuts first from reframe.core.launchers.registry import getlauncher from reframe.core.schedulers.registry import getscheduler if descr == 'nativeslurm': return getscheduler('slurm'), getlauncher('srun') if descr == 'local': return getscheduler('local'), getlauncher('local') try: sched_descr, launcher_descr = descr.split('+') except ValueError: raise ValueError('invalid syntax for the ' 'scheduling system: %s' % descr) from None return getscheduler(sched_descr), getlauncher(launcher_descr) def load_from_dict(self, site_config): if not isinstance(site_config, collections.abc.Mapping): raise TypeError('site configuration is not a dict') # We do all the necessary imports here and not on the top, because we # want to remove import time dependencies import reframe.core.environments as m_env from reframe.core.systems import System, SystemPartition sysconfig = site_config.get('systems', None) envconfig = site_config.get('environments', None) modes = site_config.get('modes', {}) if not sysconfig: raise ValueError('no entry for systems was found') if not envconfig: raise ValueError('no entry for environments was found') # Convert envconfig to a ScopedDict try: envconfig = fields.ScopedDict(envconfig) except TypeError: raise TypeError('environments configuration ' 'is not a scoped dictionary') from None # Convert modes to a `ScopedDict`; note that `modes` will implicitly # converted to a scoped dict here, since `self._modes` is a # `ScopedDictField`. try: self._modes = modes except TypeError: raise TypeError('modes configuration ' 'is not a scoped dictionary') from None def create_env(system, partition, name): # Create an environment instance try: config = envconfig['%s:%s:%s' % (system, partition, name)] except KeyError: raise ConfigError( "could not find a definition for `%s'" % name ) from None if not isinstance(config, collections.abc.Mapping): raise TypeError("config for `%s' is not a dictionary" % name) return m_env.ProgEnvironment(name, **config) # Populate the systems directory for sys_name, config in sysconfig.items(): if not isinstance(config, dict): raise TypeError('system configuration is not a dictionary') if not isinstance(config['partitions'], collections.abc.Mapping): raise TypeError('partitions must be a dictionary') sys_descr = config.get('descr', sys_name) sys_hostnames = config.get('hostnames', []) # The System's constructor provides also reasonable defaults, but # since we are going to set them anyway from the values provided by # the configuration, we should set default values here. The stage, # output and log directories default to None, since they are going # to be set dynamically by the runtime. sys_prefix = config.get('prefix', '.') sys_stagedir = config.get('stagedir', None) sys_outputdir = config.get('outputdir', None) sys_perflogdir = config.get('perflogdir', None) sys_resourcesdir = config.get('resourcesdir', '.') sys_modules_system = config.get('modules_system', None) # Expand variables if sys_prefix: sys_prefix = os_ext.expandvars(sys_prefix) if sys_stagedir: sys_stagedir = os_ext.expandvars(sys_stagedir) if sys_outputdir: sys_outputdir = os_ext.expandvars(sys_outputdir) if sys_perflogdir: sys_perflogdir = os_ext.expandvars(sys_perflogdir) if sys_resourcesdir: sys_resourcesdir = os_ext.expandvars(sys_resourcesdir) # Create the preload environment for the system sys_preload_env = m_env.Environment( name='__rfm_env_%s' % sys_name, modules=config.get('modules', []), variables=config.get('variables', {}) ) system = System(name=sys_name, descr=sys_descr, hostnames=sys_hostnames, preload_env=sys_preload_env, prefix=sys_prefix, stagedir=sys_stagedir, outputdir=sys_outputdir, perflogdir=sys_perflogdir, resourcesdir=sys_resourcesdir, modules_system=sys_modules_system) for part_name, partconfig in config.get('partitions', {}).items(): if not isinstance(partconfig, collections.abc.Mapping): raise TypeError("partition `%s' not configured " "as a dictionary" % part_name) part_descr = partconfig.get('descr', part_name) part_scheduler, part_launcher = self.get_schedsystem_config( partconfig.get('scheduler', 'local+local') ) part_local_env = m_env.Environment( name='__rfm_env_%s' % part_name, modules=partconfig.get('modules', []), variables=partconfig.get('variables', {}).items() ) part_environs = [ create_env(sys_name, part_name, e) for e in partconfig.get('environs', []) ] part_access = partconfig.get('access', []) part_resources = partconfig.get('resources', {}) part_max_jobs = partconfig.get('max_jobs', 1) part = SystemPartition(name=part_name, descr=part_descr, scheduler=part_scheduler, launcher=part_launcher, access=part_access, environs=part_environs, resources=part_resources, local_env=part_local_env, max_jobs=part_max_jobs) container_platforms = partconfig.get('container_platforms', {}) for cp, env_spec in container_platforms.items(): cp_env = m_env.Environment( name='__rfm_env_%s' % cp, modules=env_spec.get('modules', []), variables=env_spec.get('variables', {}) ) part.add_container_env(cp, cp_env) system.add_partition(part) self._systems[sys_name] = system def convert_old_config(filename): old_config = load_settings_from_file(filename) converted = { 'systems': [], 'environments': [], 'logging': [], 'perf_logging': [], } old_systems = old_config.site_configuration['systems'].items() for sys_name, sys_specs in old_systems: sys_dict = {'name': sys_name} sys_dict.update(sys_specs) # Make variables dictionary into a list of lists if 'variables' in sys_specs: sys_dict['variables'] = [ [vname, v] for vname, v in sys_dict['variables'].items() ] # Make partitions dictionary into a list if 'partitions' in sys_specs: sys_dict['partitions'] = [] for pname, p in sys_specs['partitions'].items(): new_p = {'name': pname} new_p.update(p) if p['scheduler'] == 'nativeslurm': new_p['scheduler'] = 'slurm' new_p['launcher'] = 'srun' elif p['scheduler'] == 'local': new_p['scheduler'] = 'local' new_p['launcher'] = 'local' else: sched, launch, *_ = p['scheduler'].split('+') new_p['scheduler'] = sched new_p['launcher'] = launch # Make resources dictionary into a list if 'resources' in p: new_p['resources'] = [ {'name': rname, 'options': r} for rname, r in p['resources'].items() ] # Make variables dictionary into a list of lists if 'variables' in p: new_p['variables'] = [ [vname, v] for vname, v in p['variables'].items() ] if 'container_platforms' in p: new_p['container_platforms'] = [] for cname, c in p['container_platforms'].items(): new_c = {'name': cname} new_c.update(c) if 'variables' in c: new_c['variables'] = [ [vn, v] for vn, v in c['variables'].items() ] new_p['container_platforms'].append(new_c) sys_dict['partitions'].append(new_p) converted['systems'].append(sys_dict) old_environs = old_config.site_configuration['environments'].items() for env_target, env_entries in old_environs: for ename, e in env_entries.items(): new_env = {'name': ename} if env_target != '*': new_env['target_systems'] = [env_target] new_env.update(e) # Convert variables dictionary to a list of lists if 'variables' in e: new_env['variables'] = [ [vname, v] for vname, v in e['variables'].items() ] # Type attribute is not used anymore if 'type' in new_env: del new_env['type'] converted['environments'].append(new_env) if 'modes' in old_config.site_configuration: converted['modes'] = [] old_modes = old_config.site_configuration['modes'].items() for target_mode, mode_entries in old_modes: for mname, m in mode_entries.items(): new_mode = {'name': mname, 'options': m} if target_mode != '*': new_mode['target_systems'] = [target_mode] converted['modes'].append(new_mode) def update_logging_config(log_name, original_log): new_handlers = [] for h in original_log['handlers']: new_h = h new_h['level'] = h['level'].lower() new_handlers.append(new_h) converted[log_name].append( { 'level': original_log['level'].lower(), 'handlers': new_handlers } ) update_logging_config('logging', old_config.logging_config) update_logging_config('perf_logging', old_config.perf_logging_config) converted['general'] = [{}] if hasattr(old_config, 'checks_path'): converted['general'][0][ 'check_search_path' ] = old_config.checks_path if hasattr(old_config, 'checks_path_recurse'): converted['general'][0][ 'check_search_recursive' ] = old_config.checks_path_recurse if converted['general'] == [{}]: del converted['general'] # Validate the converted file schema_filename = os.path.join(reframe.INSTALL_PREFIX, 'schemas', 'config.json') # We let the following statements raise, because if they do, that's a BUG with open(schema_filename) as fp: schema = json.loads(fp.read()) jsonschema.validate(converted, schema) with tempfile.NamedTemporaryFile(mode='w', delete=False) as fp: fp.write(f"#\n# This file was automatically generated " f"by ReFrame based on '{filename}'.\n#\n\n") fp.write(f'site_configuration = {util.ppretty(converted)}\n') return fp.name
37.874667
79
0.553897
7,872
0.554249
0
0
118
0.008308
0
0
3,327
0.234246
69ede5a7a5d5e261a9c1ba0ddb8dc8c9e3cbfadd
1,224
py
Python
account/forms.py
hhdMrLion/crm_api
66df068821be36a17c3b0e0e9660b7f8408fa1bd
[ "Apache-2.0" ]
1
2021-06-18T03:03:38.000Z
2021-06-18T03:03:38.000Z
account/forms.py
hhdMrLion/crm_api
66df068821be36a17c3b0e0e9660b7f8408fa1bd
[ "Apache-2.0" ]
null
null
null
account/forms.py
hhdMrLion/crm_api
66df068821be36a17c3b0e0e9660b7f8408fa1bd
[ "Apache-2.0" ]
null
null
null
from django import forms from django.contrib.auth import authenticate, login from django.utils.timezone import now class LoginForm(forms.Form): """ ็™ปๅฝ•่กจๅ• """ username = forms.CharField(label='็”จๆˆทๅ', max_length=100, required=False, initial='admin') password = forms.CharField(label='ๅฏ†็ ', max_length=200, min_length=6, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.username = None def clean(self): data = super(LoginForm, self).clean() # ๅˆคๆ–ญ็”จๆˆทๆ˜ฏๅ“ชไธ€ไฝ print(data) if self.errors: return username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is None: raise forms.ValidationError('็”จๆˆทๅๆˆ–่€…ๆ˜ฏๅฏ†็ ไธๆญฃ็กฎ') else: if not user.is_active: raise forms.ValidationError('่ฏฅ็”จๆˆทๅทฒ่ขซ็ฆ็”จ') self.user = user return data def do_login(self, request): # ๆ‰ง่กŒ็”จๆˆท็™ปๅฝ• user = self.user login(request, user) user.last_login = now() user.save() return user
30.6
101
0.591503
1,182
0.905054
0
0
0
0
0
0
172
0.1317
69eded2c37603527f5c2e4966e85000fb0b6519e
3,263
py
Python
fileshare/fileup/utils.py
nijatrajab/fileshare
f364788f318ffe8b731ccb68e9c275bfa73c0292
[ "MIT" ]
1
2021-07-08T06:51:28.000Z
2021-07-08T06:51:28.000Z
fileshare/fileup/utils.py
nijatrajab/fileshareproject
f364788f318ffe8b731ccb68e9c275bfa73c0292
[ "MIT" ]
null
null
null
fileshare/fileup/utils.py
nijatrajab/fileshareproject
f364788f318ffe8b731ccb68e9c275bfa73c0292
[ "MIT" ]
null
null
null
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.db.models import Q from guardian.ctypes import get_content_type from guardian.shortcuts import get_perms, get_user_perms from guardian.utils import get_user_obj_perms_model, get_group_obj_perms_model def get_users_timestamp_with_perms(obj, attach_perms=False, with_superusers=False, with_group_users=True, only_with_perms_in=None): ctype = get_content_type(obj) if not attach_perms: # It's much easier without attached perms so we do it first if that is # the case user_model = get_user_obj_perms_model(obj) related_name = user_model.user.field.related_query_name() if user_model.objects.is_generic(): user_filters = { '%s__content_type' % related_name: ctype, '%s__object_pk' % related_name: obj.pk, } else: user_filters = {'%s__content_object' % related_name: obj} qset = Q(**user_filters) if only_with_perms_in is not None: permission_ids = Permission.objects.filter(content_type=ctype, codename__in=only_with_perms_in).values_list( 'id', flat=True) qset &= Q(**{ '%s__permission_id__in' % related_name: permission_ids, }) if with_group_users: group_model = get_group_obj_perms_model(obj) if group_model.objects.is_generic(): group_obj_perm_filters = { 'content_type': ctype, 'object_pk': obj.pk, } else: group_obj_perm_filters = { 'content_object': obj, } if only_with_perms_in is not None: group_obj_perm_filters.update({ 'permission_id__in': permission_ids, }) group_ids = set( group_model.objects.filter(**group_obj_perm_filters).values_list('group_id', flat=True).distinct()) qset = qset | Q(groups__in=group_ids) if with_superusers: qset = qset | Q(is_superuser=True) model = get_user_obj_perms_model(obj) users = {} for user in get_user_model().objects.filter(qset).distinct(): permission = Permission.objects.get(codename='view_userfile') guardian_object = model.objects.get(user=user, object_pk=obj.pk, permission=permission) users[user] = guardian_object.timestamp return users else: users = {} for user in get_users_timestamp_with_perms(obj, with_group_users=with_group_users, only_with_perms_in=only_with_perms_in, with_superusers=with_superusers): if with_group_users or with_superusers: users[user] = sorted(get_perms(user, obj)) else: users[user] = sorted(get_user_perms(user, obj)) return users
44.69863
120
0.575544
0
0
0
0
0
0
0
0
245
0.075084
69ef030a305db0390a90f17929cad93e52de6059
2,090
py
Python
welly/__init__.py
agilescientific/welly
1ced65d6e7d48642112e72ec8b412687e5a910db
[ "Apache-2.0" ]
3
2022-03-17T08:42:25.000Z
2022-03-23T08:26:13.000Z
welly/__init__.py
agilescientific/welly
1ced65d6e7d48642112e72ec8b412687e5a910db
[ "Apache-2.0" ]
3
2022-03-08T13:01:14.000Z
2022-03-21T09:42:09.000Z
welly/__init__.py
agilescientific/welly
1ced65d6e7d48642112e72ec8b412687e5a910db
[ "Apache-2.0" ]
1
2022-03-16T03:51:39.000Z
2022-03-16T03:51:39.000Z
""" ================== welly ================== """ from .project import Project from .well import Well from .header import Header from .curve import Curve from .synthetic import Synthetic from .location import Location from .crs import CRS from . import tools from . import quality def read_las(path, **kwargs): """ A package namespace method to be called as `welly.read_las`. Just wraps `Project.from_las()`. Creates a `Project` from a .LAS file. Args: path (str): path or URL where LAS is located. `*.las` to load all files in dir **kwargs (): See `Project.from_las()`` for addictional arguments Returns: welly.Project. The Project object. """ return Project.from_las(path, **kwargs) def read_df(df, **kwargs): """ A package namespace method to be called as `welly.read_df`. Just wraps `Well.from_df()`. Creates a `Well` from your pd.DataFrame. Args: df (pd.DataFrame): Column data and column names Optional **kwargs: units (dict): Optional. Units of measurement of the curves in `df`. req (list): Optional. An alias list, giving all required curves. uwi (str): Unique Well Identifier (UWI) name (str): Name Returns: Well. The `Well` object. """ return Well.from_df(df, **kwargs) __all__ = [ 'Project', 'Well', 'Header', 'Curve', 'Synthetic', 'Location', 'CRS', 'quality', 'tools', # Various classes in here 'read_las' ] from pkg_resources import get_distribution, DistributionNotFound try: VERSION = get_distribution(__name__).version except DistributionNotFound: try: from ._version import version as VERSION except ImportError: raise ImportError( "Failed to find (autogenerated) _version.py. " "This might be because you are installing from GitHub's tarballs, " "use the PyPI ones." ) __version__ = VERSION
25.180723
79
0.596651
0
0
0
0
0
0
0
0
1,213
0.580383
69f057ed5c729374804cbd4b48a0e971199df0ac
784
py
Python
numpy/random/examples/cython/setup.py
IntelLabs/numpy
1b4a877449313761d3de75c1ad725fdf396b170e
[ "BSD-3-Clause" ]
7
2019-02-27T20:26:01.000Z
2020-09-27T04:37:44.000Z
numpy/random/examples/cython/setup.py
IntelLabs/numpy
1b4a877449313761d3de75c1ad725fdf396b170e
[ "BSD-3-Clause" ]
3
2019-12-23T09:26:27.000Z
2021-10-31T13:34:17.000Z
numpy/random/examples/cython/setup.py
IntelLabs/numpy
1b4a877449313761d3de75c1ad725fdf396b170e
[ "BSD-3-Clause" ]
3
2019-07-20T02:16:07.000Z
2020-08-17T20:02:30.000Z
#!/usr/bin/env python3 """ Build the demos Usage: python setup.py build_ext -i """ import numpy as np from distutils.core import setup from Cython.Build import cythonize from setuptools.extension import Extension from os.path import join extending = Extension("extending", sources=['extending.pyx'], include_dirs=[np.get_include()]) distributions = Extension("extending_distributions", sources=['extending_distributions.pyx', join('..', '..', 'src', 'distributions', 'distributions.c')], include_dirs=[np.get_include()]) extensions = [extending, distributions] setup( ext_modules=cythonize(extensions) )
28
77
0.590561
0
0
0
0
0
0
0
0
207
0.264031
69f1e9cbbe7a9063f003afdafb274eaf79f6665a
2,204
py
Python
code/mts_agent_python/config/mts_import.py
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
8
2019-03-28T04:15:59.000Z
2021-03-23T14:29:43.000Z
code/mts_agent_python/config/mts_import.py
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
null
null
null
code/mts_agent_python/config/mts_import.py
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
5
2019-11-06T12:39:21.000Z
2021-01-28T19:14:14.000Z
#!/usr/bin/env python # encoding: utf-8 import signal import sys #import pandas as pd #import numpy as np def setGlobals(g): #print globals() globals().update(g) #print globals() def exit(): mtsExit(0) def quit(signum): sys.exit(signum) def quitNow(signum,frame): quit(signum) def initialize(params,p2=None): signal.signal(signal.SIGINT, quitNow) signal.signal(signal.SIGTERM, quitNow) if (p2==None): return mtsInitialize(params) else: return mtsInitialize(params,p2) def execute(): mtsExecute() def info(*tp): return mtsInfo(tp) def log(*tp): return mtsLog(tp) def warn(*tp): return mtsWarn(tp) def error(*tp): return mtsError(tp) def file(*tp): return mtsFile(tp) def genMtsStratgyClass(): class Strategy(StrategyBase): def __init__(self,name, strategyId): super(Strategy, self).__init__(name,strategyId) def newDirectOrder(self,symbol,price,volume,direction,offsetFlag): return self.newOrder({"type":1,"symbol":symbol,"price":price,"volume":volume,"direction":direction,"offsetFlag":offsetFlag}) def newNetOrder(self,symbol,price,volume): return self.newOrder({"type":2,"symbol":symbol,"price":price,"volume":volume}) def newBoxOrder(self,symbol,price,volume): return self.newOrder({"type":3,"symbol":symbol,"price":price,"volume":volume}) # def history(self,symbol,count): # pf = pd.DataFrame(self.getHistory(symbol, count), # columns=['date', 'open', 'high', 'low', 'close', 'volume', 'vwap']) # pf['date'] = pd.to_datetime(pf['date'],format='%Y%m%d %H%M%S') # return pf.set_index('date').astype(np.float64) # # def dailyHistory(self, symbol, count): # pf = pd.DataFrame(self.getDailyHistory(symbol, count), # columns=['date', 'open', 'high', 'low', 'close', 'volume', 'vwap']) # pf['date'] = pd.to_datetime(pf['date'], format='%Y%m%d %H%M%S') # return pf.set_index('date').astype(np.float64) return Strategy
29.386667
136
0.596642
1,381
0.626588
0
0
0
0
0
0
831
0.377042
69f26355443efdf41ec0c1d1bd32986ecad1e099
8,949
py
Python
plumcot_prodigy/entity.py
julietteBergoend/plumcot-prodigy
aaac14df24309e5b2064b213031d288d284a6747
[ "MIT" ]
1
2021-06-22T12:43:42.000Z
2021-06-22T12:43:42.000Z
plumcot_prodigy/entity.py
julietteBergoend/plumcot-prodigy
aaac14df24309e5b2064b213031d288d284a6747
[ "MIT" ]
null
null
null
plumcot_prodigy/entity.py
julietteBergoend/plumcot-prodigy
aaac14df24309e5b2064b213031d288d284a6747
[ "MIT" ]
null
null
null
import prodigy from prodigy.components.preprocess import add_tokens, split_sentences from plumcot_prodigy.custom_loaders import * import requests from plumcot_prodigy.video import mkv_to_base64 from typing import Dict, List, Text, Union from typing_extensions import Literal import spacy from pathlib import Path """ Annotate entity linking (3rd person & names) Displays sentences with tokens to annotate If the token is an entity linking, write the name of the corresponding character in the text input of Prodigy Arguments : ep : episode to annotate (e.g TheWalkingDead.Season01.Episode01), Start prodigy : prodigy entity_linking entity_data <episode_name> <path_to_corpora> -F plumcot_prodigy/entity.py """ def remove_video_before_db(examples: List[Dict]) -> List[Dict]: """Remove (heavy) "video" and "pictures" key from examples before saving to Prodigy database Parameters ---------- examples : list of dict Examples. Returns ------- examples : list of dict Examples with 'video' or 'pictures' key removed. """ for eg in examples: if "video" in eg: del eg["video"] if 'field_suggestions' in eg: del eg['field_suggestions'] return examples def entity_linking(episode, user_path): DATA_PLUMCOT = user_path show = episode.split('.')[0] season = episode.split('.')[1] ep= episode.split('.')[2] # load episode episodes_list = [episode] for episode in episodes_list: print("\nCurrent Episode :", episode) # process serie or film if len(episode.split('.')) == 3: series, _, _ = episode.split('.') elif len(episode.split('.')) == 2: series, _ = episode.split('.') # load mkv, aligned file & aligned sentences mkv, aligned, sentences = load_files(series, episode, DATA_PLUMCOT) # criteria : nouns or pronouns to display automaticaly pronouns = ["he", "she", "his", "her", "himself", "herself", "him"] nouns = ["mother", "son", "daughter", "wife", "husband", "father", "uncle", "cousin", "aunt", "brother", "sister"] # store sentence id with criteria position(s) (PROPN or criteria list) store_ids = {} # labels to feed in Prodigy labels = [] # for each sentence with criteria, store idx and positions for idx, sentence in enumerate(sentences) : # store word position with criteria store_position = [] for token in sentence: # check if it is a PRON or DET if str(token).lower() in pronouns : # check if entity_linking field is empty if token._.entity_linking == "_" or token._.entity_linking == "?": store_position.append(str(sentence).split().index(str(token))) # check if it is a name if token.pos_ == "PROPN": if str(token) != "ve" and str(token) != "m" and str(token)[0].isupper(): # check if entity_linking field is empty if token._.entity_linking == "_" or token._.entity_linking == "?": store_position.append(str(sentence).split().index(str(token))) # check if it is in nouns if str(token).lower() in nouns : # check if entity_linking field is empty if token._.entity_linking == "_" or token._.entity_linking == "?": store_position.append(str(sentence).split().index(str(token))) # keep sentence id, tokens positions, sentence id store_ids[idx] = (store_position, sentence) # process sentences for prodigy for i,j in store_ids.items(): to_return = {"text":''} # tokens displayed in Prodigy tokens = [] # spans for EL spans = [] # character counter in the text start = 0 # word id ids = 0 #if previous != None and nexts != None: if j[0]: #print(sentences[i]) to_return['text'] += str(sentences[i]) print(i, to_return['text']) # get tokens for word in str(sentences[i]).split(' '): # do no add +1 to start counter for last word if "\n" in word : tokens.append({"text": str(word), "start": start , "end": len(str(word))+start-1, "id": ids, "ws": True}) else : tokens.append({"text": str(word), "start": start , "end": len(str(word))+start, "id": ids, "ws": True}) start+= len(str(word))+1 # change start token for next word ids+=1 to_return["tokens"] = tokens # get spans for position in j[0]: for dic in tokens: if position == dic["id"]: #print("FIND TOKEN",dic["text"]) #print(dic["start"], dic["end"]) corresponding_token = to_return["text"][dic["start"]:dic["end"]].lower() spans.append({"start" : dic["start"], "end" : dic["end"], "token_start": position, "token_end":position, "label": "EL1"}) to_return["spans"] = spans # get characters of the show with open(f"{DATA_PLUMCOT}/{series}/characters.txt", "r") as f: speakers = [line.split(",")[0] for line in f.readlines()] # get video (add context) try : if i not in range(0,2): start_left = sentences[i-2] end_left = sentences[i] # beug : left index = last sentence index in the list when current sentence is 0 else: start_left = None end_left = sentences[i] except IndexError: start_left = None end_left = None # video if start_left != None and end_left != None: start_time = start_left._.start_time end_time= end_left._.end_time +0.1 else: start_time = j[1]._.start_time end_time = j[1]._.end_time +0.1 # corresponding video excerpt video_excerpt = mkv_to_base64(mkv, start_time, end_time+0.01) to_return["field_id"] = "entity", to_return["field_placeholder"] = "firstname_lastname", to_return["field_rows"] = 1, to_return["field_suggestions"] = speakers to_return["sentence"] = str(j[1]) to_return["start_time"] = j[1]._.start_time to_return["end_time"] = j[1]._.end_time to_return["meta"] = {"episode": episode, "sentence_id": f"{i}", "processing":f"{i}/{len(sentences)}"} to_return["video"] = video_excerpt yield to_return @prodigy.recipe("entity_linking", dataset=("The dataset to save to", "positional", None, str), episode=("Episode to annotate (e.g : TheWalkingDead.Season01.Episode01", "positional", None, str), user_path=("Path to Plumcot corpora", "positional", None, str), ) def addresse(dataset: Text, episode: Text, user_path: Text) -> Dict: blocks = [ {"view_id": "audio"}, {"view_id": "relations"},{"view_id": "text_input", "field_id": "input_1", "field_placeholder":"Type here for EL1..."},{"view_id": "text_input", "field_id": "input_2", "field_placeholder":"Type here for EL2..."}, {"view_id": "text_input", "field_id": "input_3", "field_placeholder":"Type here for EL3..."}, ] stream = entity_linking(episode, user_path) return { "dataset": dataset, "view_id": "blocks", "stream": stream, "before_db": remove_video_before_db, "config": { "blocks": blocks, "wrap_relations" : True, # apply line breaks "hide_newlines": True, "audio_loop": False, "audio_autoplay": True, "show_audio_minimap": False, "show_audio_timeline": False, "show_audio_cursor": False, "relations_span_labels" : ["EL1", "EL2", "EL3"], "field_autofocus" : False, }, }
39.422907
335
0.519835
0
0
6,216
0.694603
1,409
0.157448
0
0
3,197
0.357247
69f2d82b9190c2480e72ca0c8018cad49bc3a03e
3,326
py
Python
sandbox_code/viz_dashboard.py
liuvictoria/sleepingbeauty
e165bea614d58ddd2c5c2a860df622241065cf47
[ "MIT" ]
null
null
null
sandbox_code/viz_dashboard.py
liuvictoria/sleepingbeauty
e165bea614d58ddd2c5c2a860df622241065cf47
[ "MIT" ]
null
null
null
sandbox_code/viz_dashboard.py
liuvictoria/sleepingbeauty
e165bea614d58ddd2c5c2a860df622241065cf47
[ "MIT" ]
null
null
null
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.3' # jupytext_version: 0.8.6 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import warnings import pandas as pd import numpy as np import scipy.stats as st import iqplot import bebi103 import bokeh.io bokeh.io.output_notebook() import holoviews as hv hv.extension('bokeh') import panel as pn import tidy_data data_path = "../data/" rg = np.random.default_rng() # + ########## # Don't comment out!!1!! ########## df = tidy_data.tidy_concentrations() #made ndarrays of various concentrations concentrations = df.concentration.unique() #make ndarrays of catastrophe times for different concentrations #catastrophe_times[0] is for the lowest concentration, while cat_times[4] is for the highest concentration catastrophe_times = np.array([ df.loc[df['concentration'] == concent, 'catastrophe time'] for concent in df.concentration.unique() ]) # + def plot_overlaid_ecdfs(alpha, time, concentration): """ ecdfs of catastrophe times, colored by concentration also includes gamma distribution overlaid Output: bokeh figure object """ if concentration != 'all': sub_df = df.loc[df['concentration_int'] == concentration] else: sub_df = df #plot actual data p = iqplot.ecdf( data = sub_df, q = 'catastrophe time', cats = 'concentration', marker_kwargs=dict(line_width=0.3, alpha = 0.6), show_legend = True, palette=bokeh.palettes.Magma8[1:-2][::-1], tooltips=[ ('concentration', '@{concentration}'), ('catastrophe time', '@{catastrophe time}') ], ) p.xaxis.axis_label = "catastrophe times (s)" #get points to plot line x = np.linspace(0, 2000) y = st.gamma.cdf(x, alpha, scale=time) #overlay ecdf, can be scaled by widgets p.line( x = x, y = y, color = 'yellowgreen', width = 3 ) p.title.text = 'ECDF of catastrophe times by concentration' return p # #uncomment to show # p = plot_exploratory_ecdfs() # bokeh.io.show(p) # + alpha_slider = pn.widgets.FloatSlider( name='alpha', start=1.8, end=4.2, step=0.1, value=2.4075 ) time_slider = pn.widgets.FloatSlider( name='average interarrival time (s)', start=75, end=215, step=10, value=1 / 0.005462 ) concentration_slider = pn.widgets.Select( name='concentration (uM)', options=[7, 9, 10, 12, 14, 'all',], value = 'all', ) # - @pn.depends( alpha=alpha_slider.param.value, time=time_slider.param.value, concentration = concentration_slider.param.value ) def plot_overlaid_ecdfs_pn(alpha, time, concentration): return plot_overlaid_ecdfs(alpha, time, concentration) widgets = pn.Column(pn.Spacer(width=30), alpha_slider, time_slider, concentration_slider, width=500) panel = pn.Column(plot_overlaid_ecdfs_pn, widgets) panel.save('interactive', embed = True, max_opts = 40) def main(): p = plot_overlaid_ecdfs(2, 1 / .005, 'all') bokeh.io.show(p) return True if __name__ == '__main__': main() # + #!jupytext --to python viz_dashboard.ipynb
22.02649
106
0.643115
0
0
0
0
253
0.076067
0
0
1,226
0.368611
69f44d6bb0d219787fb8b38bd11e93ce8f62ca75
1,694
py
Python
SCA11H/commands/bcg/RunCommand.py
ihutano/SCA11H
ee8a38ec9e47bc015851c20fa121651d2601cde0
[ "MIT" ]
null
null
null
SCA11H/commands/bcg/RunCommand.py
ihutano/SCA11H
ee8a38ec9e47bc015851c20fa121651d2601cde0
[ "MIT" ]
null
null
null
SCA11H/commands/bcg/RunCommand.py
ihutano/SCA11H
ee8a38ec9e47bc015851c20fa121651d2601cde0
[ "MIT" ]
null
null
null
from enum import Enum import json from SCA11H.commands.base.PostCommand import PostCommand class Command(Enum): # Restore BCG factory settings.(BCG parameters, direction and running mode) Restore = ('restore', 'restore') # Restore default BCG parameters SetDefaultParameters = ('set_default_pars', 'reset-parameters') class RunCommand(PostCommand): """ Run a BCG command """ def __init__(self, command: Command, **kwargs): super().__init__(endpoint='/bcg/cmd', payload=json.dumps({"cmd": command.value[0]}), **kwargs) @staticmethod def get_parser_name(): return 'run-bcg-command' @staticmethod def get_help(): return 'Run a BCG command' @staticmethod def add_arguments(parser): subparsers = parser.add_subparsers(title='bcg-command', dest='bcg_command', help='BCG Command to run') subparsers.add_parser(Command.Restore.value[1], help='Restore BCG factory settings.(BCG parameters, direction and running mode)') subparsers.add_parser(Command.SetDefaultParameters.value[1], help='Restore default BCG parameters') @staticmethod def parse_arguments(args) -> dict: if args.bcg_command is None: raise Exception('Missing required argument: bcg-command') elif args.bcg_command == Command.Restore.value[1]: command = Command.Restore elif args.bcg_command == Command.SetDefaultParameters.value[1]: command = Command.SetDefaultParameters else: raise Exception('Invalid argument: bcg-command') return {'command': command}
33.88
111
0.652302
1,596
0.942149
0
0
1,063
0.627509
0
0
470
0.27745
69f45cc29efc997451ff86c0a0f571e78b3958e7
125
py
Python
tridu_py3.py
YuriSerrano/URI-1933
58fdc5e90293ef55afacb164b955551a72a81d78
[ "MIT" ]
null
null
null
tridu_py3.py
YuriSerrano/URI-1933
58fdc5e90293ef55afacb164b955551a72a81d78
[ "MIT" ]
null
null
null
tridu_py3.py
YuriSerrano/URI-1933
58fdc5e90293ef55afacb164b955551a72a81d78
[ "MIT" ]
null
null
null
import sys ''' Criado por Yuri Serrano ''' a,b = input().split() a = int(a) b = int(b) if b > a: print(b) else: print(a)
8.928571
23
0.568
0
0
0
0
0
0
0
0
31
0.248
69f7bdeeb4b750efdf8582dd89ae606aafbd7ff2
14,595
py
Python
qt4c/keyboard.py
zhangyiming07/QT4C
2d8d60efe0a4ad78a2618c5beeb0c456a63da067
[ "BSD-3-Clause" ]
53
2020-02-20T06:56:03.000Z
2022-03-03T03:09:25.000Z
qt4c/keyboard.py
zhangyiming07/QT4C
2d8d60efe0a4ad78a2618c5beeb0c456a63da067
[ "BSD-3-Clause" ]
6
2020-03-03T03:15:53.000Z
2021-01-29T02:24:06.000Z
qt4c/keyboard.py
zhangyiming07/QT4C
2d8d60efe0a4ad78a2618c5beeb0c456a63da067
[ "BSD-3-Clause" ]
17
2020-02-26T03:51:41.000Z
2022-03-24T02:23:51.000Z
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QT4C available. # Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD 3-Clause License is included in this file. # '''้”ฎ็›˜่พ“ๅ…ฅๆจกๅ— ''' import time import ctypes import win32con import win32api import sys from ctypes import wintypes import six _SHIFT = {'~' : '`', '!' : '1', '@' : '2','#' : '3', '$' : '4','%' : '5','^' : '6','&' : '7','*' : '8','(' : '9',')' : '0','_' : '-','+' : '=', '{' : '[','}' : ']','|' : '\\',':' : ';','"' : "'",'<' : ',','>' : '.','?' : '/'} _MODIFIERS = [ win32con.VK_SHIFT, win32con.VK_CONTROL, win32con.VK_MENU, win32con.VK_LWIN, win32con.VK_RWIN, ] _MODIFIER_KEY_MAP = { '+': win32con.VK_SHIFT, '^': win32con.VK_CONTROL, '%': win32con.VK_MENU, } #ESCAPEDS= '+%^{}' _CODES = { 'F1':112, 'F2':113, 'F3':114, 'F4':115, 'F5':116, 'F6':117, 'F7':118, 'F8':119, 'F9':120, 'F10':121, 'F11':122, 'F12':123, 'BKSP':8, 'TAB':9, 'ENTER':13, 'ESC':27, 'END':35, 'HOME':36,'INSERT':45, 'DEL':46, 'SPACE':32,'PGUP':33,'PGDN':34,'LEFT':37,'UP':38,'RIGHT':39,'DOWN':40,'PRINT':44, 'SHIFT':16, 'CTRL':17, 'MENU':18, 'ALT':18, 'APPS':93, 'CAPS':20, 'WIN':91, 'LWIN': 91, 'RWIN':92, 'NUM':144, 'SCRLK':145 } def _scan2vkey(scan): return 0xff & ctypes.windll.user32.VkKeyScanW(ctypes.c_wchar("%c" % scan)) #return 0xff & ctypes.windll.user32.VkKeyScanW(scan) class _KeyboardEvent(object): KEYEVENTF_EXTENDEDKEY = 1 KEYEVENTF_KEYUP = 2 KEYEVENTF_UNICODE = 4 KEYEVENTF_SCANCODE = 8 is_64bits = sys.maxsize > 2**32 MAPVK_VK_TO_VSC = 0 if is_64bits: wintypes.ULONG_PTR = wintypes.WPARAM class _MOUSEINPUT(ctypes.Structure): _fields_ = (("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", wintypes.ULONG_PTR)) class _HARDWAREINPUT(ctypes.Structure): _fields_ = (("uMsg", wintypes.DWORD), ("wParamL", ctypes.wintypes.WORD), ("wParamH", ctypes.wintypes.WORD)) class _KEYBDINPUT(ctypes.Structure): _fields_ = (("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", wintypes.ULONG_PTR)) def __init__(self, *args, **kwds): super(_KEYBDINPUT, self).__init__(*args, **kwds) # some programs use the scan code even if KEYEVENTF_SCANCODE # isn't set in dwFflags, so attempt to map the correct code. if not self.dwFlags & _KeyboardEvent.KEYEVENTF_UNICODE: self.wScan = ctypes.windll.user32.MapVirtualKeyExW(self.wVk, MAPVK_VK_TO_VSC, 0) class _UNION_INPUT_STRUCTS(ctypes.Union): "The C Union type representing a single Event of any type" _fields_ = [ ('mi', _MOUSEINPUT), ('ki', _KEYBDINPUT), ('hi', _HARDWAREINPUT), ] class _INPUT(ctypes.Structure): _anonymous_ = ("_",) _fields_ = (("type", wintypes.DWORD), ("_", _UNION_INPUT_STRUCTS)) LPINPUT = ctypes.POINTER(_INPUT) else: class _MOUSEINPUT(ctypes.Structure): _fields_ = [ ('dx', ctypes.c_long), ('dy', ctypes.c_long), ('mouseData', ctypes.c_ulong), ('dwFlags', ctypes.c_ulong), ('time', ctypes.c_ulong), ('dwExtraInfo', ctypes.c_ulong), ] class _HARDWAREINPUT(ctypes.Structure): _fields_ = [ ('uMsg', ctypes.c_ulong), ('wParamL', ctypes.c_ushort), ('wParamH', ctypes.c_ushort), ] class _KEYBDINPUT(ctypes.Structure): _fields_ = [ ('wVk', ctypes.c_ushort), ('wScan', ctypes.c_ushort), ('dwFlags', ctypes.c_ulong), ('time', ctypes.c_ulong), ('dwExtraInfo', ctypes.c_ulong), ] class _UNION_INPUT_STRUCTS(ctypes.Union): "The C Union type representing a single Event of any type" _fields_ = [ ('mi', _MOUSEINPUT), ('ki', _KEYBDINPUT), ('hi', _HARDWAREINPUT), ] class _INPUT(ctypes.Structure): _fields_ = [ ('type', ctypes.c_ulong), ('_', _UNION_INPUT_STRUCTS), ] class KeyInputError(Exception): '''้”ฎ็›˜่พ“ๅ…ฅ้”™่ฏฏ ''' pass class Key(object): '''ไธ€ไธชๆŒ‰้”ฎ ''' def __init__(self, key): '''Constructor :type key: number or charactor :param key: ๆŒ‰้”ฎ ''' self._flag = 0 self._modifiers = [] if isinstance(key, six.string_types): self._scan = ord(key) if self._scan < 256: #ASCII code self._vk = _scan2vkey(self._scan) if key.isupper() or key in _SHIFT: #ๆŒ‰ไธ‹shift้”ฎ self._modifiers.append(Key(_MODIFIER_KEY_MAP['+'])) else: #unicode self._vk = 0 self._flag |= _KeyboardEvent.KEYEVENTF_UNICODE elif isinstance(key, int): #virtual Key self._vk = key self._scan = ctypes.windll.user32.MapVirtualKeyW(self._vk, 0) if self._isExtendedKey(self._vk): self._flag |= _KeyboardEvent.KEYEVENTF_EXTENDEDKEY else: raise KeyInputError('Key is not a number or string') # ่‹ฅๆ˜ฏไปฅไธ‹่™šๆ‹Ÿ้”ฎๅˆ™้œ€่ฆๅŒๆญฅ # ๆš‚ๅชๅฏนๆœ€ไธป่ฆ็š„SHIFTใ€CTRLใ€ALT้”ฎ่ฟ›่กŒๅŒๆญฅ self._SyncVKeys = [win32con.VK_SHIFT, win32con.VK_LSHIFT, win32con.VK_RSHIFT, win32con.VK_CONTROL, win32con.VK_LCONTROL, win32con.VK_RCONTROL, win32con.VK_MENU, win32con.VK_LMENU, win32con.VK_RMENU] def appendModifierKey(self, key): '''Modifier Key comes with the key :type key: Key :param key: Ctrl, Shift or Atl Key ''' self._modifiers.append(key) def _isExtendedKey(self, vkey): if ((vkey >= 33 and vkey <= 46) or (vkey >= 91 and vkey <= 93) ): return True else: return False def _inputKey(self, up): inp = _INPUT() inp.type = 1 inp._.ki.wVk = self._vk inp._.ki.wScan = self._scan inp._.ki.dwFlags |= self._flag if up: inp._.ki.dwFlags |= _KeyboardEvent.KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(1,ctypes.byref(inp),ctypes.sizeof(_INPUT)) def inputKey(self): '''้”ฎ็›˜ๆจกๆ‹Ÿ่พ“ๅ…ฅๆŒ‰้”ฎ ''' for mkey in self._modifiers: mkey._inputKey(up=False) self._inputKey(up=False) self._inputKey(up=True) for mkey in self._modifiers: mkey._inputKey(up=True) def _postKey(self, hwnd, up): '''็ป™ๆŸไธช็ช—ๅฃๅ‘้€ๆŒ‰้’ฎ ''' if up: ctypes.windll.user32.PostMessageW(hwnd, win32con.WM_KEYUP, self._vk, self._scan <<16 | 0xc0000001) else: ctypes.windll.user32.PostMessageW(hwnd, win32con.WM_KEYDOWN, self._vk, self._scan<<16 | 1) time.sleep(0.01) #ๅฟ…้กปๅŠ ๏ผŒๅฆๅˆ™ๆœ‰ไบ›ๆŽงไปถๅ“ๅบ”ไธไบ†๏ผŒไผšไบง็”Ÿ้—ฎ้ข˜ def postKey(self, hwnd): '''ๅฐ†ๆŒ‰้”ฎๆถˆๆฏๅ‘ๅˆฐhwnd ''' for mkey in self._modifiers: mkey._inputKey(up=False) time.sleep(0.01) #ๅฟ…้กปๅŠ ๏ผŒๅฆๅˆ™ไธ‹้ขๅฎž้™…ๅฏ„้€็š„้”ฎ็›˜ๆŒ‰้”ฎๆถˆๆฏๅฏ่ƒฝๆฏ”่ฟ™ไธชๆถˆๆฏๆ›ดๅฟซๅˆฐ่พพ็›ฎๆ ‡็ช—ๅฃ if self._scan < 256: self._postKey(hwnd, up=False) self._postKey(hwnd, up=True) else: ctypes.windll.user32.PostMessageW(hwnd, win32con.WM_CHAR, self._scan, 1) for mkey in self._modifiers: mkey._inputKey(up=True) def _isPressed(self): """่ฏฅ้”ฎๆ˜ฏๅฆ่ขซๆŒ‰ไธ‹ """ if (win32api.GetAsyncKeyState(self._vk) & 0x8000) == 0: return False else: return True def _isToggled(self): """่ฏฅ้”ฎๆ˜ฏๅฆ่ขซๅผ€ๅฏ๏ผŒๅฆ‚Caps Lockๆˆ–Num Lock็ญ‰ """ if(win32api.GetKeyState(self._vk) & 1): return True else: return False class Keyboard(object): '''้”ฎ็›˜่พ“ๅ…ฅ็ฑป๏ผŒๅฎž็Žฐไบ†ไธค็ง้”ฎ็›˜่พ“ๅ…ฅๆ–นๅผใ€‚ ไธ€็ฑปๆ–นๆณ•ไฝฟ็”จๆจกๆ‹Ÿ้”ฎ็›˜่พ“ๅ…ฅ็š„ๆ–นๅผใ€‚ ๅฆไธ€็ฑปๆ–นๆณ•ไฝฟ็”จWindowsๆถˆๆฏ็š„ๆœบๅˆถๅฐ†ๅญ—็ฌฆไธฒ็›ดๆŽฅๅ‘้€็š„็ช—ๅฃใ€‚ ้”ฎ็›˜่พ“ๅ…ฅ็ฑปๆ”ฏๆŒไปฅไธ‹ๅญ—็ฌฆ็š„่พ“ๅ…ฅใ€‚ 1ใ€็‰นๆฎŠๅญ—็ฌฆ๏ผš^, +, %, {, } '^'่กจ็คบControl้”ฎ๏ผŒๅŒ'{CTRL}'ใ€‚'+'่กจ็คบShift้”ฎ๏ผŒๅŒ'{SHIFT}'ใ€‚'%'่กจ็คบAlt้”ฎ๏ผŒๅŒ'{ALT}'ใ€‚ '^', '+', '%'ๅฏไปฅๅ•็‹ฌๆˆ–ๅŒๆ—ถไฝฟ็”จ๏ผŒๅฆ‚'^a'่กจ็คบCTRL+a๏ผŒโ€™^%a'่กจ็คบCTRL+ALT+aใ€‚ {}๏ผš ๅคงๆ‹ฌๅท็”จๆฅ่พ“ๅ…ฅ็‰นๆฎŠๅญ—็ฌฆๆœฌ่บซๅ’Œ่™š้”ฎ๏ผŒๅฆ‚โ€˜{+}โ€™่พ“ๅ…ฅๅŠ ๅท๏ผŒ'{F1}'่พ“ๅ…ฅF1่™š้”ฎ๏ผŒ'{}}'่กจ็คบ่พ“ๅ…ฅ'}'ๅญ—็ฌฆใ€‚ 2ใ€ASCIIๅญ—็ฌฆ๏ผš้™คไบ†็‰นๆฎŠๅญ—็ฌฆ้œ€่ฆ๏ฝ›๏ฝๆฅ่ฝฌไน‰๏ผŒๅ…ถไป–ASCII็ ๅญ—็ฌฆ็›ดๆŽฅ่พ“ๅ…ฅ๏ผŒ 3ใ€Unicodeๅญ—็ฌฆ๏ผš็›ดๆŽฅ่พ“ๅ…ฅ๏ผŒๅฆ‚"ๆต‹่ฏ•"ใ€‚ 4ใ€่™š้”ฎ๏ผš {F1}, {F2},...{F12} {Tab},{CAPS},{ESC},{BKSP},{HOME},{INSERT},{DEL},{END},{ENTER} {PGUP},{PGDN},{LEFT},{RIGHT},{UP},{DOWN},{CTRL},{SHIFT},{ALT},{APPS}.. ๆณจๆ„๏ผšๅฝ“ไฝฟ็”จ่”ๅˆ้”ฎๆ—ถ๏ผŒๆณจๆ„ๆญค็ฑป็š„้—ฎ้ข˜,inputKeys('^W')ๅ’ŒinputKeys('%w')๏ผŒๅญ—ๆฏ'w'็š„ๅคงๅฐๅ†™ไบง็”Ÿ็š„ๆ•ˆๆžœๅฏ่ƒฝไธไธ€ๆ ท ''' _keyclass = Key _pressedkey = None @staticmethod def selectKeyClass(newkeyclass): oldkeyclass = Keyboard._keyclass Keyboard._keyclass = newkeyclass return oldkeyclass @staticmethod def _parse_keys(keystring): keys = [] modifiers = [] index = 0 while index < len(keystring): c = keystring[index] index += 1 # Escape or named key if c == "{": end_pos = keystring.find("}", index) if end_pos == -1: raise KeyInputError('`}` not found') elif end_pos == index and keystring[end_pos+1] == '}': #{}} index +=2 code = '}' else: code = keystring[index:end_pos] index = end_pos + 1 if code in _CODES.keys(): key = _CODES[code] elif len(code) == 1: key = code else: raise KeyInputError("Code '%s' is not supported" % code) # unmatched "}" elif c == '}': raise KeyInputError('`}` should be preceeded by `{`') elif c in _MODIFIER_KEY_MAP.keys(): key = _MODIFIER_KEY_MAP[c] # so it is a normal character else: key = c if key in _MODIFIERS : modifiers.append(key) else: akey = Keyboard._keyclass(key) for mkey in modifiers: akey.appendModifierKey(Keyboard._keyclass(mkey)) modifiers = [] keys.append(akey) for akey in modifiers: keys.append(Keyboard._keyclass(akey)) return keys @staticmethod def inputKeys(keys, interval=0.01): '''ๆจกๆ‹Ÿ้”ฎ็›˜่พ“ๅ…ฅๅญ—็ฌฆไธฒ :type keys: utf-8 str or unicode :param keys: ้”ฎ็›˜่พ“ๅ…ฅๅญ—็ฌฆไธฒ,ๅฏ่พ“ๅ…ฅ็ป„ๅˆ้”ฎ๏ผŒๅฆ‚"{CTRL}{MENU}a" :type interval: number :param interval: ่พ“ๅ…ฅ็š„ๅญ—็ฌฆๅ’Œๅญ—็ฌฆไน‹้—ด็š„ๆš‚ๅœ้—ด้š”ใ€‚ ''' if not isinstance(keys, six.text_type): keys = keys.decode('utf-8') keys = Keyboard._parse_keys(keys) for k in keys: k.inputKey() time.sleep(interval) @staticmethod def postKeys(hwnd, keys, interval=0.01): '''ๅฐ†ๅญ—็ฌฆไธฒไปฅ็ช—ๅฃๆถˆๆฏ็š„ๆ–นๅผๅ‘้€ๅˆฐๆŒ‡ๅฎšwin32็ช—ๅฃใ€‚ :type hwnd: number :param hwnd: windows็ช—ๅฃๅฅๆŸ„ :type keys: utf8 str ๆˆ–่€… unicode :param keys: ้”ฎ็›˜่พ“ๅ…ฅๅญ—็ฌฆไธฒ :type interval: number :param interval: ่พ“ๅ…ฅ็š„ๅญ—็ฌฆๅ’Œๅญ—็ฌฆไน‹้—ด็š„ๆš‚ๅœ้—ด้š”ใ€‚ ''' if not isinstance(keys, six.text_type): keys = keys.decode('utf-8') keys = Keyboard._parse_keys(keys) for k in keys: k.postKey(hwnd) time.sleep(interval) @staticmethod def pressKey(key): """ๆŒ‰ไธ‹ๆŸไธช้”ฎ """ if Keyboard._pressedkey: raise ValueError("ๅฐšๆœ‰ๆŒ‰้”ฎๆœช้‡Šๆ”พ,่ฏทๅ…ˆๅฏนๆŒ‰้”ฎ่ฟ›่กŒ้‡Šๆ”พ,ๆœช้‡Šๆ”พ็š„ๆŒ‰้”ฎไธบ: %s"%Keyboard._pressedkey) if not isinstance(key, six.text_type): key = key.decode('utf-8') keys = Keyboard._parse_keys(key) if len(keys) != 1: raise ValueError("่พ“ๅ…ฅๅ‚ๆ•ฐ้”™่ฏฏ,ๅชๆ”ฏๆŒ่พ“ๅ…ฅไธ€ไธช้”ฎ,key: %s"%key) keys[0]._inputKey(up=False) Keyboard._pressedkey = key @staticmethod def releaseKey(key=None): """้‡Šๆ”พไธŠไธ€ไธช่ขซๆŒ‰ไธ‹็š„้”ฎ """ #ๅŽ็ปญๆ”นๆˆไธๅธฆๅ‚ๆ•ฐ็š„๏ผŒๅฐ†้‡Šๆ”พไธŠไธ€ไธชๆŒ‰้”ฎ๏ผŒๆš‚ๆ—ถๅ…ผๅฎนไธ‹็Žฐๆœ‰็š„ไฝฟ็”จๆ–นๅผ if not Keyboard._pressedkey: raise Exception("ๆฒกๆœ‰ๅฏ้‡Šๆ”พ็š„ๆŒ‰้”ฎ") key = Keyboard._pressedkey if not isinstance(key, six.text_type): key = key.decode('utf-8') keys = Keyboard._parse_keys(key) if len(keys) != 1: raise ValueError("่พ“ๅ…ฅๅ‚ๆ•ฐ้”™่ฏฏ,ๅชๆ”ฏๆŒ่พ“ๅ…ฅไธ€ไธช้”ฎ,key: %s"%key) keys[0]._inputKey(up=True) Keyboard._pressedkey = None @staticmethod def isPressed(key): """ๆ˜ฏๅฆ่ขซๆŒ‰ไธ‹ """ if not isinstance(key, six.text_type): key = key.decode('utf-8') keys = Keyboard._parse_keys(key) if len(keys) != 1: raise ValueError("่พ“ๅ…ฅๅ‚ๆ•ฐ้”™่ฏฏ,ๅชๆ”ฏๆŒ่พ“ๅ…ฅไธ€ไธช้”ฎ,key: %s"%key) return keys[0]._isPressed() @staticmethod def clear(): """้‡Šๆ”พ่ขซๆŒ‰ไธ‹็š„ๆŒ‰้”ฎ """ if Keyboard._pressedkey: Keyboard.releaseKey() @staticmethod def isTroggled(key): """ๆ˜ฏๅฆๅผ€ๅฏ๏ผŒๅฆ‚Caps Lockๆˆ–Num Lock็ญ‰ """ if not isinstance(key, six.text_type): key = key.decode('utf-8') keys = Keyboard._parse_keys(key) if len(keys) != 1: raise ValueError("่พ“ๅ…ฅๅ‚ๆ•ฐ้”™่ฏฏ,ๅชๆ”ฏๆŒ่พ“ๅ…ฅไธ€ไธช้”ฎ,key: %s"%key) return keys[0]._isToggled() if __name__ == "__main__": pass
32.945824
144
0.505653
13,841
0.874076
0
0
5,324
0.336217
0
0
4,825
0.304705
69f9c87dea73354181eadb4afd02ba8d68d76483
1,168
py
Python
piptui/custom/apNPSApplicationEvents.py
UltraStudioLTD/PipTUI
62f5707faa004ba6d330288656ba192f37516921
[ "MIT" ]
33
2019-07-11T13:19:29.000Z
2022-02-23T12:42:22.000Z
piptui/custom/apNPSApplicationEvents.py
UltraStudioLTD/PipTUI
62f5707faa004ba6d330288656ba192f37516921
[ "MIT" ]
6
2019-07-20T21:21:51.000Z
2021-09-24T16:24:34.000Z
piptui/custom/apNPSApplicationEvents.py
UltraStudioLTD/PipTUI
62f5707faa004ba6d330288656ba192f37516921
[ "MIT" ]
8
2019-07-21T07:38:08.000Z
2021-11-11T13:30:45.000Z
import collections from npyscreen import StandardApp, apNPSApplicationEvents class PipTuiEvents(object): def __init__(self): self.interal_queue = collections.deque() super(apNPSApplicationEvents).__init__() def get(self, maximum=None): if maximum is None: maximum = -1 counter = 1 while counter != maximum: try: yield self.interal_queue.pop() except IndexError: pass counter += 1 class PipTuiApp(StandardApp): def __init__(self): super(StandardApp, self).__init__() self.event_directory = {} self.event_queues = {} self.initalize_application_event_queues() self.initialize_event_handling() def process_event_queues(self, max_events_per_queue=None): for queue in self.event_queues.values(): try: for event in queue.get(maximum=max_events_per_queue): try: self.process_event(event) except StopIteration: pass except RuntimeError: pass
28.487805
69
0.576199
1,084
0.928082
276
0.236301
0
0
0
0
0
0
69fa2fbc965cdaf80ea59da7e32e4769409474b2
146
py
Python
web/apps.py
jakubhyza/kelvin
b06c0ed0594a3fb48df1e50ff30cee010ddeea5a
[ "MIT" ]
8
2020-01-11T15:25:25.000Z
2022-02-20T17:32:58.000Z
web/apps.py
jakubhyza/kelvin
b06c0ed0594a3fb48df1e50ff30cee010ddeea5a
[ "MIT" ]
72
2020-01-13T21:07:26.000Z
2022-03-28T10:17:50.000Z
web/apps.py
jakubhyza/kelvin
b06c0ed0594a3fb48df1e50ff30cee010ddeea5a
[ "MIT" ]
6
2020-01-11T16:50:04.000Z
2022-02-19T10:12:19.000Z
import logging from django.apps import AppConfig class WebConfig(AppConfig): name = 'web' def ready(self): import web.signals
13.272727
33
0.684932
93
0.636986
0
0
0
0
0
0
5
0.034247
69fb23cad56b8f09159f3a77a81d10b8408a289b
72
py
Python
audiotrans_transform_stft/__init__.py
keik/audiotrans-transform-stft
76db56dd78589170ea58bd59f8243dee76373ced
[ "MIT" ]
null
null
null
audiotrans_transform_stft/__init__.py
keik/audiotrans-transform-stft
76db56dd78589170ea58bd59f8243dee76373ced
[ "MIT" ]
null
null
null
audiotrans_transform_stft/__init__.py
keik/audiotrans-transform-stft
76db56dd78589170ea58bd59f8243dee76373ced
[ "MIT" ]
null
null
null
from .__main__ import STFTTransform __all__ = [ 'STFTTransform' ]
10.285714
35
0.708333
0
0
0
0
0
0
0
0
15
0.208333
69fbff5bd4e44ca32652d5e034cc628db3597195
544
py
Python
reformat/reformat-gexpnn-preds-STEP1B.py
jordan2lee/gdan-tmp-webdash
96f8a557bcbca597a816a98824fbc37a174ae838
[ "MIT" ]
null
null
null
reformat/reformat-gexpnn-preds-STEP1B.py
jordan2lee/gdan-tmp-webdash
96f8a557bcbca597a816a98824fbc37a174ae838
[ "MIT" ]
null
null
null
reformat/reformat-gexpnn-preds-STEP1B.py
jordan2lee/gdan-tmp-webdash
96f8a557bcbca597a816a98824fbc37a174ae838
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import pandas as pd ft_input='TEMP_DIR/tmp-predictions_reformatted_gexpnn20200320allCOHORTS.tsv' df = pd.read_csv(ft_input,sep='\t') # Get all tumors present in df (ACC, BRCA, ...) temp = df['Label'].unique() u_tumor = {} #k=tumor, v=1 for t in temp: t= t.split(":")[0] if t not in u_tumor: u_tumor[t]=1 # write out files for each tumor for t in u_tumor: print('starting ', t) subset = df[df['Label'].str.contains(t)] subset.to_csv('TEMP_DIR/intermediat-'+t+".tsv",sep='\t',index=False)
24.727273
76
0.658088
0
0
0
0
0
0
0
0
246
0.452206
69fc9eb460e76e55a0c0964c725759eeda16183f
4,291
py
Python
src/genie/libs/parser/iosxr/tests/ShowIsisSpfLogDetail/cli/equal/golden_output_1_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
204
2018-06-27T00:55:27.000Z
2022-03-06T21:12:18.000Z
src/genie/libs/parser/iosxr/tests/ShowIsisSpfLogDetail/cli/equal/golden_output_1_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
468
2018-06-19T00:33:18.000Z
2022-03-31T23:23:35.000Z
src/genie/libs/parser/iosxr/tests/ShowIsisSpfLogDetail/cli/equal/golden_output_1_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
309
2019-01-16T20:21:07.000Z
2022-03-30T12:56:41.000Z
expected_output = { 'instance': { 'isp': { 'address_family': { 'IPv4 Unicast': { 'spf_log': { 1: { 'type': 'FSPF', 'time_ms': 1, 'level': 1, 'total_nodes': 1, 'trigger_count': 1, 'first_trigger_lsp': '12a5.00-00', 'triggers': 'NEWLSP0', 'start_timestamp': 'Mon Aug 16 2004 19:25:35.140', 'delay': { 'since_first_trigger_ms': 51, }, 'spt_calculation': { 'cpu_time_ms': 0, 'real_time_ms': 0, }, 'prefix_update': { 'cpu_time_ms': 1, 'real_time_ms': 1, }, 'new_lsp_arrivals': 0, 'next_wait_interval_ms': 200, 'results': { 'nodes': { 'reach': 1, 'unreach': 0, 'total': 1, }, 'prefixes': { 'items': { 'critical_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'high_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'medium_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'low_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'all_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, }, 'routes': { 'critical_priority': { 'reach': 0, 'total': 0, }, 'high_priority': { 'reach': 0, 'total': 0, }, 'medium_priority': { 'reach': 0, 'total': 0, }, 'low_priority': { 'reach': 0, 'total': 0, }, 'all_priority': { 'reach': 0, 'total': 0, }, }, }, }, }, }, }, }, }, }, }
44.697917
78
0.158471
0
0
0
0
0
0
0
0
772
0.179911
69fdb392e5a9d445b9e1b7aaaada984049564da4
2,706
py
Python
monai/networks/utils.py
loftwah/MONAI
37fb3e779121e6dc74127993df102fc91d9065f8
[ "Apache-2.0" ]
1
2020-04-23T13:05:29.000Z
2020-04-23T13:05:29.000Z
monai/networks/utils.py
tranduyquockhanh/MONAI
37fb3e779121e6dc74127993df102fc91d9065f8
[ "Apache-2.0" ]
null
null
null
monai/networks/utils.py
tranduyquockhanh/MONAI
37fb3e779121e6dc74127993df102fc91d9065f8
[ "Apache-2.0" ]
1
2021-09-20T12:10:01.000Z
2021-09-20T12:10:01.000Z
# Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Utilities and types for defining networks, these depend on PyTorch. """ import warnings import torch import torch.nn.functional as f def one_hot(labels, num_classes): """ For a tensor `labels` of dimensions B1[spatial_dims], return a tensor of dimensions `BN[spatial_dims]` for `num_classes` N number of classes. Example: For every value v = labels[b,1,h,w], the value in the result at [b,v,h,w] will be 1 and all others 0. Note that this will include the background label, thus a binary mask should be treated as having 2 classes. """ num_dims = labels.dim() if num_dims > 1: assert labels.shape[1] == 1, 'labels should have a channel with length equals to one.' labels = torch.squeeze(labels, 1) labels = f.one_hot(labels.long(), num_classes) new_axes = [0, -1] + list(range(1, num_dims - 1)) labels = labels.permute(*new_axes) if not labels.is_contiguous(): return labels.contiguous() return labels def slice_channels(tensor, *slicevals): slices = [slice(None)] * len(tensor.shape) slices[1] = slice(*slicevals) return tensor[slices] def predict_segmentation(logits, mutually_exclusive=False, threshold=0): """ Given the logits from a network, computing the segmentation by thresholding all values above 0 if multi-labels task, computing the `argmax` along the channel axis if multi-classes task, logits has shape `BCHW[D]`. Args: logits (Tensor): raw data of model output. mutually_exclusive (bool): if True, `logits` will be converted into a binary matrix using a combination of argmax, which is suitable for multi-classes task. Defaults to False. threshold (float): thresholding the prediction values if multi-labels task. """ if not mutually_exclusive: return (logits >= threshold).int() else: if logits.shape[1] == 1: warnings.warn('single channel prediction, `mutually_exclusive=True` ignored, use threshold instead.') return (logits >= threshold).int() return logits.argmax(1, keepdim=True)
39.794118
115
0.698817
0
0
0
0
0
0
0
0
1,763
0.651515
69ff596252a8b8e113d28bd580c7b37e667bbc98
5,670
py
Python
Python/Newton_Raphson/newraph.py
manas0522/sci-cpy
0fad37f577e6a744717b0185c5bcfffcc72bc5ee
[ "MIT" ]
8
2021-09-26T17:41:04.000Z
2021-10-17T14:07:22.000Z
Python/Newton_Raphson/newraph.py
manas0522/sci-cpy
0fad37f577e6a744717b0185c5bcfffcc72bc5ee
[ "MIT" ]
16
2021-09-29T15:15:33.000Z
2021-11-27T04:35:37.000Z
Python/Newton_Raphson/newraph.py
manas0522/sci-cpy
0fad37f577e6a744717b0185c5bcfffcc72bc5ee
[ "MIT" ]
11
2021-09-27T09:46:38.000Z
2022-02-22T13:42:55.000Z
# This file is also a independently runnable file in addition to being a module. # You can run this file to test NewRaphAlgorithm function. ''' This program demonstrates Newton Raphson Algorithm(NPA). It is advised to follow all rules of the algorithm while entering the input. (Either read rules provided in README.md or search online) Program will cause an error in case any of the algorithm rules are not obeyed. Simply import NewRaphAlgorithm function in any program to use this algorithm to find roots of a math function. This program has a dependency on SymPy library. We used Sympy library here to convert math function in string form into a solvable function and to differentiate that function. NewRaphAlgorithm function accepts only a string as the math function, a float as root nearpoint and an integer as no. of decimal places of approximation (Any float provided will be converted to a whole number). Some non-algorithmic rules particular to ths module are: 1- There should always be a '*' sign between any number and variable or brackets. For Example: 'x^2-4x-7' is not allowed. Write it as 'x^2-4*x-7'. Also, '4(x+2)' is not allowed. Write it as '4*(x+2)' 2- Multiple alphabets together are considered as one variable. For Example: '2*kite' is considered same as '2*x'. NOTE- ITS NOT THAT I AM 100% SURE THAT THIS PROGRAM IS COMPLETELY BUG FREE, BUT I HAVE FIXED A PRETTY GOOD CHUNK OF THEM. BUT IF STILL A BUG IS FOUND THAT MEANS I DIDN'T ENCOUNTER THAT BUG IN MY TESTING. I TESTED THIS PROGRAM WITH OVER A 100 POLYNOMIALS.''' # Importing SymPy library functions from sympy import sympify, diff # Creating a custom error for this program. This helps the user to pinpoint the exact problem class New_Raph_Error(Exception): pass # Defining a function for Newton Raphson Algorithm (NRA). # This accepts a string as the math function, a float as root nearpoint, an integer as no. of decimal places of approximation. def NewRaphAlgorithm(equation, nearpoint, decimal= 3): try: #Checking invaild input decimal = abs(int(decimal)) except (TypeError, ValueError): raise New_Raph_Error('Only whole numbers are accepted as decimal places') try: #Checking invaild input nearpoint = float(nearpoint) except (TypeError, ValueError): raise New_Raph_Error('Only rational numbers are accepted as root nearpoint') try: #Checking invaild input equation = str(equation) equation = sympify(equation) except: raise New_Raph_Error("Please use '*' between any number and variable or brackets.") try: #Checking invaild input diff_equation = diff(equation) #Differentiation of given equation except ValueError: raise New_Raph_Error('Newton Raphson Method can solve only one variable polynomials') try: #Checking invaild input var = list(equation.free_symbols)[0] except IndexError: raise New_Raph_Error('A number has been entered instead of a equation') #Checking invaild input if float(diff_equation.subs(var, nearpoint)) == 0: raise New_Raph_Error('Root assumption provided is either on maxima or minima of the function') prev_np = None #Declaring previous nearpoint for comparison with nearpoint in NRA # Looping through actual Algorithm x=0 while x<1000 and prev_np != nearpoint and nearpoint != float('nan'): eq = float(equation.subs(var, nearpoint)) #Solving given function by substituting nearpoint diff_eq = float(diff_equation.subs(var, nearpoint)) #Solving differentiated function similarly prev_np = nearpoint try: nearpoint = nearpoint - (eq/diff_eq) #Formula for NRA except ZeroDivisionError: return prev_np nearpoint = round(nearpoint, decimal) #Rounding answer to the number of decimal places given x+=1 # Post Algorithm result validity checking if nearpoint == float('nan'): raise New_Raph_Error('''There is a local minima or maxima or a point of inflection around root assumption provided and nearest root value''') elif x==1000: raise New_Raph_Error('''Entered polynomial doesn't have any real root''') else: return nearpoint #-------------------------------------------------NRA Module Ends Here-------------------------------------------------------- # The code following is a sample execution program for NRA. # Anything folllowing will only execute if this file is run directly without importing. if __name__ == '__main__': print('''This program demonstrates Newton Raphson Algorithm. It is advised to follow all rules of the algorithm while entering the input. Program will cause an error in case any of the algorithm rules are not obeyed. There should always be a '*' sign between any number and variable. E.g.- 'x^2-4x-7' is not allowed. Write it as 'x^2-4*x-7'. Multiple alphabets together are considered as one variable. E.g.- '2*kite' is considered same as '2*x'.\n''') equation = input('Enter a one variable polynomial: ') nearpoint = input('Enter value of a number close to a root: ') decimal = input('Enter the no. of decimal places for the appoximation of the root: ') print(f'\nOne of the roots of given function is: {NewRaphAlgorithm(equation, nearpoint, decimal)}') # Created by Chaitanya Lakhchaura (aka ZenithFlux on github- https://github.com/ZenithFlux/)
45.36
135
0.687302
51
0.008995
0
0
0
0
0
0
3,993
0.704233
0e0038faf589bc3f8391d7469e67376d79fd62bf
1,656
py
Python
scripts/conteo_go.py
Carlosriosch/BrucellaMelitensis
4f16755fbb3e3ba33010d1e0d9fa68803b377075
[ "MIT" ]
null
null
null
scripts/conteo_go.py
Carlosriosch/BrucellaMelitensis
4f16755fbb3e3ba33010d1e0d9fa68803b377075
[ "MIT" ]
null
null
null
scripts/conteo_go.py
Carlosriosch/BrucellaMelitensis
4f16755fbb3e3ba33010d1e0d9fa68803b377075
[ "MIT" ]
null
null
null
from __future__ import division from collections import Counter import numpy as np import glob path_input = "../GO_analysis_PPI_Brucella/2.GO_crudos_y_ancestors/" path_output = "../GO_analysis_PPI_Brucella/3.GO_proporciones/" files = glob.glob(path_input + "*CON_GEN_ID_ancestors*.txt") for f in files: # esta etiqueta la voy a usar para darle nombre a los txt de output. # notar que tire el 0.2 que tenia. De todos modos habria que simplificar la nomenclatura etiqueta = f.split('.', -1)[-2] # cargo un file y cuento cuantos hay de cada cosa data = np.loadtxt(f, dtype = 'str', delimiter = '\n') # data es una lista que tiene en cada casillero varios GO. Agarro cada casillero y hago un split de todos los terminos. Luego junto todo en una sola lista. lista = [] sublista = [] for d in data: sublista.append(d.split()) for s in sublista: for ss in s: lista.append(ss) # ahora cuento las ocurrencias de cada termino. Diccionario que tiene el GO term con la cantidad de ocurrencias cuentas = Counter(lista) # para dar la proporcion, calculo la cantidad de elementos size = len(lista) proporciones = {} for c in cuentas: proporciones[c] = cuentas[c] #print(c, cuentas[c]) # ordeno proporciones = sorted(proporciones.items(), key=lambda kv: kv[1]) proporciones = proporciones[::-1] # ahora lo escribo results = open(path_output + etiqueta + "_proporciones.txt", "w") results.write("GO term\t\tocurrencias\n") for p in proporciones: results.write("%s\t%d\n" % (p[0], p[1])) results.close()
31.245283
159
0.667271
0
0
0
0
0
0
0
0
776
0.468599
0e00c3eb801451c1ce0627716ddfcc5cdd941f89
988
py
Python
gmgc.analysis/strict-species.py
luispedro/Coelho2021_GMGCv1_analysis
5f1a62844631121cc11f8ac5a776d25baca56ff7
[ "MIT" ]
6
2021-12-16T09:20:28.000Z
2022-03-29T03:21:48.000Z
gmgc.analysis/strict-species.py
luispedro/Coelho2021_GMGCv1_analysis
5f1a62844631121cc11f8ac5a776d25baca56ff7
[ "MIT" ]
1
2022-02-18T01:56:56.000Z
2022-02-22T14:39:48.000Z
gmgc.analysis/strict-species.py
luispedro/Coelho2021_GMGCv1_analysis
5f1a62844631121cc11f8ac5a776d25baca56ff7
[ "MIT" ]
8
2021-12-17T02:14:50.000Z
2022-03-21T06:40:59.000Z
from itertools import groupby from taxonomic import lca from taxonomic import ncbi n = ncbi.NCBI() def read_relationships(): for line in open('cold/GMGC.relationships.txt'): a,_,b = line.rstrip().split() yield a,b fr12name = {} for line in open('cold/freeze12.rename.table'): i,g,_ = line.strip().split('\t',2) fr12name[i] = g rename = {} for line in open('cold/GMGC10.rename.table.txt'): new,old = line.rstrip().split() rename[old] = new with open('GMGC10.inner.taxonomic.map', 'wt') as output: for g,origs in groupby(read_relationships(), lambda a_b:a_b[1]): fr_genes = [o for o,_ in origs if o.startswith('Fr12_')] if fr_genes: classif = lca.lca([n.path(fr12name[f].split('.')[0]) for f in fr_genes]) classif = classif[-1] sp = n.at_rank(classif, 'species') if sp: output.write('\t'.join([g, rename[g], classif, sp])) output.write('\n')
31.870968
84
0.593117
0
0
134
0.135628
0
0
0
0
150
0.151822
0e01f695cd84ecfecf18aacb3df164a4f595c65f
1,001
py
Python
spreadsheet2csv.py
kamimura/py-spreadsheet2csv
135b703906e41d92b34b2444ba392974abf97674
[ "MIT" ]
null
null
null
spreadsheet2csv.py
kamimura/py-spreadsheet2csv
135b703906e41d92b34b2444ba392974abf97674
[ "MIT" ]
null
null
null
spreadsheet2csv.py
kamimura/py-spreadsheet2csv
135b703906e41d92b34b2444ba392974abf97674
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import openpyxl import csv path = os.curdir if len(sys.argv) > 1: path = sys.argv[1] for excel_file in os.listdir(path): if (not os.path.isfile(excel_file)) or not excel_file.endswith('.xlsx'): continue print('{0}: Writing to csv...'.format(excel_file)) wb = openpyxl.load_workbook(excel_file) excel_filename = excel_file[:-5] for sheet_name in wb.get_sheet_names(): sheet = wb.get_sheet_by_name(sheet_name) csv_filename = '{0}_{1}.csv'.format(excel_filename, sheet_name) with open(csv_filename, 'w', newline='') as f: writer = csv.writer(f) for row_num in range(1, sheet.max_row + 1): row_data = [] for col_num in range(1, sheet.max_column + 1): row_data.append( sheet.cell(row=row_num, column=col_num).value ) writer.writerow(row_data)
32.290323
76
0.591409
0
0
0
0
0
0
0
0
94
0.093906
0e026ffcf7e117885cffc525c99c91ed9f7c0054
5,132
py
Python
thecube/fortnitecube.py
martinohanlon/thecube
41f7788cc0a754f3fc380d6a9db2fe1672d4b941
[ "MIT" ]
2
2021-12-27T18:19:46.000Z
2021-12-27T18:19:47.000Z
thecube/fortnitecube.py
martinohanlon/thecube
41f7788cc0a754f3fc380d6a9db2fe1672d4b941
[ "MIT" ]
null
null
null
thecube/fortnitecube.py
martinohanlon/thecube
41f7788cc0a754f3fc380d6a9db2fe1672d4b941
[ "MIT" ]
null
null
null
from gpiozero import Button from time import sleep, time import blinkt import random import requests import sys from constants import * FNT_URL = "https://api.fortnitetracker.com/v1/profile/{}/{}" FNT_REFRESH_TIME_SECS = 30 # debug shorter refresh # FNT_REFRESH_TIME_SECS = 10 class FortniteAPIError(Exception): pass class FortniteResponseError(Exception): pass def get_lifetime_wins(): header = {"TRN-Api-Key": FNT_API_KEY} url = FNT_URL.format("all", FN_PLAYER) response = requests.get(url, headers=header) # debug # print(response) # print(response.headers) # with open("response.txt", "w") as f: # f.write(response.text) if response.status_code != 200: raise FortniteResponseError("HTTP Status {}".format(response.status_code)) # check its a valid json response try: response.json() except ValueError: raise FortniteAPIError("Invalid JSON response") # check for errors if "error" in response.json().keys(): raise FortniteAPIError(response.json()["error"]) # get the stats life_time_stats = response.json()["lifeTimeStats"] # debug # print(life_time_stats) response.close() # convert key value pair to a dictionary data = {} for stat in life_time_stats: if stat["value"].isnumeric(): stat["value"] = int(stat["value"]) data[stat["key"]] = stat["value"] return data def on(r=255, g=255, b=255): blinkt.set_all(r, g, b) blinkt.show() def off(): blinkt.clear() blinkt.show() def flash(r, g, b, times, delay): for i in range(times): blinkt.set_all(r, g, b) blinkt.show() sleep(delay) off() sleep(delay) def crazy_lights(min_leds, max_leds, r1, r2, g1, g2, b1, b2, length, delay): start_time = time() while time() - start_time < length: # how many pixels pixels = random.sample(range(blinkt.NUM_PIXELS), random.randint(min_leds, max_leds)) for pixel in range(blinkt.NUM_PIXELS): r, g, b = random.randint(r1,r2), random.randint(g1,g2), random.randint(b1,b2) if pixel in pixels: # blinkt.set_pixel(pixel, random.randint(r1,r2), random.randint(g1,g2), random.randint(b1,b2)) blinkt.set_pixel(pixel, r, g, b) else: blinkt.set_pixel(pixel, 0, 0, 0) blinkt.show() sleep(delay) def run_cube(): # check connection on(0, 255, 0) prev_life_time_wins = get_lifetime_wins() flash(0, 255, 0, 3, 0.25) # start on() next_check = time() + FNT_REFRESH_TIME_SECS while switch.is_pressed: # debug with button # while not switch.is_pressed: sleep(0.1) if time() > next_check: life_time_wins = get_lifetime_wins() # debug # print(life_time_wins) # check a win if life_time_wins["Wins"] > prev_life_time_wins["Wins"]: crazy_lights(5, 8, 0, 255, 0, 255, 0, 255, 60, 0.1) print("Wins") on() # check a high position elif life_time_wins["Top 3s"] > prev_life_time_wins["Top 3s"]: crazy_lights(1, 5, 0, 255, 0, 255, 0, 255, 45, 0.4) print("Top 3s") on() elif life_time_wins["Top 10"] > prev_life_time_wins["Top 10"]: crazy_lights(1, 5, 0, 255, 0, 255, 0, 255, 45, 0.4) print("Top 10") on() elif life_time_wins["Top 5s"] > prev_life_time_wins["Top 5s"]: crazy_lights(1, 5, 0, 255, 0, 255, 0, 255, 45, 0.4) print("Top 5s") on() prev_life_time_wins = life_time_wins next_check = time() + FNT_REFRESH_TIME_SECS off() print("Fortnite stopped") # debug with button # switch.wait_for_release() switch = Button(17) blinkt.set_clear_on_exit() running = True restart_after_error = False print("Service running") while running: try: if restart_after_error: restart_after_error = False else: switch.wait_for_press() # debug with button # switch.wait_for_release() print("Fortnite started") run_cube() except FortniteResponseError as err: print("Fortnite Response Error: {}".format(err)) flash(0, 0, 255, 3, 0.25) restart_after_error = True except FortniteAPIError as err: print("Stopping - Fortnite API Error: {}".format(err)) flash(255, 0, 255, 3, 0.25) on(255, 0, 255) switch.wait_for_release() off() except KeyboardInterrupt: print("Service cancelled") off() running = False except: print("Stopping - Unexpected error:", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) flash(255, 0, 0, 3, 0.25) on(255,0,0) switch.wait_for_release() off()
25.788945
110
0.571707
91
0.017732
0
0
0
0
0
0
1,087
0.211808
0e04b755a0e6d8844b6bf932a0953df1cef59253
8,704
py
Python
server/application/utils_files.py
c-jordi/pdf2data
daa9f8b58e6603063b411ba7fba89054c924c5bc
[ "MIT" ]
null
null
null
server/application/utils_files.py
c-jordi/pdf2data
daa9f8b58e6603063b411ba7fba89054c924c5bc
[ "MIT" ]
1
2022-01-09T12:06:40.000Z
2022-01-09T12:06:40.000Z
server/application/utils_files.py
c-jordi/pdf2data
daa9f8b58e6603063b411ba7fba89054c924c5bc
[ "MIT" ]
null
null
null
import os, sys from uuid import uuid4 import numpy as np from pathlib import Path import xml.etree.ElementTree as ET import copy import re from urllib import request, parse from pdfminer.layout import LAParams from pdfminer.high_level import extract_text_to_fp from pdf2image import convert_from_path import matplotlib.pyplot as plt from .constants import TMP_FOLDER, TMP_SUFFIX, SEP_UID_NAME, IMG_FOLDER, POPPLER_PATH def extract_xml(uri): """ Obtain the xml from the pdf """ uid, name, suffix = info_from_uri(uri) file_name = name + '.xml' # We cannot use tempfile because the file is being closed and # deleted automatically, and we need it for further processing #fout = tempfile.TemporaryFile(dir = TMP_FOLDER) uri_out = create_tmp(file_name) fout = open(uri_out, 'wb') fin = open_urlopen_seek(uri) extract_text_to_fp(fin, fout, laparams=LAParams(), output_type='xml', codec="utf-8") return uri_out def clean_xml(uri): """ Works on an xml file, and perform some cleaning and simplification """ tree = ET.parse(uri) root = tree.getroot() root_new = remove_attrib_textl(root, keys_rem = ['colourspace', 'ncolour']) return root_new def remove_attrib_textl(tree, keys_rem = ['colourspace', 'ncolour']): """ Remove the indicated attributes from the <text> level of the xml """ for ip, page in enumerate(tree): for ib, block in enumerate(page): for it, textline in enumerate(block): for itext, text in enumerate(textline): keys_t = text.keys() val_keys = np.setdiff1d(keys_t, keys_rem) if len(val_keys): aux_dict = text.attrib tree[ip][ib][it][itext].attrib = dict() for key in val_keys: tree[ip][ib][it][itext].attrib[key] = aux_dict[key] return tree def info_from_uri(uri): name = Path(uri).stem uid = name.split(SEP_UID_NAME)[0] filename = name.split(SEP_UID_NAME)[1] suffix = Path(uri).suffix return uid, filename, suffix def create_tmp(filename): """ Just creates a tmp file in /tmp folder inside the storage folder """ uid = uuid4().hex fname = uid + SEP_UID_NAME + Path(filename).stem + Path(filename).suffix uri = TMP_FOLDER + fname return uri def open_urlopen_seek(uri): """ To obtain the xml from the pdf, we need a seekable file object, and the http response does not have that method. We need to create and intermediate file, open that, and remove it """ resp = request.urlretrieve(uri, TMP_FOLDER + uuid4().hex + TMP_SUFFIX) resp_seek = open(resp[0],'rb') os.remove(resp[0]) return resp_seek def get_text_onefile(XML_root, flag_clean = True): """ Groups all characters inside the <text> level as proper sentences in the <textline> level, preserving information on the fontsize """ # helper function to clean text # !!! so far only removing new lines and primitive dehyphenation def clean_text(text): # replace newline text = text.replace('\n', ' ') # account for hyphenation (not completely correct...) # TODO: needs to be improved text = text.replace('- ', '') return text # initialize textbox count and empty dictionary XML_new = copy.deepcopy(XML_root) # for every page for ind_p, page in enumerate(XML_root): #print(page.tag, page.attrib) # for every textbox on that page for ind_t, textbox in enumerate(page): if (textbox.tag == 'textbox'): # initialize string #print(textbox.tag, textbox.attrib) # for every textline in that textbox for ind_tl, textline in enumerate(textbox): prev_fontsize = 0 prev_fonttype = 'Def' complete_text = '' flag_in = 0 if textline.tag == 'textline': #print(textline.tag, textline.attrib) # for every text (actually just a letter) for ind_ch, text in enumerate(textline): #print(ind_ch, text.text, len(textline), len(XML_new[ind_p][ind_t][ind_tl])) # extend string if 'font' in text.attrib.keys(): if (text.attrib['font'] != prev_fonttype) or (text.attrib['size'] != str(prev_fontsize)): if flag_in: complete_text += '[/font]' else: flag_in = 1 complete_text += '[font face="' + text.attrib['font'] + '" size="' + text.attrib['size'] + '"]' prev_fontsize = text.attrib['size'] prev_fonttype = text.attrib['font'] complete_text = complete_text + text.text child_new = XML_new[ind_p][ind_t][ind_tl][0] # Because we are removing elements XML_new[ind_p][ind_t][ind_tl].remove(child_new) # clean text complete_text += '[/font]' # Remove \n and - from hypenation if flag_clean: complete_text = clean_text(complete_text) XML_new[ind_p][ind_t][ind_tl].text = complete_text return XML_new def structure_text_string(text): """ Takes a string with font annotations and returns a list of dict objects. (one for each block of text) :param text: a string with "[font face=...] blabla [/font]" annotations :return: a list of dicionaries, one for each block of text in certain font. each has the fields 'font', 'size', 'text', 'l_text' """ if text is None: return [] regex_string = '\[font face="([a-zA-Z\-]*)" size="(\d+\.\d*)"]([^[]*)\[\/font\]' pattern = re.compile(regex_string) matches = re.findall(pattern, text) # This simply because in the past the face and size were wrongly labelled if not len(matches): regex_string = '\[font face="(\d+\.\d*)" size="([a-zA-Z\-]*)"]([^[]*)\[\/font\]' pattern = re.compile(regex_string) matches = re.findall(pattern, text) collector = list() for m in matches: f = dict(font=m[1], size=float(m[0]), text=m[2], l_text=len(m[2])) collector.append(f) return collector else: collector = list() for m in matches: f = dict(font=m[0], size=float(m[1]), text=m[2], l_text=len(m[2])) collector.append(f) return collector def convert_textlines_in_xml_tree(orig): """ Adds one more hierarchy level of children in each 'textline' tag in the document xml tree obtained from the 04_corrected_xml. Specifically each 'textline' then contains children with tag 'text_block'. Each 'text_block' represents a part of the textline with the same formatting. It has attributes ['font', 'size'] and contains the actual text formatted in this way. :param orig: the xml tree obtained from 04_corrected xml :return: a modified copy of it where each 'textline' tag has children with tag 'text_block' """ new = copy.deepcopy(orig) for tL in new.findall(".//textline"): annotated_text = tL.text tL.text = "" for text_block in structure_text_string(annotated_text): params = dict(font=text_block["font"], size=str(text_block["size"])) text_block_element = ET.Element("text_block", params) text_block_element.text = text_block["text"] tL.append(text_block_element) return new def pdf2imgobj(pdf_uri, resolution = 150, first_page=None, last_page=None): """ Function that receives the pdf_uri and obtain the images, for some pages, storing them directly in the folder for tmp images """ uid, filename, suffix = info_from_uri(pdf_uri) img_obj_array_tmp = convert_from_path(pdf_uri, dpi = resolution, first_page = first_page, last_page = last_page, poppler_path=POPPLER_PATH) for image, page_numb in zip(img_obj_array_tmp,range(first_page, last_page + 1)): fname = os.path.join(IMG_FOLDER, filename + '_' + str(page_numb) + '.png') plt.imsave(fname, np.asarray(image))
37.679654
132
0.590648
0
0
0
0
0
0
0
0
2,942
0.338006
0e0641eb1c77685ac180e16ede2719bf186f1b48
616
py
Python
acq4/util/PySideImporter.py
aleonlein/acq4
4b1fcb9ad2c5e8d4595a2b9cf99d50ece0c0f555
[ "MIT" ]
1
2020-06-04T17:04:53.000Z
2020-06-04T17:04:53.000Z
acq4/util/PySideImporter.py
aleonlein/acq4
4b1fcb9ad2c5e8d4595a2b9cf99d50ece0c0f555
[ "MIT" ]
24
2016-09-27T17:25:24.000Z
2017-03-02T21:00:11.000Z
acq4/util/PySideImporter.py
sensapex/acq4
9561ba73caff42c609bd02270527858433862ad8
[ "MIT" ]
4
2016-10-19T06:39:36.000Z
2019-09-30T21:06:45.000Z
# -*- coding: utf-8 -*- from __future__ import print_function """This module installs an import hook which overrides PyQt4 imports to pull from PySide instead. Used for transitioning between the two libraries.""" import imp class PyQtImporter: def find_module(self, name, path): if name == 'PyQt4' and path is None: print("PyQt4 -> PySide") self.modData = imp.find_module('PySide') return self return None def load_module(self, name): return imp.load_module(name, *self.modData) import sys sys.meta_path.append(PyQtImporter())
29.333333
82
0.655844
331
0.537338
0
0
0
0
0
0
206
0.334416
0e0971e24a4cebbe3f58d427eb92c896a2027f86
619
py
Python
L1Trigger/DTTrigger/python/dtTriggerPrimitiveDigis_cfi.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/DTTrigger/python/dtTriggerPrimitiveDigis_cfi.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/DTTrigger/python/dtTriggerPrimitiveDigis_cfi.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
import FWCore.ParameterSet.Config as cms from L1TriggerConfig.DTTPGConfigProducers.L1DTTPGConfigFromDB_cff import * dtTriggerPrimitiveDigis = cms.EDProducer("DTTrigProd", debug = cms.untracked.bool(False), # DT digis input tag digiTag = cms.InputTag("muonDTDigis"), # Convert output into DTTF sector numbering: # false means [1-12] (useful for debug) # true is [0-11] useful as input for the DTTF emulator DTTFSectorNumbering = cms.bool(True), # config params for dumping of LUTs info from emulator lutBtic = cms.untracked.int32(31), lutDumpFlag = cms.untracked.bool(False) )
36.411765
74
0.733441
0
0
0
0
0
0
0
0
237
0.382876
0e09835187c4782a7d307df7391d9bcf5ed91648
14,774
py
Python
PythonChessEnviroment.py
teleansh/PythonChessEnviorment
cd19a9148a0da8e69c0efcf21dd559ab2084e07a
[ "MIT" ]
null
null
null
PythonChessEnviroment.py
teleansh/PythonChessEnviorment
cd19a9148a0da8e69c0efcf21dd559ab2084e07a
[ "MIT" ]
1
2022-03-08T16:16:26.000Z
2022-03-08T16:16:26.000Z
PythonChessEnviroment.py
teleansh/PythonChessEnviorment
cd19a9148a0da8e69c0efcf21dd559ab2084e07a
[ "MIT" ]
null
null
null
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def newBoard(): b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def display(): #white side view c , k= 1 ,0 ap = range(1,9)[::-1] row,col=[],[] for i in b: row.append(i) if c==8 : c=0 col.append(row) row=[] c+=1 for j in col[::-1]: print(ap[k] , " |" ,end=" ") for i in j: print(i,end=' ') print() k+=1 print(" ",end="") print("-"*18," A B C D E F G H",sep="\n") def move(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 b[fnum], b[tnum] = '.',b[fnum] display() def conv(s): num = int(s[1]) alp = s[0] a = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8} alpn = a[alp] return ((num-1)*8)+alpn def rookValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 con1,con2,con3=False,False,False if abs(fnum-tnum)%8==0: con1=True rows=[range(0,8),range(8,16),range(16,24),range(24,32),range(32,40),range(40,48),range(48,56),range(56,64)] for k in rows: if fnum in k and tnum in k: con2=True if con2: #verifies if path is clear if fr and to are in same row for l in range(fnum+1,tnum): if b[l] != '.': con2=False mi =min(fnum,tnum) ma = max(fnum,tnum) if con1: while mi < ma: mi+=8 if b[mi] !='.': con1=False if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con3 = True return (con1 or con2) and con3 def kingValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False con1,con2=False,False if fnum%8!=0 and fnum%9!=0: val = [fnum+1 , fnum-1,fnum+8,fnum-8] elif fnum%8==0: val =[fnum+8 , fnum-8,fnum-1] else: val =[fnum+8 , fnum-8,fnum+1] if fnum in val : con=True if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2 = True return con1 and con2 def pawnValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False if fr.isupper() : c='b' if fr.islower() : c='w' if c=='w': if fr in range(8,16): vm = [fnum+8,fnum+16] else : vm= [fnum+8] if b[fnum+7].isupper(): vm.append(fnum+7) if b[fnum+9].isupper(): vm.append(fnum+9) if tnum in vm and not b[tnum].islower(): return True else: return False if c=='b': if fr in range(48,56): vm = [fnum-8,fnum-16] else : vm= [fnum-8] if b[fnum-7].islower(): vm.append(fnum+7) if b[fnum-9].islower(): vm.append(fnum+9) if tnum in vm and not b[tnum].isupper(): return True else: return False def bishopValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False con1=False if abs(fnum-tnum)%9==0 or abs(fnum-tnum)%7==0: con1 = True if (fnum-tnum)%9==0: while fnum!=tnum: tnum+=9 if b[tnum]!='.' : return False if (fnum-tnum)%7==0: while fnum!=tnum: tnum+=7 if b[tnum]!='.' : return False if (tnum-fnum)%9==0: while tnum!=fnum: fnum+=9 if b[fnum]!='.' : return False if (tnum-fnum)%7==0: while tnum!=fnum: fnum+=7 if b[fnum]!='.' : return False if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2 = True return con1 and con2 def queenValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False return bishopValid(fr,to) or rookValid(fr,to) def knightValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False if tnum in [fnum+17,fnum-17,fnum+15,fnum-15,fnum+10,fnum-6,fnum+6,fnum-10]: con1=True if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2=True return con1 and con2 def addressValid(fnum,tnum): return 0<=fnum<64 and 0<=tnum<64 def rookMoves(pos): num=(conv(pos))-1 #num is index if b[num].isupper() : c='b' elif b[num].islower() : c='w' else: return "Block is empty" vm=[] col=(num+1)%8 if col==0: col=8 row=int(pos[1]) if c=='w': block=num+8 while row<=8: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=8 row+=1 row=int(pos[1]) block=num-8 while row>0: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=8 row-=1 tcol=col+1 #col is from 1 to 8 , row is from 1 to 8 block =num+1 while tcol<=8: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=1 tcol+=1 block =num-1 tcol=col while tcol>1: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=1 tcol-=1 tcol=col row=int(pos[1]) if c=='b': block=num+8 while row<=8: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=8 row+=1 row=int(pos[1]) block=num-8 while row>1: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=8 row-=1 tcol=col+1 #col is from 1 to 8 , row is from 1 to 8 block =num+1 while tcol<=8: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=1 tcol+=1 block =num-1 tcol=col while tcol>1: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=1 tcol-=1 move=[] for l in vm: move.append(numToAlg(l)) return move def bishopMoves(pos): num=(conv(pos))-1 if b[num].isupper() : c='b' elif b[num].islower() : c='w' else: return "Block is empty" vm=[] col=(num+1)%8 if col==0: col=8 row=int(pos[1])+1 if c=='w': tcol=col+1 row=int(pos[1])+1 block=num+9 while row<=8 and col<=8 : #goes top right if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=9 row+=1 tcol+=1 row=int(pos[1])-1 tcol=col-1 block=num-9 while row>0 and tcol>1: #goes below left if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=9 row-=1 tcol-=1 row=int(pos[1])-1 tcol=col+1 block =num-7 while tcol<=8 and row>1: #goes below right if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=7 tcol+=1 row-=1 block =num+7 tcol=col-1 row=int(pos[1])+1 while tcol>0 and row<=8: #goes top left if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=7 tcol-=1 row+=1 if c=='b': tcol=col+1 row=int(pos[1])+1 block=num+9 while row<=8 and col<=8 : #goes top right if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=9 row+=1 tcol+=1 row=int(pos[1])-1 tcol=col-1 block=num-9 while row>0 and tcol>1: #goes below left if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=9 row-=1 tcol-=1 row=int(pos[1])-1 tcol=col+1 block =num-7 while tcol<=8 and row>1: #goes below right if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=7 tcol+=1 row-=1 block =num+7 tcol=col-1 row=int(pos[1])+1 while tcol>0 and row<=8: #goes top left if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].upper(): break block+=7 tcol-=1 row+=1 move=[] for l in vm: move.append(numToAlg(l)) return move def queenMoves(pos): return rookMoves(pos) + bishopMoves(pos) def knightMoves(pos): num = conv(pos)-1 #num is index vm = [num-17,num-15,num-10,num-6,num+6,num+10,num+15,num+17] if vm[3]%8 in [0,1]: vm.pop(3) vm.pop(5) if vm[4]%8 in [6,7]: vm.pop(4) vm.pop(2) tvm=[] for i in vm: if (i>=0 and i<=63) and not ((b[num].isupper and b[i].isupper()) or (b[num].islower and b[i].islower())) : tvm.append(i) move=[] for l in tvm: move.append(numToAlg(l)) return move def kingMoves(pos): num = conv(pos)-1 #num is index vm = [num+8,num-8,num+9,num-9,num+7,num-7,num+1,num-1] if vm[2]%8==0: vm.pop(2) vm.pop(6) vm.pop(5) if vm[3]%8 ==7: vm.pop(3) vm.pop(-1) vm.pop(4) tvm=[] for i in vm: if (i>=0 and i<=63) and not ((b[num].isupper and b[i].isupper()) or (b[num].islower and b[i].islower())) : tvm.append(i) move=[] for l in tvm: move.append(numToAlg(l)) return move def pawnMoves(pos): num = conv(pos)-1 vm=[] if b[num].islower() : if b[num+8] =='.':vm.append(num+8) if b[num+9].isupper() : vm.append(num+9) if b[num+7].isupper() : vm.append(num+7) if b[num+16] =='.' and 7<num<16 : vm.append(num+16) if b[num].isupper() : if b[num-8] =='.':vm.append(num-8) if b[num-9].islower() : vm.append(num-9) if b[num-7].islower() : vm.append(num-7) if b[num-16] =='.' and 7<num<16 : vm.append(num-16) list =[] for i in vm: list.append(numToAlg(i)) return list def moves(pos): num = conv(pos)-1 if b[num].lower() =='k': return(kingMoves(pos)) elif b[num].lower() == 'q': return(queenMoves(pos)) elif b[num].lower() == 'p': return(pawnMoves(pos)) elif b[num].lower() == 'r': return(rookMoves(pos)) elif b[num].lower() == 'b': return(bishopMoves(pos)) elif b[num].lower() == 'n': return(knightMoves(pos)) def isCheck(pos): num = conv(pos)-1 r = rookMoves(pos) b = bishopMoves(pos) n = knightMoves(pos) check = False for rcase in r: if b[conv(rcase)-1].lower() in ['r','q'] and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ) : check=True for bcase in r: if b[conv(bcase)-1].lower() in ['b','q'] and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ): check=True for kcas in r: if b[conv(bcase)-1].lower()=='n' and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ): check=True return check def numToAlg(ind): alp=(ind+1)%8 n=((ind+1)//8) + 1 if alp==0: n-=1 a = {0:'h',1 : 'a' , 2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h'} return str(a[alp]) + str(n)
26.66787
173
0.425274
0
0
0
0
0
0
0
0
759
0.051374
0e0d7b53e41d2bf0a7a2e0799a229887f7c07708
5,408
py
Python
txosc/async.py
oubiwann/txosc
6560a0dc9ef564d785170d4529967599455e4f3e
[ "MIT" ]
1
2018-02-11T07:34:29.000Z
2018-02-11T07:34:29.000Z
txosc/async.py
oubiwann/txosc
6560a0dc9ef564d785170d4529967599455e4f3e
[ "MIT" ]
1
2019-01-14T22:42:45.000Z
2019-01-14T22:42:45.000Z
txosc/async.py
oubiwann/txosc
6560a0dc9ef564d785170d4529967599455e4f3e
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- test-case-name: txosc.test.test_async -*- # Copyright (c) 2009 Alexandre Quessy, Arjan Scherpenisse # See LICENSE for details. """ Asynchronous OSC sender and receiver using Twisted """ import struct import socket from twisted.internet import defer, protocol from twisted.application.internet import MulticastServer from txosc.osc import * from txosc.osc import _elementFromBinary # # Stream based client/server protocols # class StreamBasedProtocol(protocol.Protocol): """ OSC over TCP sending and receiving protocol. """ def connectionMade(self): self.factory.connectedProtocol = self if hasattr(self.factory, 'deferred'): self.factory.deferred.callback(True) self._buffer = "" self._pkgLen = None def dataReceived(self, data): """ Called whenever data is received. In a stream-based protocol such as TCP, the stream should begin with an int32 giving the size of the first packet, followed by the contents of the first packet, followed by the size of the second packet, etc. @type data: L{str} """ self._buffer += data if len(self._buffer) < 4: return if self._pkgLen is None: self._pkgLen = struct.unpack(">i", self._buffer[:4])[0] if len(self._buffer) < self._pkgLen + 4: print "waiting for %d more bytes" % (self._pkgLen + 4 - len(self._buffer)) return payload = self._buffer[4:4 + self._pkgLen] self._buffer = self._buffer[4 + self._pkgLen:] self._pkgLen = None if payload: element = _elementFromBinary(payload) self.factory.gotElement(element) if len(self._buffer): self.dataReceived("") def send(self, element): """ Send an OSC element over the TCP wire. @param element: L{txosc.osc.Message} or L{txosc.osc.Bundle} """ binary = element.toBinary() self.transport.write(struct.pack(">i", len(binary)) + binary) #TODO: return a Deferred class StreamBasedFactory(object): """ Factory object for the sending and receiving of elements in a stream-based protocol (e.g. TCP, serial). @ivar receiver: A L{Receiver} object which is used to dispatch incoming messages to. @ivar connectedProtocol: An instance of L{StreamBasedProtocol} representing the current connection. """ receiver = None connectedProtocol = None def __init__(self, receiver=None): if receiver: self.receiver = receiver def send(self, element): self.connectedProtocol.send(element) def gotElement(self, element): if self.receiver: self.receiver.dispatch(element, self) else: raise OscError("Element received, but no Receiver in place: " + str(element)) def __str__(self): return str(self.connectedProtocol.transport.client) class ClientFactory(protocol.ClientFactory, StreamBasedFactory): """ TCP client factory """ protocol = StreamBasedProtocol def __init__(self, receiver=None): StreamBasedFactory.__init__(self, receiver) self.deferred = defer.Deferred() class ServerFactory(protocol.ServerFactory, StreamBasedFactory): """ TCP server factory """ protocol = StreamBasedProtocol # # Datagram client/server protocols # class DatagramServerProtocol(protocol.DatagramProtocol): """ The UDP OSC server protocol. @ivar receiver: The L{Receiver} instance to dispatch received elements to. """ def __init__(self, receiver): """ @param receiver: L{Receiver} instance. """ self.receiver = receiver def datagramReceived(self, data, (host, port)): element = _elementFromBinary(data) self.receiver.dispatch(element, (host, port)) class MulticastDatagramServerProtocol(DatagramServerProtocol): """ UDP OSC server protocol that can listen to multicast. Here is an example on how to use it: reactor.listenMulticast(8005, MulticastServerUDP(receiver, "224.0.0.1"), listenMultiple=True) This way, many listeners can listen on the same port, same host, to the same multicast group. (in this case, the 224.0.0.1 multicast group) """ def __init__(self, receiver, multicast_addr="224.0.0.1"): """ @param multicast_addr: IP address of the multicast group. @param receiver: L{txosc.dispatch.Receiver} instance. @type multicast_addr: str @type receiver: L{txosc.dispatch.Receiver} """ self.multicast_addr = multicast_addr DatagramServerProtocol.__init__(self, receiver) def startProtocol(self): """ Join a specific multicast group, which is the IP we will respond to """ self.transport.joinGroup(self.multicast_addr) class DatagramClientProtocol(protocol.DatagramProtocol): """ The UDP OSC client protocol. """ def send(self, element, (host, port)): """ Send a L{txosc.osc.Message} or L{txosc.osc.Bundle} to the address specified. @type element: L{txosc.osc.Message} """ data = element.toBinary() self.transport.write(data, (socket.gethostbyname(host), port))
28.765957
143
0.645895
4,892
0.904586
0
0
0
0
0
0
2,404
0.444527
0e0f6259ba624db7fa0c2c5d4fdc06aa5c711408
2,740
py
Python
main.py
theIsaacLim/hakdPizza
0471dc6ee9fc049bd10f0a8aa9d707f2c0388fc5
[ "MIT" ]
null
null
null
main.py
theIsaacLim/hakdPizza
0471dc6ee9fc049bd10f0a8aa9d707f2c0388fc5
[ "MIT" ]
null
null
null
main.py
theIsaacLim/hakdPizza
0471dc6ee9fc049bd10f0a8aa9d707f2c0388fc5
[ "MIT" ]
null
null
null
from selenium import webdriver from time import sleep # Sleep will pause the program import os # for getting the local path from json import loads dirpath = os.getcwd() # gets local path driver = webdriver.Chrome(dirpath + "/chromedriver") def login(username, password): global driver # LOGIN driver.find_element_by_css_selector(".header-login > span:nth-child(1)").click() # Click login button usernameField, passwordField = driver.find_element_by_css_selector("#txt-ac-userName"), driver.find_element_by_css_selector("#txt-ac-passWord") usernameField.send_keys(username) passwordField.send_keys(password) loginButton = driver.find_element_by_css_selector("#main > div > div.body > div > div:nth-child(1) > div.operator-bar > div") loginButton.click() sleep(4) def addPizzaToCart(pizzaName, size): global driver pizzaText = driver.find_element_by_xpath('//div[text() = "{}"]'.format(pizzaName)) # uses xpath to select the pizza label element # Here, we have the label that says what pizza it is # This isn't what we want though # # We want to click the button that says to buy # To do that, we have to have a look at the actual structure of the page # The label and the button are all wrapped in a bigger div. We can get the button by finding # the label's parent and getting it's child, the button # # That's essentially what the following code does containerDiv = pizzaText.find_element_by_xpath('..') button = containerDiv.find_element_by_css_selector("a[data-mltext='p-buy']") buttonWrapperSpan = button.find_element_by_xpath('..') # Okay so what happens here is that it should in theory open up a modal window that allows you to tick certain options scriptFunction = buttonWrapperSpan.get_attribute('onclick') # This is the function that opens the modal window driver.execute_script(scriptFunction) # Execute that function sleep(5) driver.switch_to.frame("iframe") driver.execute_script("SizeClick('{}');".format(size)) driver.execute_script("AddShoppingCar();") def checkout(): driver.get("http://www.dominos.com.cn/order/cart.html") driver.execute_script("ConfirmOrder();") # GET PAGE AND CHANGE LANGUAGE TO ENGLISH driver.get("http://www.dominos.com.cn/menu/menu.html?menuIndex=0&RNDSEED=c42905609c237eff75c1bd6767345f43") # dominos menu page login("username", "password") english = driver.find_element_by_css_selector('#lanEn > a') english.click() # click on english to change tha language sleep(7) # Wait for the website to update rawText = open("order.json").read() orderDict = loads(rawText) for order in orderDict: addPizzaToCart(order["name"], order["size"]) sleep(2)
42.153846
147
0.729562
0
0
0
0
0
0
0
0
1,351
0.493066
0e0fc6085ae3cea9518a28dc404a0b76c2ffa235
127,770
py
Python
pandatools/Client.py
Jon-Burr/panda-client
ff7ee8fc8481537cf604d983340eda102f041a20
[ "Apache-2.0" ]
null
null
null
pandatools/Client.py
Jon-Burr/panda-client
ff7ee8fc8481537cf604d983340eda102f041a20
[ "Apache-2.0" ]
null
null
null
pandatools/Client.py
Jon-Burr/panda-client
ff7ee8fc8481537cf604d983340eda102f041a20
[ "Apache-2.0" ]
null
null
null
''' client methods ''' import os if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : importing %s" % __name__ import re import sys import time import stat import types try: import json except: import simplejson as json import random import urllib import struct import commands import cPickle as pickle import xml.dom.minidom import socket import tempfile import MiscUtils import PLogger # configuration try: baseURL = os.environ['PANDA_URL'] except: baseURL = 'http://pandaserver.cern.ch:25080/server/panda' try: baseURLSSL = os.environ['PANDA_URL_SSL'] except: baseURLSSL = 'https://pandaserver.cern.ch:25443/server/panda' baseURLDQ2 = 'http://atlddmcat-reader.cern.ch/dq2' baseURLDQ2SSL = 'https://atlddmcat-writer.cern.ch:443/dq2' baseURLSUB = "http://pandaserver.cern.ch:25080/trf/user" baseURLMON = "http://panda.cern.ch:25980/server/pandamon/query" baseURLCSRV = "http://pandacache.cern.ch:25080/server/panda" baseURLCSRVSSL = "http://pandacache.cern.ch:25443/server/panda" #baseURLCSRV = "http://aipanda011.cern.ch:25080/server/panda" #baseURLCSRVSSL = "http://aipanda011.cern.ch:25443/server/panda" # exit code EC_Failed = 255 # default max size per job maxTotalSize = long(14*1024*1024*1024) # safety size for input size calculation safetySize = long(500*1024*1024) # suffix for shadow dataset suffixShadow = "_shadow" # limit on maxCpuCount maxCpuCountLimit = 1000000000 # retrieve pathena config try: # get default timeout defTimeOut = socket.getdefaulttimeout() # set timeout socket.setdefaulttimeout(60) except: pass if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : getting panda cache server's name" # get panda cache server's name try: getServerURL = baseURLCSRV + '/getServer' res = urllib.urlopen(getServerURL) # overwrite URL baseURLCSRVSSL = "https://%s/server/panda" % res.read() except: type, value, traceBack = sys.exc_info() print type,value print "ERROR : could not getServer from %s" % getServerURL sys.exit(EC_Failed) try: # reset timeout socket.setdefaulttimeout(defTimeOut) except: pass if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : ready" # look for a grid proxy certificate def _x509(): # see X509_USER_PROXY try: return os.environ['X509_USER_PROXY'] except: pass # see the default place x509 = '/tmp/x509up_u%s' % os.getuid() if os.access(x509,os.R_OK): return x509 # no valid proxy certificate # FIXME print "No valid grid proxy certificate found" return '' # look for a CA certificate directory def _x509_CApath(): # use X509_CERT_DIR try: return os.environ['X509_CERT_DIR'] except: pass # get X509_CERT_DIR gridSrc = _getGridSrc() com = "%s echo $X509_CERT_DIR" % gridSrc tmpOut = commands.getoutput(com) return tmpOut.split('\n')[-1] # keep list of tmp files for cleanup globalTmpDir = '' # curl class class _Curl: # constructor def __init__(self): # path to curl self.path = 'curl --user-agent "dqcurl" ' # verification of the host certificate self.verifyHost = True # request a compressed response self.compress = True # SSL cert/key self.sslCert = '' self.sslKey = '' # verbose self.verbose = False # GET method def get(self,url,data,rucioAccount=False): # make command com = '%s --silent --get' % self.path if not self.verifyHost or not url.startswith('https://'): com += ' --insecure' else: tmp_x509_CApath = _x509_CApath() if tmp_x509_CApath != '': com += ' --capath %s' % tmp_x509_CApath if self.compress: com += ' --compressed' if self.sslCert != '': com += ' --cert %s' % self.sslCert com += ' --cacert %s' % self.sslCert if self.sslKey != '': com += ' --key %s' % self.sslKey # max time of 10 min com += ' -m 600' # add rucio account info if rucioAccount: if os.environ.has_key('RUCIO_ACCOUNT'): data['account'] = os.environ['RUCIO_ACCOUNT'] if os.environ.has_key('RUCIO_APPID'): data['appid'] = os.environ['RUCIO_APPID'] data['client_version'] = '2.4.1' # data strData = '' for key in data.keys(): strData += 'data="%s"\n' % urllib.urlencode({key:data[key]}) # write data to temporary config file if globalTmpDir != '': tmpFD,tmpName = tempfile.mkstemp(dir=globalTmpDir) else: tmpFD,tmpName = tempfile.mkstemp() os.write(tmpFD,strData) os.close(tmpFD) com += ' --config %s' % tmpName com += ' %s' % url # execute if self.verbose: print com print strData[:-1] s,o = commands.getstatusoutput(com) if o != '\x00': try: tmpout = urllib.unquote_plus(o) o = eval(tmpout) except: pass ret = (s,o) # remove temporary file os.remove(tmpName) ret = self.convRet(ret) if self.verbose: print ret return ret # POST method def post(self,url,data,rucioAccount=False): # make command com = '%s --silent' % self.path if not self.verifyHost or not url.startswith('https://'): com += ' --insecure' else: tmp_x509_CApath = _x509_CApath() if tmp_x509_CApath != '': com += ' --capath %s' % tmp_x509_CApath if self.compress: com += ' --compressed' if self.sslCert != '': com += ' --cert %s' % self.sslCert com += ' --cacert %s' % self.sslCert if self.sslKey != '': com += ' --key %s' % self.sslKey # max time of 10 min com += ' -m 600' # add rucio account info if rucioAccount: if os.environ.has_key('RUCIO_ACCOUNT'): data['account'] = os.environ['RUCIO_ACCOUNT'] if os.environ.has_key('RUCIO_APPID'): data['appid'] = os.environ['RUCIO_APPID'] data['client_version'] = '2.4.1' # data strData = '' for key in data.keys(): strData += 'data="%s"\n' % urllib.urlencode({key:data[key]}) # write data to temporary config file if globalTmpDir != '': tmpFD,tmpName = tempfile.mkstemp(dir=globalTmpDir) else: tmpFD,tmpName = tempfile.mkstemp() os.write(tmpFD,strData) os.close(tmpFD) com += ' --config %s' % tmpName com += ' %s' % url # execute if self.verbose: print com print strData[:-1] s,o = commands.getstatusoutput(com) if o != '\x00': try: tmpout = urllib.unquote_plus(o) o = eval(tmpout) except: pass ret = (s,o) # remove temporary file os.remove(tmpName) ret = self.convRet(ret) if self.verbose: print ret return ret # PUT method def put(self,url,data): # make command com = '%s --silent' % self.path if not self.verifyHost or not url.startswith('https://'): com += ' --insecure' else: tmp_x509_CApath = _x509_CApath() if tmp_x509_CApath != '': com += ' --capath %s' % tmp_x509_CApath if self.compress: com += ' --compressed' if self.sslCert != '': com += ' --cert %s' % self.sslCert com += ' --cacert %s' % self.sslCert if self.sslKey != '': com += ' --key %s' % self.sslKey # emulate PUT for key in data.keys(): com += ' -F "%s=@%s"' % (key,data[key]) com += ' %s' % url if self.verbose: print com # execute ret = commands.getstatusoutput(com) ret = self.convRet(ret) if self.verbose: print ret return ret # convert return def convRet(self,ret): if ret[0] != 0: ret = (ret[0]%255,ret[1]) # add messages to silent errors if ret[0] == 35: ret = (ret[0],'SSL connect error. The SSL handshaking failed. Check grid certificate/proxy.') elif ret[0] == 7: ret = (ret[0],'Failed to connect to host.') elif ret[0] == 55: ret = (ret[0],'Failed sending network data.') elif ret[0] == 56: ret = (ret[0],'Failure in receiving network data.') return ret ''' public methods ''' # get site specs def getSiteSpecs(siteType=None): # instantiate curl curl = _Curl() # execute url = baseURL + '/getSiteSpecs' data = {} if siteType != None: data['siteType'] = siteType status,output = curl.get(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() errStr = "ERROR getSiteSpecs : %s %s" % (type,value) print errStr return EC_Failed,output+'\n'+errStr # get cloud specs def getCloudSpecs(): # instantiate curl curl = _Curl() # execute url = baseURL + '/getCloudSpecs' status,output = curl.get(url,{}) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() errStr = "ERROR getCloudSpecs : %s %s" % (type,value) print errStr return EC_Failed,output+'\n'+errStr # refresh spacs at runtime def refreshSpecs(): global PandaSites global PandaClouds # get Panda Sites tmpStat,PandaSites = getSiteSpecs() if tmpStat != 0: print "ERROR : cannot get Panda Sites" sys.exit(EC_Failed) for id, val in PandaSites.iteritems(): if 'setokens' not in val: if 'setokens_output' in val: val['setokens'] = val['setokens_output'] else: val['setokens'] = {} # get cloud info tmpStat,PandaClouds = getCloudSpecs() if tmpStat != 0: print "ERROR : cannot get Panda Clouds" sys.exit(EC_Failed) # initialize spacs refreshSpecs() # get LRC def getLRC(site): ret = None # look for DQ2ID for id,val in PandaSites.iteritems(): if id == site or val['ddm'] == site: if not val['dq2url'] in [None,"","None"]: ret = val['dq2url'] break return ret # get LFC def getLFC(site): ret = None # use explicit matching for sitename if PandaSites.has_key(site): val = PandaSites[site] if not val['lfchost'] in [None,"","None"]: ret = val['lfchost'] return ret # look for DQ2ID for id,val in PandaSites.iteritems(): if id == site or val['ddm'] == site: if not val['lfchost'] in [None,"","None"]: ret = val['lfchost'] break return ret # get SEs def getSE(site): ret = [] # use explicit matching for sitename if PandaSites.has_key(site): val = PandaSites[site] if not val['se'] in [None,"","None"]: for tmpSE in val['se'].split(','): match = re.search('.+://([^:/]+):*\d*/*',tmpSE) if match != None: ret.append(match.group(1)) return ret # look for DQ2ID for id,val in PandaSites.iteritems(): if id == site or val['ddm'] == site: if not val['se'] in [None,"","None"]: for tmpSE in val['se'].split(','): match = re.search('.+://([^:/]+):*\d*/*',tmpSE) if match != None: ret.append(match.group(1)) break # return return ret # convert DQ2 ID to Panda siteid def convertDQ2toPandaID(site, getAll=False): keptSite = '' siteList = [] for tmpID,tmpSpec in PandaSites.iteritems(): # # exclude long,xrootd,local queues if isExcudedSite(tmpID): continue # get list of DQ2 IDs srmv2ddmList = [] for tmpDdmID in tmpSpec['setokens'].values(): srmv2ddmList.append(convSrmV2ID(tmpDdmID)) # use Panda sitename if convSrmV2ID(site) in srmv2ddmList: keptSite = tmpID # keep non-online site just in case if tmpSpec['status']=='online': if not getAll: return keptSite siteList.append(keptSite) if getAll: return ','.join(siteList) return keptSite # convert DQ2 ID to Panda site IDs def convertDQ2toPandaIDList(site): sites = [] sitesOff = [] for tmpID,tmpSpec in PandaSites.iteritems(): # # exclude long,xrootd,local queues if isExcudedSite(tmpID): continue # get list of DQ2 IDs srmv2ddmList = [] for tmpDdmID in tmpSpec['setokens'].values(): srmv2ddmList.append(convSrmV2ID(tmpDdmID)) # use Panda sitename if convSrmV2ID(site) in srmv2ddmList: # append if tmpSpec['status']=='online': if not tmpID in sites: sites.append(tmpID) else: # keep non-online site just in case if not tmpID in sitesOff: sitesOff.append(tmpID) # return if sites != []: return sites return sitesOff # convert to long queue def convertToLong(site): tmpsite = re.sub('ANALY_','ANALY_LONG_',site) tmpsite = re.sub('_\d+$','',tmpsite) # if sitename exists if PandaSites.has_key(tmpsite): site = tmpsite return site # submit jobs def submitJobs(jobs,verbose=False): # set hostname hostname = commands.getoutput('hostname') for job in jobs: job.creationHost = hostname # serialize strJobs = pickle.dumps(jobs) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/submitJobs' data = {'jobs':strJobs} status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR submitJobs : %s %s" % (type,value) return EC_Failed,None # get job status def getJobStatus(ids): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() # execute url = baseURL + '/getJobStatus' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getJobStatus : %s %s" % (type,value) return EC_Failed,None # kill jobs def killJobs(ids,verbose=False): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/killJobs' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR killJobs : %s %s" % (type,value) return EC_Failed,None # kill task def killTask(jediTaskID,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/killTask' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR killTask : %s %s" % (type,value) return EC_Failed,None # finish task def finishTask(jediTaskID,soft=False,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/finishTask' data = {'jediTaskID':jediTaskID} if soft: data['soft'] = True status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR finishTask : %s %s" % (type,value) return EC_Failed,None # retry task def retryTask(jediTaskID,verbose=False,properErrorCode=False,newParams=None): if newParams == None: newParams = {} # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/retryTask' data = {'jediTaskID':jediTaskID, 'properErrorCode':properErrorCode} if newParams != {}: data['newParams'] = json.dumps(newParams) status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR retryTask : %s %s" % (type,value) return EC_Failed,None # reassign jobs def reassignJobs(ids): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() # execute url = baseURLSSL + '/reassignJobs' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR reassignJobs : %s %s" % (type,value) return EC_Failed,None # query PandaIDs def queryPandaIDs(ids): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() # execute url = baseURL + '/queryPandaIDs' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR queryPandaIDs : %s %s" % (type,value) return EC_Failed,None # query last files in datasets def queryLastFilesInDataset(datasets,verbose=False): # serialize strDSs = pickle.dumps(datasets) # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/queryLastFilesInDataset' data = {'datasets':strDSs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR queryLastFilesInDataset : %s %s" % (type,value) return EC_Failed,None # put file def putFile(file,verbose=False,useCacheSrv=False,reuseSandbox=False): # size check for noBuild sizeLimit = 10*1024*1024 fileSize = os.stat(file)[stat.ST_SIZE] if not os.path.basename(file).startswith('sources.'): if fileSize > sizeLimit: errStr = 'Exceeded size limit (%sB >%sB). ' % (fileSize,sizeLimit) errStr += 'Your working directory contains too large files which cannot be put on cache area. ' errStr += 'Please submit job without --noBuild/--libDS so that your files will be uploaded to SE' # get logger tmpLog = PLogger.getPandaLogger() tmpLog.error(errStr) return EC_Failed,'False' # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # check duplicationn if reuseSandbox: # get CRC fo = open(file) fileContent = fo.read() fo.close() footer = fileContent[-8:] checkSum,isize = struct.unpack("II",footer) # check duplication url = baseURLSSL + '/checkSandboxFile' data = {'fileSize':fileSize,'checkSum':checkSum} status,output = curl.post(url,data) if status != 0: return EC_Failed,'ERROR: Could not check Sandbox duplication with %s' % status elif output.startswith('FOUND:'): # found reusable sandbox hostName,reuseFileName = output.split(':')[1:] # set cache server hostname global baseURLCSRVSSL baseURLCSRVSSL = "https://%s:25443/server/panda" % hostName # return reusable filename return 0,"NewFileName:%s" % reuseFileName # execute if useCacheSrv: url = baseURLCSRVSSL + '/putFile' else: url = baseURLSSL + '/putFile' data = {'file':file} return curl.put(url,data) # delete file def deleteFile(file): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() # execute url = baseURLSSL + '/deleteFile' data = {'file':file} return curl.post(url,data) # check dataset in map by ignoring case sensitivity def checkDatasetInMap(name,outMap): try: for tmpKey in outMap.keys(): if name.upper() == tmpKey.upper(): return True except: pass return False # get real dataset name from map by ignoring case sensitivity def getDatasetValueInMap(name,outMap): for tmpKey in outMap.keys(): if name.upper() == tmpKey.upper(): return tmpKey # return original name return name # query files in dataset def queryFilesInDataset(name,verbose=False,v_vuids=None,getDsString=False,dsStringOnly=False): # instantiate curl curl = _Curl() curl.verbose = verbose # for container failure status,out = 0,'' nameVuidsMap = {} dsString = '' try: errStr = '' # get VUID if v_vuids == None: url = baseURLDQ2 + '/ws_repository/rpc' if re.search(',',name) != None: # comma-separated list names = name.split(',') elif name.endswith('/'): # container names = [name] else: names = [name] # loop over all names vuidList = [] iLookUp = 0 for tmpName in names: iLookUp += 1 if iLookUp % 20 == 0: time.sleep(1) data = {'operation':'queryDatasetByName','dsn':tmpName, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) if status != 0 or out == '\x00' or (re.search('\*',tmpName) == None and not checkDatasetInMap(tmpName,out)): errStr = "ERROR : could not find %s in DQ2 DB. Check if the dataset name is correct" \ % tmpName sys.exit(EC_Failed) # parse if re.search('\*',tmpName) == None: # get real dataset name tmpName = getDatasetValueInMap(tmpName,out) vuidList.append(out[tmpName]['vuids']) # mapping between name and vuids nameVuidsMap[tuple(out[tmpName]['vuids'])] = tmpName # string to expand wildcard dsString += '%s,' % tmpName else: # using wildcard for outKeyName in out.keys(): # skip sub/dis if re.search('_dis\d+$',outKeyName) != None or re.search('_sub\d+$',outKeyName) != None: continue # append vuidList.append(out[outKeyName]['vuids']) # mapping between name and vuids nameVuidsMap[tuple(out[outKeyName]['vuids'])] = outKeyName # string to expand wildcard dsString += '%s,' % outKeyName else: vuidList = [v_vuids] if dsStringOnly: return dsString[:-1] # reset for backward comatiblity when * or , is not used if re.search('\*',name) == None and re.search(',',name) == None: nameVuidsMap = {} dsString = '' # get files url = baseURLDQ2 + '/ws_content/rpc' ret = {} generalLFNmap = {} iLookUp = 0 for vuids in vuidList: iLookUp += 1 if iLookUp % 20 == 0: time.sleep(1) data = {'operation': 'queryFilesInDataset','vuids':vuids, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not get files in %s" % name sys.exit(EC_Failed) # parse if out == '\x00' or len(out) < 2 or out==(): # empty continue for guid,vals in out[0].iteritems(): # remove attemptNr generalLFN = re.sub('\.\d+$','',vals['lfn']) # choose greater attempt to avoid duplication if generalLFNmap.has_key(generalLFN): if vals['lfn'] > generalLFNmap[generalLFN]: # remove lesser attempt del ret[generalLFNmap[generalLFN]] else: continue # append to map generalLFNmap[generalLFN] = vals['lfn'] ret[vals['lfn']] = {'guid' : guid, 'fsize' : vals['filesize'], 'md5sum' : vals['checksum'], 'scope' : vals['scope']} # add dataset name if nameVuidsMap.has_key(tuple(vuids)): ret[vals['lfn']]['dataset'] = nameVuidsMap[tuple(vuids)] except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) if getDsString: return ret,dsString[:-1] return ret # get datasets def getDatasets(name,verbose=False,withWC=False,onlyNames=False): # instantiate curl curl = _Curl() curl.verbose = verbose try: errStr = '' # get VUID url = baseURLDQ2 + '/ws_repository/rpc' data = {'operation':'queryDatasetByName','dsn':name,'version':0, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} if onlyNames: data['API'] = '30' data['onlyNames'] = int(onlyNames) status,out = curl.get(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not access DQ2 server" sys.exit(EC_Failed) # parse datasets = {} if out == '\x00' or ((not withWC) and (not checkDatasetInMap(name,out))): # no datasets return datasets # get names only if isinstance(out,types.DictionaryType): return out else: # wrong format errStr = "ERROR : DQ2 didn't give a dictionary for %s" % name sys.exit(EC_Failed) # get VUIDs for dsname,idMap in out.iteritems(): # check format if idMap.has_key('vuids') and len(idMap['vuids'])>0: datasets[dsname] = idMap['vuids'][0] else: # wrong format errStr = "ERROR : could not parse HTTP response for %s" % name sys.exit(EC_Failed) except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) return datasets # disable expiring file check globalUseShortLivedReplicas = False def useExpiringFiles(): global globalUseShortLivedReplicas globalUseShortLivedReplicas = True # get expiring files globalCompleteDsMap = {} globalExpFilesMap = {} globalExpOkFilesMap = {} globalExpCompDq2FilesMap = {} def getExpiringFiles(dsStr,removedDS,siteID,verbose,getOKfiles=False): # convert * in dsStr if re.search('\*',dsStr) != None: dsStr = queryFilesInDataset(dsStr,verbose,dsStringOnly=True) # reuse map global globalExpFilesMap global globalExpOkFilesMap global expCompDq2FilesList global globalUseShortLivedReplicas mapKey = (dsStr,siteID) if globalExpFilesMap.has_key(mapKey): if getOKfiles: return globalExpFilesMap[mapKey],globalExpOkFilesMap[mapKey],globalExpCompDq2FilesMap[mapKey] return globalExpFilesMap[mapKey] # get logger tmpLog = PLogger.getPandaLogger() if verbose: tmpLog.debug("checking metadata for %s, removed=%s " % (dsStr,str(removedDS))) # get DQ2 location and used data tmpLocations,dsUsedDsMap = getLocations(dsStr,[],'',False,verbose,getDQ2IDs=True, removedDatasets=removedDS, useOutContainer=True, includeIncomplete=True, notSiteStatusCheck=True) # get all sites matching with site's DQ2ID here, to work with brokeroff sites fullSiteList = convertDQ2toPandaIDList(PandaSites[siteID]['ddm']) # get datasets at the site datasets = [] for tmpDsUsedDsMapKey,tmpDsUsedDsVal in dsUsedDsMap.iteritems(): siteMatched = False for tmpTargetID in fullSiteList: # check with short/long siteID if tmpDsUsedDsMapKey in [tmpTargetID,convertToLong(tmpTargetID)]: datasets = tmpDsUsedDsVal siteMatched = True break if siteMatched: break # not found if datasets == []: tmpLog.error("cannot find datasets at %s for replica metadata check" % siteID) sys.exit(EC_Failed) # loop over all datasets convertedOrigSite = convSrmV2ID(PandaSites[siteID]['ddm']) expFilesMap = {'datasets':[],'files':[]} expOkFilesList = [] expCompDq2FilesList = [] for dsName in datasets: # get DQ2 IDs for the siteID dq2Locations = [] if tmpLocations.has_key(dsName): for tmpLoc in tmpLocations[dsName]: # check Panda site IDs for tmpPandaSiteID in convertDQ2toPandaIDList(tmpLoc): if tmpPandaSiteID in fullSiteList: if not tmpLoc in dq2Locations: dq2Locations.append(tmpLoc) break # check prefix mainly for MWT2 and MWT2_UC convertedScannedID = convSrmV2ID(tmpLoc) if convertedOrigSite.startswith(convertedScannedID) or \ convertedScannedID.startswith(convertedOrigSite): if not tmpLoc in dq2Locations: dq2Locations.append(tmpLoc) # empty if dq2Locations == []: tmpLog.error("cannot find replica locations for %s:%s to check metadata" % (siteID,dsName)) sys.exit(EC_Failed) # check completeness compInDQ2 = False global globalCompleteDsMap if globalCompleteDsMap.has_key(dsName): for tmpDQ2Loc in dq2Locations: if tmpDQ2Loc in globalCompleteDsMap[dsName]: compInDQ2 = True break # get metadata metaList = getReplicaMetadata(dsName,dq2Locations,verbose) # check metadata metaOK = False for metaItem in metaList: # replica deleted if isinstance(metaItem,types.StringType) and "No replica found at the location" in metaItem: continue if not globalUseShortLivedReplicas: # check the archived attribute if isinstance(metaItem['archived'],types.StringType) and metaItem['archived'].lower() in ['tobedeleted',]: continue # check replica lifetime if metaItem.has_key('expirationdate') and isinstance(metaItem['expirationdate'],types.StringType): try: import datetime expireDate = datetime.datetime.strptime(metaItem['expirationdate'],'%Y-%m-%d %H:%M:%S') # expire in 7 days if expireDate-datetime.datetime.utcnow() < datetime.timedelta(days=7): continue except: pass # all OK metaOK = True break # expiring if not metaOK: # get files expFilesMap['datasets'].append(dsName) expFilesMap['files'] += queryFilesInDataset(dsName,verbose) else: tmpFilesList = queryFilesInDataset(dsName,verbose) expOkFilesList += tmpFilesList # complete if compInDQ2: expCompDq2FilesList += tmpFilesList # keep to avoid redundant lookup globalExpFilesMap[mapKey] = expFilesMap globalExpOkFilesMap[mapKey] = expOkFilesList globalExpCompDq2FilesMap[mapKey] = expCompDq2FilesList if expFilesMap['datasets'] != []: msgStr = 'ignore replicas of ' for tmpDsStr in expFilesMap['datasets']: msgStr += '%s,' % tmpDsStr msgStr = msgStr[:-1] msgStr += ' at %s due to archived=ToBeDeleted or short lifetime < 7days. ' % siteID msgStr += 'If you want to use those replicas in spite of short lifetime, use --useShortLivedReplicas' tmpLog.info(msgStr) # return if getOKfiles: return expFilesMap,expOkFilesList,expCompDq2FilesList return expFilesMap # get replica metadata def getReplicaMetadata(name,dq2Locations,verbose): # get logger tmpLog = PLogger.getPandaLogger() if verbose: tmpLog.debug("getReplicaMetadata for %s" % (name)) # instantiate curl curl = _Curl() curl.verbose = verbose try: errStr = '' # get VUID url = baseURLDQ2 + '/ws_repository/rpc' data = {'operation':'queryDatasetByName','dsn':name,'version':0, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not access DQ2 server" sys.exit(EC_Failed) # parse datasets = {} if out == '\x00' or not checkDatasetInMap(name,out): errStr = "ERROR : VUID for %s was not found in DQ2" % name sys.exit(EC_Failed) # get VUIDs vuid = out[name]['vuids'][0] # get replica metadata retList = [] for location in dq2Locations: url = baseURLDQ2 + '/ws_location/rpc' data = {'operation':'queryDatasetReplicaMetadata','vuid':vuid, 'location':location,'API':'0_3_0', 'tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not access DQ2 server to get replica metadata" sys.exit(EC_Failed) # append retList.append(out) # return return retList except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) # query files in shadow datasets associated to container def getFilesInShadowDataset(contName,suffixShadow,verbose=False): fileList = [] # query files in PandaDB first to get running/failed files + files which are being added tmpList = getFilesInUseForAnal(contName,verbose) for tmpItem in tmpList: if not tmpItem in fileList: # append fileList.append(tmpItem) # get elements in container elements = getElementsFromContainer(contName,verbose) for tmpEle in elements: # remove merge tmpEle = re.sub('\.merge$','',tmpEle) shadowDsName = "%s%s" % (tmpEle,suffixShadow) # check existence tmpDatasets = getDatasets(shadowDsName,verbose) if len(tmpDatasets) == 0: continue # get files in shadow dataset tmpList = queryFilesInDataset(shadowDsName,verbose) for tmpItem in tmpList: if not tmpItem in fileList: # append fileList.append(tmpItem) return fileList # query files in shadow dataset associated to old dataset def getFilesInShadowDatasetOld(outDS,suffixShadow,verbose=False): shadowList = [] # query files in PandaDB first to get running/failed files + files which are being added tmpShadowList = getFilesInUseForAnal(outDS,verbose) for tmpItem in tmpShadowList: shadowList.append(tmpItem) # query files in shadow dataset for tmpItem in queryFilesInDataset("%s%s" % (outDS,suffixShadow),verbose): if not tmpItem in shadowList: shadowList.append(tmpItem) return shadowList # list datasets by GUIDs def listDatasetsByGUIDs(guids,dsFilter,verbose=False,forColl=False): # instantiate curl curl = _Curl() curl.verbose = verbose # get filter dsFilters = [] if dsFilter != '': dsFilters = dsFilter.split(',') # get logger tmpLog = PLogger.getPandaLogger() retMap = {} allMap = {} iLookUp = 0 guidLfnMap = {} checkedDSList = [] # loop over all GUIDs for guid in guids: # check existing map to avid redundant lookup if guidLfnMap.has_key(guid): retMap[guid] = guidLfnMap[guid] continue iLookUp += 1 if iLookUp % 20 == 0: time.sleep(1) # get vuids url = baseURLDQ2 + '/ws_content/rpc' data = {'operation': 'queryDatasetsWithFileByGUID','guid':guid, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) # failed if status != 0: if not verbose: print status,out errStr = "could not get dataset vuids for %s" % guid tmpLog.error(errStr) sys.exit(EC_Failed) # GUID was not registered in DQ2 if out == '\x00' or out == (): if verbose: errStr = "DQ2 gave an empty list for GUID=%s" % guid tmpLog.debug(errStr) allMap[guid] = [] continue tmpVUIDs = list(out) # get dataset name url = baseURLDQ2 + '/ws_repository/rpc' data = {'operation':'queryDatasetByVUIDs','vuids':tmpVUIDs, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) # failed if status != 0: if not verbose: print status,out errStr = "could not get dataset name for %s" % guid tmpLog.error(errStr) sys.exit(EC_Failed) # empty if out == '\x00': errStr = "DQ2 gave an empty list for VUID=%s" % tmpVUIDs tmpLog.error(errStr) sys.exit(EC_Failed) # datasets are deleted if out == {}: allMap[guid] = [] continue # check with filter tmpDsNames = [] tmpAllDsNames = [] for tmpDsName in out.keys(): # ignore junk datasets if tmpDsName.startswith('panda') or \ tmpDsName.startswith('user') or \ tmpDsName.startswith('group') or \ re.search('_sub\d+$',tmpDsName) != None or \ re.search('_dis\d+$',tmpDsName) != None or \ re.search('_shadow$',tmpDsName) != None: continue tmpAllDsNames.append(tmpDsName) # check with filter if dsFilters != []: flagMatch = False for tmpFilter in dsFilters: # replace . to \. tmpFilter = tmpFilter.replace('.','\.') # replace * to .* tmpFilter = tmpFilter.replace('*','.*') if re.search('^'+tmpFilter,tmpDsName) != None: flagMatch = True break # not match if not flagMatch: continue # append tmpDsNames.append(tmpDsName) # empty if tmpDsNames == []: # there may be multiple GUIDs for the same event, and some may be filtered by --eventPickDS allMap[guid] = tmpAllDsNames continue # duplicated if len(tmpDsNames) != 1: if not forColl: errStr = "there are multiple datasets %s for GUID:%s. Please set --eventPickDS and/or --eventPickStreamName to choose one dataset"\ % (str(tmpAllDsNames),guid) else: errStr = "there are multiple datasets %s for GUID:%s. Please set --eventPickDS to choose one dataset"\ % (str(tmpAllDsNames),guid) tmpLog.error(errStr) sys.exit(EC_Failed) # get LFN if not tmpDsNames[0] in checkedDSList: tmpMap = queryFilesInDataset(tmpDsNames[0],verbose) for tmpLFN,tmpVal in tmpMap.iteritems(): guidLfnMap[tmpVal['guid']] = (tmpDsNames[0],tmpLFN) checkedDSList.append(tmpDsNames[0]) # append if not guidLfnMap.has_key(guid): errStr = "LFN for %s in not found in %s" % (guid,tmpDsNames[0]) tmpLog.error(errStr) sys.exit(EC_Failed) retMap[guid] = guidLfnMap[guid] # return return retMap,allMap # register dataset def addDataset(name,verbose=False,location='',dsExist=False,allowProdDisk=False,dsCheck=True): # generate DUID/VUID duid = MiscUtils.wrappedUuidGen() vuid = MiscUtils.wrappedUuidGen() # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose try: errStr = '' # add if not dsExist: url = baseURLDQ2SSL + '/ws_repository/rpc' nTry = 3 for iTry in range(nTry): data = {'operation':'addDataset','dsn': name,'duid': duid,'vuid':vuid, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen(),'update':'yes'} status,out = curl.post(url,data,rucioAccount=True) if not dsCheck and out != None and re.search('DQDatasetExistsException',out) != None: dsExist = True break elif status != 0 or (out != None and re.search('Exception',out) != None): if iTry+1 == nTry: errStr = "ERROR : could not add dataset to DQ2 repository" sys.exit(EC_Failed) time.sleep(20) else: break # get VUID if dsExist: # check location tmpLocations = getLocations(name,[],'',False,verbose,getDQ2IDs=True) if location in tmpLocations: return # get VUID url = baseURLDQ2 + '/ws_repository/rpc' data = {'operation':'queryDatasetByName','dsn':name,'version':0, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not get VUID from DQ2" sys.exit(EC_Failed) # parse vuid = out[name]['vuids'][0] # add replica if re.search('SCRATCHDISK$',location) != None or re.search('USERDISK$',location) != None \ or re.search('LOCALGROUPDISK$',location) != None \ or (allowProdDisk and (re.search('PRODDISK$',location) != None or \ re.search('DATADISK$',location) != None)): url = baseURLDQ2SSL + '/ws_location/rpc' nTry = 3 for iTry in range(nTry): data = {'operation':'addDatasetReplica','vuid':vuid,'site':location, 'complete':0,'transferState':1, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0 or out != 1: if iTry+1 == nTry: errStr = "ERROR : could not register location : %s" % location sys.exit(EC_Failed) time.sleep(20) else: break else: errStr = "ERROR : registration at %s is disallowed" % location sys.exit(EC_Failed) except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) # create dataset container def createContainer(name,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose try: errStr = '' # add url = baseURLDQ2SSL + '/ws_dq2/rpc' nTry = 3 for iTry in range(nTry): data = {'operation':'container_create','name': name, 'API':'030','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0 or (out != None and re.search('Exception',out) != None): if iTry+1 == nTry: errStr = "ERROR : could not create container in DQ2" sys.exit(EC_Failed) time.sleep(20) else: break except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) # add datasets to container def addDatasetsToContainer(name,datasets,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose try: errStr = '' # add url = baseURLDQ2SSL + '/ws_dq2/rpc' nTry = 3 for iTry in range(nTry): data = {'operation':'container_register','name': name, 'datasets':datasets,'API':'030', 'tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0 or (out != None and re.search('Exception',out) != None): if iTry+1 == nTry: errStr = "ERROR : could not add DQ2 datasets to container" sys.exit(EC_Failed) time.sleep(20) else: break except: print status,out if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) # get container elements def getElementsFromContainer(name,verbose=False): # instantiate curl curl = _Curl() curl.verbose = verbose try: errStr = '' # get elements url = baseURLDQ2 + '/ws_dq2/rpc' data = {'operation':'container_retrieve','name': name, 'API':'030','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) if status != 0 or (isinstance(out,types.StringType) and re.search('Exception',out) != None): errStr = "ERROR : could not get container %s from DQ2" % name sys.exit(EC_Failed) return out except: print status,out type, value, traceBack = sys.exc_info() print "%s %s" % (type,value) if errStr != '': print errStr else: print "ERROR : invalid DQ2 response" sys.exit(EC_Failed) # convert srmv2 site to srmv1 site ID def convSrmV2ID(tmpSite): # keep original name to avoid double conversion origSite = tmpSite # doesn't convert FR/IT/UK sites for tmpPrefix in ['IN2P3-','INFN-','UKI-','GRIF-','DESY-','UNI-','RU-', 'LIP-','RO-']: if tmpSite.startswith(tmpPrefix): tmpSite = re.sub('_[A-Z,0-9]+DISK$', 'DISK',tmpSite) tmpSite = re.sub('_[A-Z,0-9]+TAPE$', 'DISK',tmpSite) tmpSite = re.sub('_PHYS-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('_PERF-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('_DET-[A-Z,0-9]+$', 'DISK',tmpSite) tmpSite = re.sub('_SOFT-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('_TRIG-DAQ$','DISK',tmpSite) return tmpSite # parch for CERN EOS if tmpSite.startswith('CERN-PROD_EOS'): return 'CERN-PROD_EOSDISK' # parch for CERN TMP if tmpSite.startswith('CERN-PROD_TMP'): return 'CERN-PROD_TMPDISK' # parch for CERN OLD if tmpSite.startswith('CERN-PROD_OLD') or tmpSite.startswith('CERN-PROD_LOCAL'): return 'CERN-PROD_OLDDISK' # patch for SRM v2 tmpSite = re.sub('-[^-_]+_[A-Z,0-9]+DISK$', 'DISK',tmpSite) tmpSite = re.sub('-[^-_]+_[A-Z,0-9]+TAPE$', 'DISK',tmpSite) tmpSite = re.sub('-[^-_]+_PHYS-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('-[^-_]+_PERF-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('-[^-_]+_DET-[A-Z,0-9]+$', 'DISK',tmpSite) tmpSite = re.sub('-[^-_]+_SOFT-[A-Z,0-9]+$','DISK',tmpSite) tmpSite = re.sub('-[^-_]+_TRIG-DAQ$','DISK',tmpSite) # SHOULD BE REMOVED Once all sites and DQ2 migrate to srmv2 # patch for BNL if tmpSite in ['BNLDISK','BNLTAPE']: tmpSite = 'BNLPANDA' # patch for LYON if tmpSite in ['LYONDISK','LYONTAPE']: tmpSite = 'IN2P3-CCDISK' # patch for TAIWAN if tmpSite.startswith('ASGC'): tmpSite = 'TAIWANDISK' # patch for CERN if tmpSite.startswith('CERN'): tmpSite = 'CERNDISK' # patche for some special sites where automatic conjecture is impossible if tmpSite == 'UVIC': tmpSite = 'VICTORIA' # US T2s if origSite == tmpSite: tmpSite = re.sub('_[A-Z,0-9]+DISK$', '',tmpSite) tmpSite = re.sub('_[A-Z,0-9]+TAPE$', '',tmpSite) tmpSite = re.sub('_PHYS-[A-Z,0-9]+$','',tmpSite) tmpSite = re.sub('_PERF-[A-Z,0-9]+$','',tmpSite) tmpSite = re.sub('_DET-[A-Z,0-9]+$', '',tmpSite) tmpSite = re.sub('_SOFT-[A-Z,0-9]+$','',tmpSite) tmpSite = re.sub('_TRIG-DAQ$','',tmpSite) if tmpSite == 'NET2': tmpSite = 'BU' if tmpSite == 'MWT2_UC': tmpSite = 'MWT2' # return return tmpSite # check tape sites def isTapeSite(origTmpSite): if re.search('TAPE$',origTmpSite) != None or \ re.search('PROD_TZERO$',origTmpSite) != None or \ re.search('PROD_TMPDISK$',origTmpSite) != None or \ re.search('PROD_DAQ$',origTmpSite) != None: return True return False # check online site def isOnlineSite(origTmpSite): # get PandaID tmpPandaSite = convertDQ2toPandaID(origTmpSite) # check if Panda site if not PandaSites.has_key(tmpPandaSite): return False # exclude long,local queues if isExcudedSite(tmpPandaSite): return False # status if PandaSites[tmpPandaSite]['status'] == 'online': return True return False # get locations def getLocations(name,fileList,cloud,woFileCheck,verbose=False,expCloud=False,getReserved=False, getTapeSites=False,getDQ2IDs=False,locCandidates=None,removeDS=False, removedDatasets=[],useOutContainer=False,includeIncomplete=False, notSiteStatusCheck=False,useCVMFS=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # get logger tmpLog = PLogger.getPandaLogger() try: errStr = '' names = name.split(',') # loop over all names retSites = [] retSiteMap = {} resRetSiteMap = {} resBadStSites = {} resTapeSites = {} retDQ2IDs = [] retDQ2IDmap = {} allOut = {} iLookUp = 0 resUsedDsMap = {} global globalCompleteDsMap # convert candidates for SRM v2 if locCandidates != None: locCandidatesSrmV2 = [] for locTmp in locCandidates: locCandidatesSrmV2.append(convSrmV2ID(locTmp)) # loop over all names for tmpName in names: # ignore removed datasets if tmpName in removedDatasets: continue iLookUp += 1 if iLookUp % 20 == 0: time.sleep(1) # container containerFlag = False if tmpName.endswith('/'): containerFlag = True # get VUID url = baseURLDQ2 + '/ws_repository/rpc' data = {'operation':'queryDatasetByName','dsn':tmpName,'version':0, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.get(url,data,rucioAccount=True) if status != 0 or out == '\x00' or (not checkDatasetInMap(tmpName,out)): errStr = "ERROR : could not find %s in DQ2 DB. Check if the dataset name is correct" \ % tmpName if getReserved and getTapeSites: sys.exit(EC_Failed) if verbose: print errStr return retSites # get real datasetname tmpName = getDatasetValueInMap(tmpName,out) # parse duid = out[tmpName]['duid'] # get replica location url = baseURLDQ2 + '/ws_location/rpc' if containerFlag: data = {'operation':'listContainerReplicas','cn':tmpName, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} else: data = {'operation':'listDatasetReplicas','duid':duid, 'API':'0_3_0','tuid':MiscUtils.wrappedUuidGen()} status,out = curl.post(url,data,rucioAccount=True) if status != 0: errStr = "ERROR : could not query location for %s" % tmpName sys.exit(EC_Failed) # convert container format to dataset's one outTmp = {} if containerFlag: # count number of complete elements for tmpEleName,tmpEleVal in out.iteritems(): # ignore removed datasets if tmpEleName in removedDatasets: continue for tmpEleVUID,tmpEleLocs in tmpEleVal.iteritems(): # get complete locations tmpFoundFlag = False for tmpEleLoc in tmpEleLocs[1]: # don't use TAPE if isTapeSite(tmpEleLoc): if not resTapeSites.has_key(tmpEleLoc): resTapeSites[tmpEleLoc] = [] if not tmpEleName in resTapeSites[tmpEleLoc]: resTapeSites[tmpEleLoc].append(tmpEleName) continue # append if not outTmp.has_key(tmpEleLoc): outTmp[tmpEleLoc] = [{'found':0,'useddatasets':[]}] # increment outTmp[tmpEleLoc][0]['found'] += 1 # append list if not tmpEleName in outTmp[tmpEleLoc][0]['useddatasets']: outTmp[tmpEleLoc][0]['useddatasets'].append(tmpEleName) # found online site if isOnlineSite(tmpEleLoc): tmpFoundFlag = True # add to global map if not globalCompleteDsMap.has_key(tmpEleName): globalCompleteDsMap[tmpEleName] = [] globalCompleteDsMap[tmpEleName].append(tmpEleLoc) # use incomplete locations if no complete replica at online sites if includeIncomplete or not tmpFoundFlag: for tmpEleLoc in tmpEleLocs[0]: # don't use TAPE if isTapeSite(tmpEleLoc): if not resTapeSites.has_key(tmpEleLoc): resTapeSites[tmpEleLoc] = [] if not tmpEleName in resTapeSites[tmpEleLoc]: resTapeSites[tmpEleLoc].append(tmpEleName) continue # append if not outTmp.has_key(tmpEleLoc): outTmp[tmpEleLoc] = [{'found':0,'useddatasets':[]}] # increment outTmp[tmpEleLoc][0]['found'] += 1 # append list if not tmpEleName in outTmp[tmpEleLoc][0]['useddatasets']: outTmp[tmpEleLoc][0]['useddatasets'].append(tmpEleName) else: # check completeness tmpIncompList = [] tmpFoundFlag = False for tmpOutKey,tmpOutVar in out.iteritems(): # don't use TAPE if isTapeSite(tmpOutKey): if not resTapeSites.has_key(tmpOutKey): resTapeSites[tmpOutKey] = [] if not tmpName in resTapeSites[tmpOutKey]: resTapeSites[tmpOutKey].append(tmpName) continue # protection against unchecked tmpNfound = tmpOutVar[0]['found'] # complete or not if isinstance(tmpNfound,types.IntType) and tmpNfound == tmpOutVar[0]['total']: outTmp[tmpOutKey] = [{'found':1,'useddatasets':[tmpName]}] # found online site if isOnlineSite(tmpOutKey): tmpFoundFlag = True # add to global map if not globalCompleteDsMap.has_key(tmpName): globalCompleteDsMap[tmpName] = [] globalCompleteDsMap[tmpName].append(tmpOutKey) else: # keep just in case if not tmpOutKey in tmpIncompList: tmpIncompList.append(tmpOutKey) # use incomplete replicas when no complete at online sites if includeIncomplete or not tmpFoundFlag: for tmpOutKey in tmpIncompList: outTmp[tmpOutKey] = [{'found':1,'useddatasets':[tmpName]}] # replace out = outTmp # sum for tmpOutKey,tmpOutVar in out.iteritems(): if not allOut.has_key(tmpOutKey): allOut[tmpOutKey] = [{'found':0,'useddatasets':[]}] allOut[tmpOutKey][0]['found'] += tmpOutVar[0]['found'] allOut[tmpOutKey][0]['useddatasets'] += tmpOutVar[0]['useddatasets'] # replace out = allOut if verbose: print out # choose sites where most files are available if not woFileCheck: tmpMaxFiles = -1 for origTmpSite,origTmpInfo in out.iteritems(): # get PandaID tmpPandaSite = convertDQ2toPandaID(origTmpSite) # check status if PandaSites.has_key(tmpPandaSite) and (notSiteStatusCheck or PandaSites[tmpPandaSite]['status'] == 'online'): # don't use TAPE if isTapeSite(origTmpSite): if not resTapeSites.has_key(origTmpSite): if origTmpInfo[0].has_key('useddatasets'): resTapeSites[origTmpSite] = origTmpInfo[0]['useddatasets'] else: resTapeSites[origTmpSite] = names continue # check the number of available files if tmpMaxFiles < origTmpInfo[0]['found']: tmpMaxFiles = origTmpInfo[0]['found'] # remove sites for origTmpSite in out.keys(): if out[origTmpSite][0]['found'] < tmpMaxFiles: # use sites where most files are avaialble if output container is not used if not useOutContainer: del out[origTmpSite] if verbose: print out tmpFirstDump = True for origTmpSite,origTmpInfo in out.iteritems(): # don't use TAPE if isTapeSite(origTmpSite): if not resTapeSites.has_key(origTmpSite): resTapeSites[origTmpSite] = origTmpInfo[0]['useddatasets'] continue # collect DQ2 IDs if not origTmpSite in retDQ2IDs: retDQ2IDs.append(origTmpSite) for tmpUDS in origTmpInfo[0]['useddatasets']: if not retDQ2IDmap.has_key(tmpUDS): retDQ2IDmap[tmpUDS] = [] if not origTmpSite in retDQ2IDmap[tmpUDS]: retDQ2IDmap[tmpUDS].append(origTmpSite) # patch for SRM v2 tmpSite = convSrmV2ID(origTmpSite) # if candidates are limited if locCandidates != None and (not tmpSite in locCandidatesSrmV2): continue if verbose: tmpLog.debug('%s : %s->%s' % (tmpName,origTmpSite,tmpSite)) # check cloud, DQ2 ID and status tmpSiteBeforeLoop = tmpSite for tmpID,tmpSpec in PandaSites.iteritems(): # reset tmpSite = tmpSiteBeforeLoop # get list of DQ2 IDs srmv2ddmList = [] for tmpDdmID in tmpSpec['setokens'].values(): srmv2ddmList.append(convSrmV2ID(tmpDdmID)) # dump if tmpFirstDump: if verbose: pass if tmpSite in srmv2ddmList or convSrmV2ID(tmpSpec['ddm']).startswith(tmpSite) \ or (useCVMFS and tmpSpec['iscvmfs'] == True): # overwrite tmpSite for srmv1 tmpSite = convSrmV2ID(tmpSpec['ddm']) # exclude long,xrootd,local queues if isExcudedSite(tmpID): continue if not tmpSite in retSites: retSites.append(tmpSite) # just collect locations when file check is disabled if woFileCheck: break # append site if tmpSpec['status'] == 'online' or notSiteStatusCheck: # return sites in a cloud when it is specified or all sites if tmpSpec['cloud'] == cloud or (not expCloud): appendMap = retSiteMap else: appendMap = resRetSiteMap # mapping between location and Panda siteID if not appendMap.has_key(tmpSite): appendMap[tmpSite] = [] if not tmpID in appendMap[tmpSite]: appendMap[tmpSite].append(tmpID) if origTmpInfo[0].has_key('useddatasets'): if not tmpID in resUsedDsMap: resUsedDsMap[tmpID] = [] resUsedDsMap[tmpID] += origTmpInfo[0]['useddatasets'] else: # not interested in another cloud if tmpSpec['cloud'] != cloud and expCloud: continue # keep bad status sites for info if not resBadStSites.has_key(tmpSpec['status']): resBadStSites[tmpSpec['status']] = [] if not tmpID in resBadStSites[tmpSpec['status']]: resBadStSites[tmpSpec['status']].append(tmpID) tmpFirstDump = False # retrun DQ2 IDs if getDQ2IDs: if includeIncomplete: return retDQ2IDmap,resUsedDsMap return retDQ2IDs # return list when file check is not required if woFileCheck: return retSites # use reserved map when the cloud doesn't hold the dataset if retSiteMap == {} and (not expCloud) and (not getReserved): retSiteMap = resRetSiteMap # reset reserved map for expCloud if getReserved and expCloud: resRetSiteMap = {} # return map if verbose: if not getReserved: tmpLog.debug("getLocations -> %s" % retSiteMap) else: tmpLog.debug("getLocations pri -> %s" % retSiteMap) tmpLog.debug("getLocations sec -> %s" % resRetSiteMap) # print bad status sites for info if retSiteMap == {} and resRetSiteMap == {} and resBadStSites != {}: msgFirstFlag = True for tmpStatus,tmpSites in resBadStSites.iteritems(): # ignore panda secific site if tmpStatus.startswith('panda_'): continue if msgFirstFlag: tmpLog.warning("the following sites hold %s but they are not online" % name) msgFirstFlag = False print " status=%s : %s" % (tmpStatus,tmpSites) if not getReserved: return retSiteMap elif not getTapeSites: return retSiteMap,resRetSiteMap elif not removeDS: return retSiteMap,resRetSiteMap,resTapeSites else: return retSiteMap,resRetSiteMap,resTapeSites,resUsedDsMap except: print status,out if errStr != '': print errStr else: type, value, traceBack = sys.exc_info() print "ERROR : invalid DQ2 response - %s %s" % (type,value) sys.exit(EC_Failed) #@ Returns number of events per file in a given dataset #SP 2006 # def nEvents(name, verbose=False, askServer=True, fileList = {}, scanDir = '.', askUser=True): # @ These declarations can be moved to the configuration section at the very beginning # Here just for code clarity # # Parts of the query str1="/?dset=" str2="&get=evperfile" # Form full query string m_query = baseURLMON+str1+name+str2 manualEnter = True # Send query get number of events per file if askServer: nEvents=urllib.urlopen(m_query).read() if verbose: print m_query print nEvents if re.search('HTML',nEvents) == None and nEvents != '-1': manualEnter = False else: # use ROOT to get # of events try: import ROOT rootFile = ROOT.TFile("%s/%s" % (scanDir,fileList[0])) tree = ROOT.gDirectory.Get( 'CollectionTree' ) nEvents = tree.GetEntriesFast() # disable if nEvents > 0: manualEnter = False except: if verbose: type, value, traceBack = sys.exc_info() print "ERROR : could not get nEvents with ROOT - %s %s" % (type,value) # In case of error PANDAMON server returns full HTML page # Normally return an integer if manualEnter: if askUser: if askServer: print "Could not get the # of events from MetaDB for %s " % name while True: str = raw_input("Enter the number of events per file (or set --nEventsPerFile) : ") try: nEvents = int(str) break except: pass else: print "ERROR : Could not get the # of events from MetaDB for %s " % name sys.exit(EC_Failed) if verbose: print "Dataset %s has %s evetns per file" % (name,nEvents) return int(nEvents) # get PFN from LRC def _getPFNsLRC(lfns,dq2url,verbose): pfnMap = {} # instantiate curl curl = _Curl() curl.verbose = verbose # get PoolFileCatalog iLFN = 0 strLFNs = '' url = dq2url + 'lrc/PoolFileCatalog' firstError = True # check if GUID lookup is supported useGUID = True status,out = curl.get(url,{'guids':'test'}) if status ==0 and out == 'Must GET or POST a list of LFNs!': useGUID = False for lfn,vals in lfns.iteritems(): iLFN += 1 # make argument if useGUID: strLFNs += '%s ' % vals['guid'] else: strLFNs += '%s ' % lfn if iLFN % 40 == 0 or iLFN == len(lfns): # get PoolFileCatalog strLFNs = strLFNs.rstrip() if useGUID: data = {'guids':strLFNs} else: data = {'lfns':strLFNs} # avoid too long argument strLFNs = '' # execute status,out = curl.get(url,data) time.sleep(2) if out.startswith('Error'): # LFN not found continue if status != 0 or (not out.startswith('<?xml')): if firstError: print status,out print "ERROR : LRC %s returned invalid response" % dq2url firstError = False continue # parse try: root = xml.dom.minidom.parseString(out) files = root.getElementsByTagName('File') for file in files: # get PFN and LFN nodes physical = file.getElementsByTagName('physical')[0] pfnNode = physical.getElementsByTagName('pfn')[0] logical = file.getElementsByTagName('logical')[0] lfnNode = logical.getElementsByTagName('lfn')[0] # convert UTF8 to Raw pfn = str(pfnNode.getAttribute('name')) lfn = str(lfnNode.getAttribute('name')) # remove /srm/managerv1?SFN= pfn = re.sub('/srm/managerv1\?SFN=','',pfn) # append pfnMap[lfn] = pfn except: print status,out type, value, traceBack = sys.exc_info() print "ERROR : could not parse XML - %s %s" % (type, value) sys.exit(EC_Failed) # return return pfnMap # get list of missing LFNs from LRC def getMissLFNsFromLRC(files,url,verbose=False,nFiles=0): # get PFNs pfnMap = _getPFNsLRC(files,url,verbose) # check Files missFiles = [] for file in files: if not file in pfnMap.keys(): missFiles.append(file) return missFiles # get PFN list from LFC def _getPFNsLFC(fileMap,site,explicitSE,verbose=False,nFiles=0): pfnMap = {} for path in sys.path: # look for base package basePackage = __name__.split('.')[-2] if os.path.exists(path) and os.path.isdir(path) and basePackage in os.listdir(path): lfcClient = '%s/%s/LFCclient.py' % (path,basePackage) if explicitSE: stList = getSE(site) else: stList = [] lfcHost = getLFC(site) inFile = '%s_in' % MiscUtils.wrappedUuidGen() outFile = '%s_out' % MiscUtils.wrappedUuidGen() # write GUID/LFN ifile = open(inFile,'w') fileKeys = fileMap.keys() fileKeys.sort() for lfn in fileKeys: vals = fileMap[lfn] ifile.write('%s %s\n' % (vals['guid'],lfn)) ifile.close() # construct command gridSrc = _getGridSrc() com = '%s python -Wignore %s -l %s -i %s -o %s -n %s' % (gridSrc,lfcClient,lfcHost,inFile,outFile,nFiles) for index,stItem in enumerate(stList): if index != 0: com += ',%s' % stItem else: com += ' -s %s' % stItem if verbose: com += ' -v' print com # exeute status = os.system(com) if status == 0: ofile = open(outFile) line = ofile.readline() line = re.sub('\n','',line) exec 'pfnMap = %s' %line ofile.close() # remove tmp files try: os.remove(inFile) os.remove(outFile) except: pass # failed if status != 0: print "ERROR : failed to access LFC %s" % lfcHost return {} break # return return pfnMap # get list of missing LFNs from LFC def getMissLFNsFromLFC(fileMap,site,explicitSE,verbose=False,nFiles=0,shadowList=[],dsStr='',removedDS=[], skipScan=False): # get logger tmpLog = PLogger.getPandaLogger() missList = [] # ignore files in shadow if shadowList != []: tmpFileMap = {} for lfn,vals in fileMap.iteritems(): if not lfn in shadowList: tmpFileMap[lfn] = vals else: tmpFileMap = fileMap # ignore expiring files if dsStr != '': tmpTmpFileMap = {} expFilesMap,expOkFilesList,expCompInDQ2FilesList = getExpiringFiles(dsStr,removedDS,site,verbose,getOKfiles=True) # collect files in incomplete replicas for lfn,vals in tmpFileMap.iteritems(): if lfn in expOkFilesList and not lfn in expCompInDQ2FilesList: tmpTmpFileMap[lfn] = vals tmpFileMap = tmpTmpFileMap # skipScan use only complete replicas if skipScan and expCompInDQ2FilesList == []: tmpLog.info("%s may hold %s files at most in incomplete replicas but they are not used when --skipScan is set" % \ (site,len(expOkFilesList))) # get PFNS if tmpFileMap != {} and not skipScan: tmpLog.info("scanning LFC %s for files in incompete datasets at %s" % (getLFC(site),site)) pfnMap = _getPFNsLFC(tmpFileMap,site,explicitSE,verbose,nFiles) else: pfnMap = {} for lfn,vals in fileMap.iteritems(): if (not vals['guid'] in pfnMap.keys()) and (not lfn in shadowList) \ and not lfn in expCompInDQ2FilesList: missList.append(lfn) # return return missList # get grid source file def _getGridSrc(): # set Grid setup.sh if needed status,out = commands.getstatusoutput('voms-proxy-info --version') athenaStatus,athenaPath = commands.getstatusoutput('which athena.py') if status == 0: gridSrc = '' if athenaStatus == 0 and athenaPath.startswith('/afs/in2p3.fr'): # for LYON, to avoid missing LD_LIBRARY_PATH gridSrc = '/afs/in2p3.fr/grid/profiles/lcg_env.sh' elif athenaStatus == 0 and re.search('^/afs/\.*cern.ch',athenaPath) != None: # for CERN, VDT is already installed gridSrc = '/dev/null' else: # set Grid setup.sh if os.environ.has_key('PATHENA_GRID_SETUP_SH'): gridSrc = os.environ['PATHENA_GRID_SETUP_SH'] else: if not os.environ.has_key('CMTSITE'): os.environ['CMTSITE'] = '' if os.environ['CMTSITE'] == 'CERN' or (athenaStatus == 0 and \ re.search('^/afs/\.*cern.ch',athenaPath) != None): gridSrc = '/dev/null' elif os.environ['CMTSITE'] == 'BNL': gridSrc = '/afs/usatlas.bnl.gov/osg/client/@sys/current/setup.sh' else: # try to determin site using path to athena if athenaStatus == 0 and athenaPath.startswith('/afs/in2p3.fr'): # LYON gridSrc = '/afs/in2p3.fr/grid/profiles/lcg_env.sh' elif athenaStatus == 0 and athenaPath.startswith('/cvmfs/atlas.cern.ch'): # CVMFS if not os.environ.has_key('ATLAS_LOCAL_ROOT_BASE'): os.environ['ATLAS_LOCAL_ROOT_BASE'] = '/cvmfs/atlas.cern.ch/repo/ATLASLocalRootBase' gridSrc = os.environ['ATLAS_LOCAL_ROOT_BASE'] + '/user/pandaGridSetup.sh' else: print "ERROR : PATHENA_GRID_SETUP_SH is not defined in envvars" print " for CERN on SLC6 : export PATHENA_GRID_SETUP_SH=/dev/null" print " for CERN on SLC5 : export PATHENA_GRID_SETUP_SH=/afs/cern.ch/project/gd/LCG-share/current_3.2/etc/profile.d/grid_env.sh" print " for LYON : export PATHENA_GRID_SETUP_SH=/afs/in2p3.fr/grid/profiles/lcg_env.sh" print " for BNL : export PATHENA_GRID_SETUP_SH=/afs/usatlas.bnl.gov/osg/client/@sys/current/setup.sh" return False # check grid-proxy if gridSrc != '': gridSrc = 'source %s > /dev/null;' % gridSrc # some grid_env.sh doen't correct PATH/LD_LIBRARY_PATH gridSrc = "unset LD_LIBRARY_PATH; unset PYTHONPATH; unset MANPATH; export PATH=/usr/local/bin:/bin:/usr/bin; %s" % gridSrc # return return gridSrc # get DN def getDN(origString): shortName = '' distinguishedName = '' for line in origString.split('/'): if line.startswith('CN='): distinguishedName = re.sub('^CN=','',line) distinguishedName = re.sub('\d+$','',distinguishedName) distinguishedName = re.sub('\.','',distinguishedName) distinguishedName = distinguishedName.strip() if re.search(' ',distinguishedName) != None: # look for full name distinguishedName = distinguishedName.replace(' ','') break elif shortName == '': # keep short name shortName = distinguishedName distinguishedName = '' # use short name if distinguishedName == '': distinguishedName = shortName # return return distinguishedName from HTMLParser import HTMLParser class _monHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.map = {} self.switch = False self.td = False def getMap(self): retMap = {} if len(self.map) > 1: names = self.map[0] vals = self.map[1] # values try: retMap['total'] = int(vals[names.index('Jobs')]) except: retMap['total'] = 0 try: retMap['finished'] = int(vals[names.index('Finished')]) except: retMap['finished'] = 0 try: retMap['failed'] = int(vals[names.index('Failed')]) except: retMap['failed'] = 0 retMap['running'] = retMap['total'] - retMap['finished'] - \ retMap['failed'] return retMap def handle_data(self, data): if self.switch: if self.td: self.td = False self.map[len(self.map)-1].append(data) else: self.map[len(self.map)-1][-1] += data else: if data == "Job Sets:": self.switch = True def handle_starttag(self, tag, attrs): if self.switch and tag == 'tr': self.map[len(self.map)] = [] if self.switch and tag == 'td': self.td = True def handle_endtag(self, tag): if self.switch and self.td: self.map[len(self.map)-1].append("") self.td = False # get jobInfo from Mon def getJobStatusFromMon(id,verbose=False): # get name shortName = '' distinguishedName = '' for line in commands.getoutput('%s grid-proxy-info -identity' % _getGridSrc()).split('/'): if line.startswith('CN='): distinguishedName = re.sub('^CN=','',line) distinguishedName = re.sub('\d+$','',distinguishedName) distinguishedName = distinguishedName.strip() if re.search(' ',distinguishedName) != None: # look for full name break elif shortName == '': # keep short name shortName = distinguishedName distinguishedName = '' # use short name if distinguishedName == '': distinguishedName = shortName # instantiate curl curl = _Curl() curl.verbose = verbose data = {'job':'*', 'jobDefinitionID' : id, 'user' : distinguishedName, 'days' : 100} # execute status,out = curl.get(baseURLMON,data) if status != 0 or re.search('Panda monitor and browser',out)==None: return {} # parse parser = _monHTMLParser() for line in out.split('\n'): if re.search('Job Sets:',line) != None: parser.feed( line ) break return parser.getMap() def isDirectAccess(site,usingRAW=False,usingTRF=False,usingARA=False): # unknown site if not PandaSites.has_key(site): return False # parse copysetup params = PandaSites[site]['copysetup'].split('^') # doesn't use special parameters if len(params) < 5: return False # directIn directIn = params[4] if directIn != 'True': return False # xrootd uses local copy for RAW newPrefix = params[2] if newPrefix.startswith('root:'): if usingRAW: return False # official TRF doesn't work with direct dcap/xrootd if usingTRF and (not usingARA): if newPrefix.startswith('root:') or newPrefix.startswith('dcap:') or \ newPrefix.startswith('dcache:') or newPrefix.startswith('gsidcap:'): return False # return return True # run brokerage def runBrokerage(sites,atlasRelease,cmtConfig=None,verbose=False,trustIS=False,cacheVer='',processingType='', loggingFlag=False,memorySize=0,useDirectIO=False,siteGroup=None,maxCpuCount=-1,rootVer=''): # use only directIO sites nonDirectSites = [] if useDirectIO: tmpNewSites = [] for tmpSite in sites: if isDirectAccess(tmpSite): tmpNewSites.append(tmpSite) else: nonDirectSites.append(tmpSite) sites = tmpNewSites if sites == []: if not loggingFlag: return 0,'ERROR : no candidate.' else: return 0,{'site':'ERROR : no candidate.','logInfo':[]} # choose at most 50 sites randomly to avoid too many lookup random.shuffle(sites) sites = sites[:50] # serialize strSites = pickle.dumps(sites) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/runBrokerage' data = {'sites':strSites, 'atlasRelease':atlasRelease} if cmtConfig != None: data['cmtConfig'] = cmtConfig if trustIS: data['trustIS'] = True if maxCpuCount > 0: data['maxCpuCount'] = maxCpuCount if cacheVer != '': # change format if needed cacheVer = re.sub('^-','',cacheVer) match = re.search('^([^_]+)_(\d+\.\d+\.\d+\.\d+\.*\d*)$',cacheVer) if match != None: cacheVer = '%s-%s' % (match.group(1),match.group(2)) else: # nightlies match = re.search('_(rel_\d+)$',cacheVer) if match != None: # use base release as cache version cacheVer = '%s:%s' % (atlasRelease,match.group(1)) # use cache for brokerage data['atlasRelease'] = cacheVer # use ROOT ver if rootVer != '' and data['atlasRelease'] == '': data['atlasRelease'] = 'ROOT-%s' % rootVer if processingType != '': # set processingType mainly for HC data['processingType'] = processingType # enable logging if loggingFlag: data['loggingFlag'] = True # memory size if not memorySize in [-1,0,None,'NULL']: data['memorySize'] = memorySize # site group if not siteGroup in [None,-1]: data['siteGroup'] = siteGroup status,output = curl.get(url,data) try: if not loggingFlag: return status,output else: outputPK = pickle.loads(output) # add directIO info if nonDirectSites != []: if not outputPK.has_key('logInfo'): outputPK['logInfo'] = [] for tmpSite in nonDirectSites: msgBody = 'action=skip site=%s reason=nondirect - not directIO site' % tmpSite outputPK['logInfo'].append(msgBody) return status,outputPK except: type, value, traceBack = sys.exc_info() print output print "ERROR runBrokerage : %s %s" % (type,value) return EC_Failed,None # run rebrokerage def runReBrokerage(jobID,libDS='',cloud=None,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/runReBrokerage' data = {'jobID':jobID} if cloud != None: data['cloud'] = cloud if not libDS in ['',None,'NULL']: data['libDS'] = libDS retVal = curl.get(url,data) # communication error if retVal[0] != 0: return retVal # succeeded if retVal[1] == True: return 0,'' # server error errMsg = retVal[1] if errMsg.startswith('ERROR: '): # remove ERROR: errMsg = re.sub('ERROR: ','',errMsg) return EC_Failed,errMsg # retry failed jobs in Active def retryFailedJobsInActive(jobID,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/retryFailedJobsInActive' data = {'jobID':jobID} retVal = curl.get(url,data) # communication error if retVal[0] != 0: return retVal # succeeded if retVal[1] == True: return 0,'' # server error errMsg = retVal[1] if errMsg.startswith('ERROR: '): # remove ERROR: errMsg = re.sub('ERROR: ','',errMsg) return EC_Failed,errMsg # send brokerage log def sendBrokerageLog(jobID,jobsetID,brokerageLogs,verbose): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose msgList = [] for tmpMsgBody in brokerageLogs: if not jobsetID in [None,'NULL']: tmpMsg = ' : jobset=%s jobdef=%s : %s' % (jobsetID,jobID,tmpMsgBody) else: tmpMsg = ' : jobdef=%s : %s' % (jobID,tmpMsgBody) msgList.append(tmpMsg) # execute url = baseURLSSL + '/sendLogInfo' data = {'msgType':'analy_brokerage', 'msgList':pickle.dumps(msgList)} retVal = curl.post(url,data) return True # exclude long,xrootd,local queues def isExcudedSite(tmpID): excludedSite = False for exWord in ['ANALY_LONG_','_LOCAL','_test']: if re.search(exWord,tmpID,re.I) != None: excludedSite = True break return excludedSite # get default space token def getDefaultSpaceToken(fqans,defaulttoken): # mapping is not defined if defaulttoken == '': return '' # loop over all groups for tmpStr in defaulttoken.split(','): # extract group and token items = tmpStr.split(':') if len(items) != 2: continue tmpGroup = items[0] tmpToken = items[1] # look for group if re.search(tmpGroup+'/',fqans) != None: return tmpToken # not found return '' # use dev server def useDevServer(): global baseURL baseURL = 'http://aipanda007.cern.ch:25080/server/panda' global baseURLSSL baseURLSSL = 'https://aipanda007.cern.ch:25443/server/panda' global baseURLCSRV baseURLCSRV = 'https://aipanda007.cern.ch:25443/server/panda' global baseURLCSRVSSL baseURLCSRVSSL = 'https://aipanda007.cern.ch:25443/server/panda' global baseURLSUB baseURLSUB = 'http://atlpan.web.cern.ch/atlpan' # use INTR server def useIntrServer(): global baseURL baseURL = 'http://aipanda027.cern.ch:25080/server/panda' global baseURLSSL baseURLSSL = 'https://aipanda027.cern.ch:25443/server/panda' # set server def setServer(urls): global baseURL baseURL = urls.split(',')[0] global baseURLSSL baseURLSSL = urls.split(',')[-1] # set cache server def setCacheServer(urls): global baseURLCSRV baseURLCSRV = urls.split(',')[0] global baseURLCSRVSSL baseURLCSRVSSL = urls.split(',')[-1] # register proxy key def registerProxyKey(credname,origin,myproxy,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose curl.verifyHost = True # execute url = baseURLSSL + '/registerProxyKey' data = {'credname': credname, 'origin' : origin, 'myproxy' : myproxy } return curl.post(url,data) # get proxy key def getProxyKey(verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getProxyKey' status,output = curl.post(url,{}) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getProxyKey : %s %s" % (type,value) return EC_Failed,None # add site access def addSiteAccess(siteID,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/addSiteAccess' data = {'siteID': siteID} status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR listSiteAccess : %s %s" % (type,value) return EC_Failed,None # list site access def listSiteAccess(siteID,verbose=False,longFormat=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/listSiteAccess' data = {} if siteID != None: data['siteID'] = siteID if longFormat: data['longFormat'] = True status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR listSiteAccess : %s %s" % (type,value) return EC_Failed,None # update site access def updateSiteAccess(method,siteid,userName,verbose=False,value=''): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/updateSiteAccess' data = {'method':method,'siteid':siteid,'userName':userName} if value != '': data['attrValue'] = value status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,output except: type, value, traceBack = sys.exc_info() print "ERROR updateSiteAccess : %s %s" % (type,value) return EC_Failed,None # site access map SiteAcessMapForWG = None # add allowed sites def addAllowedSites(verbose=False): # get logger tmpLog = PLogger.getPandaLogger() if verbose: tmpLog.debug('check site access') # get access list global SiteAcessMapForWG SiteAcessMapForWG = {} tmpStatus,tmpOut = listSiteAccess(None,verbose,True) if tmpStatus != 0: return False global PandaSites for tmpVal in tmpOut: tmpID = tmpVal['primKey'] # keep info to map SiteAcessMapForWG[tmpID] = tmpVal # set online if the site is allowed if tmpVal['status']=='approved': if PandaSites.has_key(tmpID): if PandaSites[tmpID]['status'] in ['brokeroff']: PandaSites[tmpID]['status'] = 'online' if verbose: tmpLog.debug('set %s online' % tmpID) return True # check permission def checkSiteAccessPermission(siteName,workingGroup,verbose): # get site access if needed if SiteAcessMapForWG == None: ret = addAllowedSites(verbose) if not ret: return True # don't check if site name is undefined if siteName == None: return True # get logger tmpLog = PLogger.getPandaLogger() if verbose: tmpLog.debug('checking site access permission') tmpLog.debug('site=%s workingGroup=%s map=%s' % (siteName,workingGroup,str(SiteAcessMapForWG))) # check if (not SiteAcessMapForWG.has_key(siteName)) or SiteAcessMapForWG[siteName]['status'] != 'approved': errStr = "You don't have permission to send jobs to %s with workingGroup=%s. " % (siteName,workingGroup) # allowed member only if PandaSites[siteName]['accesscontrol'] == 'grouplist': tmpLog.error(errStr) return False else: # reset workingGroup if not workingGroup in ['',None]: errStr += 'Resetting workingGroup to None' tmpLog.warning(errStr) return True elif not workingGroup in ['',None]: # check workingGroup wgList = SiteAcessMapForWG[siteName]['workingGroups'].split(',') if not workingGroup in wgList: errStr = "Invalid workingGroup=%s. Must be one of %s. " % (workingGroup,str(wgList)) errStr += 'Resetting workingGroup to None' tmpLog.warning(errStr) return True # no problems return True # get JobIDs in a time range def getJobIDsInTimeRange(timeRange,dn=None,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getJobIDsInTimeRange' data = {'timeRange':timeRange} if dn != None: data['dn'] = dn status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getJobIDsInTimeRange : %s %s" % (type,value) return EC_Failed,None # get JobIDs and jediTasks in a time range def getJobIDsJediTasksInTimeRange(timeRange, dn=None, minTaskID=None, verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getJediTasksInTimeRange' data = {'timeRange': timeRange, 'fullFlag': True} if dn != None: data['dn'] = dn if minTaskID is not None: data['minTaskID'] = minTaskID status,output = curl.post(url,data) if status!=0: print output return status, None try: jediTaskDicts = pickle.loads(output) return 0, jediTaskDicts except: type, value, traceBack = sys.exc_info() print "ERROR getJediTasksInTimeRange : %s %s" % (type,value) return EC_Failed, None # get details of jedi task def getJediTaskDetails(taskDict,fullFlag,withTaskInfo,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getJediTaskDetails' data = {'jediTaskID':taskDict['jediTaskID'], 'fullFlag':fullFlag, 'withTaskInfo':withTaskInfo} status,output = curl.post(url,data) if status != 0: print output return status,None try: tmpDict = pickle.loads(output) # server error if tmpDict == {}: print "ERROR getJediTaskDetails got empty" return EC_Failed,None # copy for tmpKey,tmpVal in tmpDict.iteritems(): taskDict[tmpKey] = tmpVal return 0,taskDict except: errType,errValue = sys.exc_info()[:2] print "ERROR getJediTaskDetails : %s %s" % (errType,errValue) return EC_Failed,None # get PandaIDs for a JobID def getPandIDsWithJobID(jobID,dn=None,nJobs=0,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getPandIDsWithJobID' data = {'jobID':jobID, 'nJobs':nJobs} if dn != None: data['dn'] = dn status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getPandIDsWithJobID : %s %s" % (type,value) return EC_Failed,None # check merge job generation for a JobID def checkMergeGenerationStatus(jobID,dn=None,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/checkMergeGenerationStatus' data = {'jobID':jobID} if dn != None: data['dn'] = dn status,output = curl.post(url,data) if status!=0: print output return status,None try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR checkMergeGenerationStatus : %s %s" % (type,value) return EC_Failed,None # get full job status def getFullJobStatus(ids,verbose): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getFullJobStatus' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getFullJobStatus : %s %s" % (type,value) return EC_Failed,None # get slimmed file info def getSlimmedFileInfoPandaIDs(ids,verbose): # serialize strIDs = pickle.dumps(ids) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getSlimmedFileInfoPandaIDs' data = {'ids':strIDs} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getSlimmedFileInfoPandaIDs : %s %s" % (type,value) return EC_Failed,None # get input files currently in used for analysis def getFilesInUseForAnal(outDataset,verbose): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getDisInUseForAnal' data = {'outDataset':outDataset} status,output = curl.post(url,data) try: inputDisList = pickle.loads(output) # failed if inputDisList == None: print "ERROR getFilesInUseForAnal : failed to get shadow dis list from the panda server" sys.exit(EC_Failed) # split to small chunks to avoid timeout retLFNs = [] nDis = 3 iDis = 0 while iDis < len(inputDisList): # serialize strInputDisList = pickle.dumps(inputDisList[iDis:iDis+nDis]) # get LFNs url = baseURLSSL + '/getLFNsInUseForAnal' data = {'inputDisList':strInputDisList} status,output = curl.post(url,data) tmpLFNs = pickle.loads(output) if tmpLFNs == None: print "ERROR getFilesInUseForAnal : failed to get LFNs in shadow dis from the panda server" sys.exit(EC_Failed) retLFNs += tmpLFNs iDis += nDis time.sleep(1) return retLFNs except: type, value, traceBack = sys.exc_info() print "ERROR getFilesInUseForAnal : %s %s" % (type,value) sys.exit(EC_Failed) # set debug mode def setDebugMode(pandaID,modeOn,verbose): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/setDebugMode' data = {'pandaID':pandaID,'modeOn':modeOn} status,output = curl.post(url,data) try: return status,output except: type, value = sys.exc_info()[:2] errStr = "setDebugMode failed with %s %s" % (type,value) return EC_Failed,errStr # set tmp dir def setGlobalTmpDir(tmpDir): global globalTmpDir globalTmpDir = tmpDir # exclude site def excludeSite(excludedSiteList,origFullExecString='',infoList=[]): if excludedSiteList == []: return # decompose excludedSite = [] for tmpItemList in excludedSiteList: for tmpItem in tmpItemList.split(','): if tmpItem != '' and not tmpItem in excludedSite: excludedSite.append(tmpItem) # get list of original excludedSites origExcludedSite = [] if origFullExecString != '': # extract original excludedSite origFullExecString = urllib.unquote(origFullExecString) matchItr = re.finditer('--excludedSite\s*=*([^ "]+)',origFullExecString) for match in matchItr: origExcludedSite += match.group(1).split(',') else: # use excludedSite since this is the first loop origExcludedSite = excludedSite # remove empty if '' in origExcludedSite: origExcludedSite.remove('') # sites composed of long/short queues compSites = ['CERN','LYON','BNL'] # remove sites global PandaSites for tmpPatt in excludedSite: # skip empty if tmpPatt == '': continue # check if the user sepcified userSpecified = False if tmpPatt in origExcludedSite: userSpecified = True # check if it is a composite for tmpComp in compSites: if tmpComp in tmpPatt: # use generic ID to remove all queues tmpPatt = tmpComp break sites = PandaSites.keys() for site in sites: # look for pattern if tmpPatt in site: try: # add brokerage info if userSpecified and PandaSites[site]['status'] == 'online' and not isExcudedSite(site): msgBody = 'action=exclude site=%s reason=useroption - excluded by user' % site if not msgBody in infoList: infoList.append(msgBody) PandaSites[site]['status'] = 'excluded' else: # already used by previous submission cycles PandaSites[site]['status'] = 'panda_excluded' except: pass # use certain sites def useCertainSites(sitePat): if re.search(',',sitePat) == None: return sitePat,[] # remove sites global PandaSites sites = PandaSites.keys() cloudsForRandom = [] for site in sites: # look for pattern useThisSite = False for tmpPatt in sitePat.split(','): if tmpPatt in site: useThisSite = True break # delete if not useThisSite: PandaSites[site]['status'] = 'skip' else: if not PandaSites[site]['cloud'] in cloudsForRandom: cloudsForRandom.append(PandaSites[site]['cloud']) # return return 'AUTO',cloudsForRandom # get client version def getPandaClientVer(verbose): # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/getPandaClientVer' status,output = curl.get(url,{}) # failed if status != 0: return status,output # check format if re.search('^\d+\.\d+\.\d+$',output) == None: return EC_Failed,"invalid version '%s'" % output # return return status,output # get list of cache prefix def getCachePrefixes(verbose): # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/getCachePrefixes' status,output = curl.get(url,{}) # failed if status != 0: print output errStr = "cannot get the list of Athena projects" tmpLog.error(errStr) sys.exit(EC_Failed) # return try: tmpList = pickle.loads(output) tmpList.append('AthAnalysisBase') return tmpList except: print output errType,errValue = sys.exc_info()[:2] print "ERROR: getCachePrefixes : %s %s" % (errType,errValue) sys.exit(EC_Failed) # get list of cmtConfig def getCmtConfigList(athenaVer,verbose): # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/getCmtConfigList' data = {} data['relaseVer'] = athenaVer status,output = curl.get(url,data) # failed if status != 0: print output errStr = "cannot get the list of cmtconfig for %s" % athenaVer tmpLog.error(errStr) sys.exit(EC_Failed) # return try: return pickle.loads(output) except: print output errType,errValue = sys.exc_info()[:2] print "ERROR: getCmtConfigList : %s %s" % (errType,errValue) sys.exit(EC_Failed) # get files in dataset with filte def getFilesInDatasetWithFilter(inDS,filter,shadowList,inputFileListName,verbose,dsStringFlag=False,isRecursive=False, antiFilter='',notSkipLog=False): # get logger tmpLog = PLogger.getPandaLogger() # query files in dataset if not isRecursive or verbose: tmpLog.info("query files in %s" % inDS) if dsStringFlag: inputFileMap,inputDsString = queryFilesInDataset(inDS,verbose,getDsString=True) else: inputFileMap = queryFilesInDataset(inDS,verbose) # read list of files to be used filesToBeUsed = [] if inputFileListName != '': rFile = open(inputFileListName) for line in rFile: line = re.sub('\n','',line) line = line.strip() if line != '': filesToBeUsed.append(line) rFile.close() # get list of filters filters = [] if filter != '': filters = filter.split(',') antifilters = [] if antiFilter != '': antifilters = antiFilter.split(',') # remove redundant files tmpKeys = inputFileMap.keys() filesPassFilter = [] for tmpLFN in tmpKeys: # remove log if not notSkipLog: if re.search('\.log(\.tgz)*(\.\d+)*$',tmpLFN) != None or \ re.search('\.log(\.\d+)*(\.tgz)*$',tmpLFN) != None: del inputFileMap[tmpLFN] continue # filename matching if filter != '': matchFlag = False for tmpFilter in filters: if re.search(tmpFilter,tmpLFN) != None: matchFlag = True break if not matchFlag: del inputFileMap[tmpLFN] continue # anti matching if antiFilter != '': antiMatchFlag = False for tmpFilter in antifilters: if re.search(tmpFilter,tmpLFN) != None: antiMatchFlag = True break if antiMatchFlag: del inputFileMap[tmpLFN] continue # files to be used if filesToBeUsed != []: # check matching matchFlag = False for pattern in filesToBeUsed: # normal matching if pattern == tmpLFN: matchFlag =True break # doesn't match if not matchFlag: del inputFileMap[tmpLFN] continue # files which pass the matching filters filesPassFilter.append(tmpLFN) # files in shadow if tmpLFN in shadowList: if inputFileMap.has_key(tmpLFN): del inputFileMap[tmpLFN] continue # no files in filelist are available if inputFileMap == {} and (filter != '' or antiFilter != '' or inputFileListName != '') and filesPassFilter == []: if inputFileListName != '': errStr = "Files specified in %s are unavailable in %s. " % (inputFileListName,inDS) elif filter != '': errStr = "Files matching with %s are unavailable in %s. " % (filters,inDS) else: errStr = "Files unmatching with %s are unavailable in %s. " % (antifilters,inDS) errStr += "Make sure that you specify correct file names or matching patterns" tmpLog.error(errStr) sys.exit(EC_Failed) # return if dsStringFlag: return inputFileMap,inputDsString return inputFileMap # check if DQ2-free site def isDQ2free(site): if PandaSites.has_key(site) and PandaSites[site]['ddm'] == 'local': return True return False # check queued analysis jobs at a site def checkQueuedAnalJobs(site,verbose=False): # get logger tmpLog = PLogger.getPandaLogger() # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getQueuedAnalJobs' data = {'site':site} status,output = curl.post(url,data) try: # get queued analysis queuedMap = pickle.loads(output) if queuedMap.has_key('running') and queuedMap.has_key('queued'): if queuedMap['running'] > 20 and queuedMap['queued'] > 2 * queuedMap['running']: warStr = 'Your job might be delayed since %s is busy. ' % site warStr += 'There are %s jobs already queued by other users while %s jobs are running. ' \ % (queuedMap['queued'],queuedMap['running']) warStr += 'Please consider replicating the input dataset to a free site ' warStr += 'or avoiding the --site/--cloud option so that the brokerage will ' warStr += 'find a free site' tmpLog.warning(warStr) except: type, value, traceBack = sys.exc_info() tmpLog.error("checkQueuedAnalJobs %s %s" % (type,value)) # request EventPicking def requestEventPicking(eventPickEvtList,eventPickDataType,eventPickStreamName, eventPickDS,eventPickAmiTag,fileList,fileListName,outDS, lockedBy,params,eventPickNumSites,eventPickWithGUID,ei_api, verbose=False): # get logger tmpLog = PLogger.getPandaLogger() # list of input files strInput = '' for tmpInput in fileList: if tmpInput != '': strInput += '%s,' % tmpInput if fileListName != '': for tmpLine in open(fileListName): tmpInput = re.sub('\n','',tmpLine) if tmpInput != '': strInput += '%s,' % tmpInput strInput = strInput[:-1] # make dataset name userDatasetName = '%s.%s.%s/' % tuple(outDS.split('.')[:2]+[MiscUtils.wrappedUuidGen()]) # open run/event number list evpFile = open(eventPickEvtList) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/putEventPickingRequest' data = {'runEventList' : evpFile.read(), 'eventPickDataType' : eventPickDataType, 'eventPickStreamName' : eventPickStreamName, 'eventPickDS' : eventPickDS, 'eventPickAmiTag' : eventPickAmiTag, 'userDatasetName' : userDatasetName, 'lockedBy' : lockedBy, 'giveGUID' : eventPickWithGUID, 'params' : params, 'inputFileList' : strInput, } if eventPickNumSites > 1: data['eventPickNumSites'] = eventPickNumSites if ei_api: data['ei_api'] = ei_api evpFile.close() status,output = curl.post(url,data) # failed if status != 0 or output != True: print output errStr = "failed to request EventPicking" tmpLog.error(errStr) sys.exit(EC_Failed) # return user dataset name return True,userDatasetName # check if enough sites have DBR def checkEnoughSitesHaveDBR(dq2IDs): # collect sites correspond to DQ2 IDs sitesWithDBR = [] for tmpDQ2ID in dq2IDs: tmpPandaSiteList = convertDQ2toPandaIDList(tmpDQ2ID) for tmpPandaSite in tmpPandaSiteList: if PandaSites.has_key(tmpPandaSite) and PandaSites[tmpPandaSite]['status'] == 'online': if isExcudedSite(tmpPandaSite): continue sitesWithDBR.append(tmpPandaSite) # count the number of online sites with DBR nOnline = 0 nOnlineWithDBR = 0 nOnlineT1 = 0 nOnlineT1WithDBR = 0 for tmpPandaSite,tmpSiteStat in PandaSites.iteritems(): if tmpSiteStat['status'] == 'online': # exclude test,long,local if isExcudedSite(tmpPandaSite): continue # DQ2 free if tmpSiteStat['ddm'] == 'local': continue nOnline += 1 if tmpPandaSite in PandaTier1Sites: nOnlineT1 += 1 if tmpPandaSite in sitesWithDBR or tmpSiteStat['iscvmfs'] == True: nOnlineWithDBR += 1 # DBR at enough T1 DISKs is used if tmpPandaSite in PandaTier1Sites and tmpPandaSite in sitesWithDBR: nOnlineT1WithDBR += 1 # enough replicas if nOnlineWithDBR < 10: return False # threshold 90% if float(nOnlineWithDBR) < 0.9 * float(nOnline): return False # not all T1s have the DBR if nOnlineT1 != nOnlineT1WithDBR: return False # all OK return True # get latest DBRelease def getLatestDBRelease(verbose=False): # get logger tmpLog = PLogger.getPandaLogger() tmpLog.info('trying to get the latest version number for DBRelease=LATEST') # get ddo datasets ddoDatasets = getDatasets('ddo.*',verbose,True,onlyNames=True) if ddoDatasets == {}: tmpLog.error('failed to get a list of DBRelease datasets from DQ2') sys.exit(EC_Failed) # reverse sort to avoid redundant lookup ddoDatasets = ddoDatasets.keys() ddoDatasets.sort() ddoDatasets.reverse() # extract version number latestVerMajor = 0 latestVerMinor = 0 latestVerBuild = 0 latestVerRev = 0 latestDBR = '' for tmpName in ddoDatasets: # ignore CDRelease if ".CDRelease." in tmpName: continue # ignore user if tmpName.startswith('ddo.user'): continue # use Atlas.Ideal if not ".Atlas.Ideal." in tmpName: continue match = re.search('\.v(\d+)(_*[^\.]*)$',tmpName) if match == None: tmpLog.warning('cannot extract version number from %s' % tmpName) continue # ignore special DBRs if match.group(2) != '': continue # get major,minor,build,revision numbers tmpVerStr = match.group(1) tmpVerMajor = 0 tmpVerMinor = 0 tmpVerBuild = 0 tmpVerRev = 0 try: tmpVerMajor = int(tmpVerStr[0:2]) except: pass try: tmpVerMinor = int(tmpVerStr[2:4]) except: pass try: tmpVerBuild = int(tmpVerStr[4:6]) except: pass try: tmpVerRev = int(tmpVerStr[6:]) except: pass # compare if latestVerMajor > tmpVerMajor: continue elif latestVerMajor == tmpVerMajor: if latestVerMinor > tmpVerMinor: continue elif latestVerMinor == tmpVerMinor: if latestVerBuild > tmpVerBuild: continue elif latestVerBuild == tmpVerBuild: if latestVerRev > tmpVerRev: continue # check replica locations to use well distributed DBRelease. i.e. to avoid DBR just created tmpLocations = getLocations(tmpName,[],'',False,verbose,getDQ2IDs=True) if not checkEnoughSitesHaveDBR(tmpLocations): continue # check contents to exclude reprocessing DBR tmpDbrFileMap = queryFilesInDataset(tmpName,verbose) if len(tmpDbrFileMap) != 1 or not tmpDbrFileMap.keys()[0].startswith('DBRelease'): continue # higher or equal version latestVerMajor = tmpVerMajor latestVerMinor = tmpVerMinor latestVerBuild = tmpVerBuild latestVerRev = tmpVerRev latestDBR = tmpName # failed if latestDBR == '': tmpLog.error('failed to get the latest version of DBRelease dataset from DQ2') sys.exit(EC_Failed) # get DBRelease file name tmpList = queryFilesInDataset(latestDBR,verbose) if len(tmpList) == 0: tmpLog.error('DBRelease=%s is empty' % latestDBR) sys.exit(EC_Failed) # retrun dataset:file retVal = '%s:%s' % (latestDBR,tmpList.keys()[0]) tmpLog.info('use %s' % retVal) return retVal # get inconsistent datasets which are complete in DQ2 but not in LFC def getInconsistentDS(missList,newUsedDsList): if missList == [] or newUsedDsList == []: return [] inconDSs = [] # loop over all datasets for tmpDS in newUsedDsList: # escape if missList == []: break # get file list tmpList = queryFilesInDataset(tmpDS) newMissList = [] # look for missing files for tmpFile in missList: if tmpList.has_key(tmpFile): # append if not tmpDS in inconDSs: inconDSs.append(tmpDS) else: # keep as missing newMissList.append(tmpFile) # use new missing list for the next dataset missList = newMissList # return return inconDSs # submit task def insertTaskParams(taskParams,verbose,properErrorCode=False): """Insert task parameters args: taskParams: a dictionary of task parameters returns: status code 0: communication succeeded to the panda server 255: communication failure tuple of return code and message from the server 0: request is processed 1: duplication in DEFT 2: duplication in JEDI 3: accepted for incremental execution 4: server error """ # serialize taskParamsStr = json.dumps(taskParams) # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/insertTaskParams' data = {'taskParams':taskParamsStr, 'properErrorCode':properErrorCode} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: errtype,errvalue = sys.exc_info()[:2] errStr = "ERROR insertTaskParams : %s %s" % (errtype,errvalue) return EC_Failed,output+'\n'+errStr # get history of job retry def getRetryHistory(jediTaskID,verbose=False): # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/getRetryHistory' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() print "ERROR getRetryHistory : %s %s" % (type,value) return EC_Failed,None # get PanDA IDs with TaskID def getPandaIDsWithTaskID(jediTaskID,verbose=False): """Get PanDA IDs with TaskID args: jediTaskID: jediTaskID of the task to get lit of PanDA IDs returns: status code 0: communication succeeded to the panda server 255: communication failure the list of PanDA IDs """ # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/getPandaIDsWithTaskID' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() errStr = "ERROR getPandaIDsWithTaskID : %s %s" % (type,value) print errStr return EC_Failed,output+'\n'+errStr # reactivate task def reactivateTask(jediTaskID,verbose=False): """Reactivate task args: jediTaskID: jediTaskID of the task to be reactivated returns: status code 0: communication succeeded to the panda server 255: communication failure return: a tupple of return code and message 0: unknown task 1: succeeded None: database error """ # instantiate curl curl = _Curl() curl.sslCert = _x509() curl.sslKey = _x509() curl.verbose = verbose # execute url = baseURLSSL + '/reactivateTask' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: errtype,errvalue = sys.exc_info()[:2] errStr = "ERROR reactivateTask : %s %s" % (errtype,errvalue) return EC_Failed,output+'\n'+errStr # get task status TaskID def getTaskStatus(jediTaskID,verbose=False): """Get task status args: jediTaskID: jediTaskID of the task to get lit of PanDA IDs returns: status code 0: communication succeeded to the panda server 255: communication failure the status string """ # instantiate curl curl = _Curl() curl.verbose = verbose # execute url = baseURL + '/getTaskStatus' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() errStr = "ERROR getTaskStatus : %s %s" % (type,value) print errStr return EC_Failed,output+'\n'+errStr # get taskParamsMap with TaskID def getTaskParamsMap(jediTaskID): """Get task status args: jediTaskID: jediTaskID of the task to get taskParamsMap returns: status code 0: communication succeeded to the panda server 255: communication failure return: a tuple of return code and taskParamsMap 1: logical error 0: success None: database error """ # instantiate curl curl = _Curl() # execute url = baseURL + '/getTaskParamsMap' data = {'jediTaskID':jediTaskID} status,output = curl.post(url,data) try: return status,pickle.loads(output) except: type, value, traceBack = sys.exc_info() errStr = "ERROR getTaskParamsMap : %s %s" % (type,value) print errStr return EC_Failed,output+'\n'+errStr # get T1 sites def getTier1sites(): global PandaTier1Sites PandaTier1Sites = [] # FIXME : will be simplified once schedconfig has a tier field for tmpCloud,tmpCloudVal in PandaClouds.iteritems(): for tmpDQ2ID in tmpCloudVal['tier1SE']: # ignore NIKHEF if tmpDQ2ID.startswith('NIKHEF'): continue # convert DQ2 ID to Panda Sites tmpPandaSites = convertDQ2toPandaIDList(tmpDQ2ID) for tmpPandaSite in tmpPandaSites: if not tmpPandaSite in PandaTier1Sites: PandaTier1Sites.append(tmpPandaSite) # set X509_CERT_DIR if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : setting X509_CERT_DIR" if not os.environ.has_key('X509_CERT_DIR') or os.environ['X509_CERT_DIR'] == '': tmp_x509_CApath = _x509_CApath() if tmp_x509_CApath != '': os.environ['X509_CERT_DIR'] = tmp_x509_CApath else: os.environ['X509_CERT_DIR'] = '/etc/grid-security/certificates' if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : imported %s" % __name__
34.757889
149
0.555796
7,510
0.058777
0
0
0
0
0
0
31,642
0.247648
0e106a42c5cef8990bd1a339b05449023a909ba7
6,952
py
Python
pseudo_dojo/refdata/nist/atomicdata.py
fnaccarato/pseudo_dojo
5a887c13d617b533ab3aab23af2c9466728d2f75
[ "CC-BY-4.0" ]
null
null
null
pseudo_dojo/refdata/nist/atomicdata.py
fnaccarato/pseudo_dojo
5a887c13d617b533ab3aab23af2c9466728d2f75
[ "CC-BY-4.0" ]
null
null
null
pseudo_dojo/refdata/nist/atomicdata.py
fnaccarato/pseudo_dojo
5a887c13d617b533ab3aab23af2c9466728d2f75
[ "CC-BY-4.0" ]
null
null
null
#!/usr/bin/env python import os.path import sys from pprint import pprint import nist_database def sort_dict(d, key=None, reverse=False): """ Returns an OrderedDict object whose keys are ordered according to their value. Args: d: Input dictionary key: function which takes an tuple (key, object) and returns a value to compare and sort by. By default, the function compares the values of the dict i.e. key = lambda t : t[1] reverse: allows to reverse sort order. """ import collections kv_items = [kv for kv in d.items()] # Sort kv_items according to key. if key is None: kv_items.sort(key=lambda t: t[1], reverse=reverse) else: kv_items.sort(key=key, reverse=reverse) # Build ordered dict. return collections.OrderedDict(kv_items) #class AtomicData(dict): # # _mandatory_keys = [ # "Etot", # "Ekin", # "Ecoul", # "Eenuc", # "Exc", # ] # # def __init__(self, *args, **kwargs): # super(AtomicData, self).__init__(*args, **kwargs) # # for k in self._mandatory_keys: # if k not in self: # raise ValueError("mandatory key %s is missing" % k) # #self.symbol # #self.Z = Z # #self.configurations = configurations def make_nist_configurations(path): neutral, cations, symb2Z = parse_nist_configurations(path) print("# Computer generated code") print("neutral = ") pprint(neutral) print("") print("# Computer generated code") print("cations = ") pprint(cations) print("") print("# Computer generated code") print("symb2Z = ") pprint(symb2Z) print("") def parse_nist_configurations(path): """Read and parse the file with the configurations.""" # Z Symbol Neutral Positive ion # 1 H 1s^1 - # 2 He 1s^2 1s^1 neutral, cations, symb2Z = {}, {}, {} count = 1 with open(os.path.join(path, "configurations"), "r") as fh: for line in fh: if not (len(line) > 1 and line[1].isdigit()): continue head, catio = line[:44], line[44:].strip() toks = head.split() Z, symbol, neutr = int(toks[0]), toks[1], " ".join(t for t in toks[2:]) assert Z == count count += 1 neutr = neutr.replace("^", "") catio = catio.replace("^", "") neutral[symbol] = neutr cations[symbol] = catio if catio != "-" else None symb2Z[symbol] = Z return neutral, cations, symb2Z def occupations_from_symbol(symbol): Z = symb2Z[symbol] configuration = neutral[Z] if configuration[0][0] == '[': occupations = occupations_from_symbol(configuration[0][1:-1]) configuration = configuration[1:] else: occupations = [] for s in configuration: occupations.append((s[:2], int(s[3:]))) return occupations def extract_nistdata(path, nist_xctype, iontype): # http://www.physics.nist.gov/PhysRefData/DFTdata/ # Read and parse the configurations file # Z Symbol Neutral Positive ion # 1 H 1s^1 - # 2 He 1s^2 1s^1 Ztable = {} configurations = [['X', '']] Z = 1 with open(os.path.join(path, "configurations"), "r") as fh: for line in fh: if len(line) > 1 and line[1].isdigit(): line = line[:44].split() symbol = line[1] Ztable[symbol] = Z assert int(line[0]) == Z configurations.append(line[2:]) Z += 1 def occupations_from_symbol(symbol): Z = Ztable[symbol] configuration = configurations[Z] if configuration[0][0] == '[': occupations = occupations_from_symbol(configuration[0][1:-1]) configuration = configuration[1:] else: occupations = [] for s in configuration: occupations.append((s[:2], int(s[3:]))) return occupations # Ex of file with AE results: # Etot = -675.742283 # Ekin = 674.657334 # Ecoul = 285.206130 # Eenuc = -1601.463209 # Exc = -34.142538 # 1s -143.935181 # 2s -15.046905 # 2p -12.285376 # 3s -1.706331 # 3p -1.030572 # 4s -0.141411 nistdata = {} spdf = {'s': 0, 'p': 1, 'd': 2, 'f': 3} for (symbol, Z) in Ztable.items(): #print("in symbol %s" % symbol) occupations = occupations_from_symbol(symbol) fname = os.path.join(path, nist_xctype, iontype, '%02d%s' % (Z, symbol)) energies, eigens = {}, {} with open(fname, 'r') as fh: for n in range(5): ename, evalue = fh.readline().split("=") energies[ename.strip()] = float(evalue) for line in fh: state, eig = line.split() eigens[state] = float(eig) nloe = [] for (state, occ) in occupations: n = int(state[0]) l = spdf[state[1]] eig = eigens[state] nloe.append((n, l, occ, eig)) nistdata[symbol] = (Z, nloe, energies) return nistdata def make_nistmodule(path, nist_xctype): #for iontype in ["neutrals", "cations",]: for iontype in ["neutrals",]: print('# Computer generated code: nist_xctype = %s, iontype = %s' % (nist_xctype, iontype)) print("format:\n\t element: (atomic number, [(n, l, occ, energy), ...]") print('%s = ' % iontype) data = extract_nistdata(path, nist_xctype, iontype) pprint(data) #print(json.dumps(data, indent=4)) if __name__ == '__main__': import sys from qatom import states_from_string, AtomicConfiguration for symbol in nist_database.symbols: aconf = AtomicConfiguration.neutral_from_symbol(symbol) print(aconf) sys.exit(1) path = sys.argv[1] #neutral = {} #for (symbol, confstr) in nist_database.neutral.items(): # states = states_from_string(confstr) # print(confstr) # neutral[symbol] = (nist_database.symb2Z[symbol], states) #for s in states: # pprint(tuple(s)) #aconf = AtomicConfiguration.from_string(confstr, symb2Z[symbol]) #make_nist_configurations(path) #xctypes = ["LDA", "ScRLDA"] #, "LSD", "RLDA",] nist_xctypes = ["LDA",] for xctype in nist_xctypes: print("xctype: %s" % xctype) make_nistmodule(path, xctype) #iontype = "neutrals" #dft_data = extract_nistdata(sys.argv[1], nist_xctype, iontype) #make_nistmodule(sys.argv[1], "LDA")
29.087866
99
0.542434
0
0
0
0
0
0
0
0
2,692
0.387227
0e1150fe2b483ba84007e43e4d97cff782d1e09f
1,292
py
Python
collect_users/methods/papers_with_code/papers_with_code.py
UtrechtUniversity/SWORDS-UU
d9b45706566054541625ec363e41bdf97f58c6b1
[ "MIT" ]
1
2022-02-09T14:53:45.000Z
2022-02-09T14:53:45.000Z
collect_users/methods/papers_with_code/papers_with_code.py
UtrechtUniversity/SWORDS-UU
d9b45706566054541625ec363e41bdf97f58c6b1
[ "MIT" ]
28
2021-11-30T14:37:17.000Z
2022-03-22T12:46:53.000Z
collect_users/methods/papers_with_code/papers_with_code.py
UtrechtUniversity/SWORDS-UU
d9b45706566054541625ec363e41bdf97f58c6b1
[ "MIT" ]
1
2022-01-17T10:53:26.000Z
2022-01-17T10:53:26.000Z
""" This file retrieves Github usernames from PapersWithCode.com """ import argparse from pathlib import Path from datetime import datetime import pandas as pd from paperswithcode import PapersWithCodeClient if __name__ == '__main__': # Initiate the parser parser = argparse.ArgumentParser() # Add arguments to be parsed parser.add_argument("--query", "-t", help="set topic search string") SERVICE = "github.com" current_date = datetime.today().strftime('%Y-%m-%d') # Read arguments from the command line args = parser.parse_args() client = PapersWithCodeClient() query_result = client.search(q=args.query, items_per_page=100).results result = [] paper_title = [] for paper in query_result: paper_title.append(paper.paper.title) result.append([SERVICE, current_date, paper.repository.owner]) print(f"Found following papers: {paper_title}") print(f"Found following users: {[user[2] for user in result]}") pd.DataFrame(result, columns=["service", "date", "user_id"]).to_csv(Path("results", "paperswithcode.csv"), index=False) print("Successfully exported users.")
31.512195
74
0.630031
0
0
0
0
0
0
0
0
404
0.312693
0e13465d1affe7ff9fd1bfc60e3a0c993a225447
5,087
py
Python
mc.py
ABeastofPrey/AmazingGym
d92697f3aa1025550140d3318f045fa1f497a2ea
[ "MIT" ]
1
2018-05-20T02:52:51.000Z
2018-05-20T02:52:51.000Z
mc.py
ABeastofPrey/AmazingGym
d92697f3aa1025550140d3318f045fa1f497a2ea
[ "MIT" ]
null
null
null
mc.py
ABeastofPrey/AmazingGym
d92697f3aa1025550140d3318f045fa1f497a2ea
[ "MIT" ]
null
null
null
import gym import time import random import custom_envs import pprint class MCOBJ(object): def __init__(self, grid_mdp): self.env = grid_mdp # Just for pass the error. self.states = self.env.getStates() self.actions = self.env.getActions() def gen_random_pi_sample(self, num): """่’™็‰นๅก็ฝ—ๆ ทๆœฌ้‡‡้›† Arguments: num {number} -- ๆฌกๆ•ฐ Returns: array -- ็Šถๆ€้›†๏ผŒ่กŒไธบ้›†๏ผŒๅ›žๆŠฅ้›† """ state_sample = [] action_sample = [] reward_sample = [] for _ in range(num): s_tmp = [] a_tmp = [] r_tmp = [] s = self.states[int(random.random() * len(self.states))] t = False while t == False: a = self.actions[int(random.random() * len(self.actions))] t, s1, r = self.env.transform1(s, a) s_tmp.append(s) r_tmp.append(r) a_tmp.append(a) s = s1 # ๆ ทๆœฌๅŒ…ๅซๅคšไธช็Šถๆ€ๅบๅˆ—ใ€‚ state_sample.append(s_tmp) action_sample.append(a_tmp) reward_sample.append(r_tmp) return state_sample, action_sample, reward_sample def mc_evaluation(self, state_sample, action_sample, reward_sample, gamma=0.8): vfunc, nfunc = dict(), dict() for s in self.states: vfunc[s] = 0.0 nfunc[s] = 0.0 for iter1 in range(len(state_sample)): G = 0.0 # ้€†ๅ‘่ฎก็ฎ—ๅˆๅง‹็Šถๆ€็š„็ดฏ็งฏๅ›žๆŠฅ: s1 -> s2 -> s3 -> s7 for step in range(len(state_sample[iter1])-1, -1, -1): G *= gamma G += reward_sample[iter1][step] # ๆญฃๅ‘่ฎก็ฎ—ๆฏไธช็Šถๆ€ๅค„็š„็ดฏ่ฎกๅ›žๆŠฅ for step in range(len(state_sample[iter1])): s = state_sample[iter1][step] vfunc[s] += G nfunc[s] += 1.0 G -= reward_sample[iter1][step] G /= gamma # ๅœจๆฏไธช็Šถๆ€ๅค„ๆฑ‚็ป้ชŒๅนณๅ‡ for s in self.states: if nfunc[s] > 0.000001: vfunc[s] /= nfunc[s] return vfunc def mc(self, num_iter1, epsilon, gamma): # x, y = [], [] qfunc, n = dict(), dict() for s in self.states: for a in self.actions: qfunc["%d_%s"%(s, a)] = 0.0 n["%d_%s"%(s, a)] = 0.001 for _ in range(num_iter1): # x.append(iter1) # y.append(compute_error(qfunc)) s_sample, a_sample, r_sample = [], [], [] s = self.states[int(random.random() * len(self.states))] t = False count = 0 while False == t and count < 100: a = self.epsilon_greedy(qfunc, s, epsilon) t, s1, r = self.env.transform1(s, a) s_sample.append(s) a_sample.append(a) r_sample.append(r) s = s1 count += 1 g = 0.0 for i in range(len(s_sample)-1, -1, -1): g *= gamma g += r_sample[i] for i in range(len(s_sample)): key = "%d_%s"%(s_sample[i], a_sample[i]) n[key] += 1.0 qfunc[key] = (qfunc[key] * (n[key] - 1) + g) / n[key] g -= r_sample[i] g /= gamma return qfunc def epsilon_greedy(self, qfunc, state, epsilon): if random.random() > epsilon: return self.__max_action(qfunc, state) else: return self.actions[int(random.random() * len(self.actions))] def __max_action(self, qfunc, state): state_rewards = { key: value for key, value in qfunc.items() if int(key.split("_")[0]) == state } max_reward = max(zip(state_rewards.values(), state_rewards.keys())) return max_reward[1].split("_")[1] def main(): env = gym.make('GridEnv-v0') gamma = env.gamma mc_obj = MCOBJ(env) ### ๆŽข็ดข็ญ–็•ฅ ### method1 # state_sample, action_sample, reward_sample = mc_obj.gen_random_pi_sample(10) # print(state_sample) # print(action_sample) # print(reward_sample) # vfunc = mc_obj.mc_evaluation(state_sample, action_sample, reward_sample, gamma) # print('mc evaluation: ') # print(vfunc) ### method2 qfunc = mc_obj.mc(10, 0.5, gamma) # ๆ‰“ๅฐๆœ€็ปˆ่กŒไธบๅ€ผๅ‡ฝๆ•ฐใ€‚ pprint.pprint(qfunc) ### ไฝฟ็”จๆœ€็ปˆ่กŒไธบๅ€ผๅ‡ฝๆ•ฐ่ฎฉๆœบๅ™จไบบๆ‰พ้‡‘ๅธใ€‚ # ๅฐ่ฏ•ๆ‰พ้‡‘ๅธ10ๆฌก. for _ in range(10): env.reset() env.render() time.sleep(0.3) state = env.getState() # ๅˆคๆ–ญๆ˜ฏๅฆไธบๆœ€็ปˆ็Šถๆ€ if state in env.getTerminateStates(): time.sleep(1) continue # ๆ นๆฎๆœ€็ปˆ่กŒไธบๅ€ผๅ‡ฝๆ•ฐ้‡‡ๅ–่กŒไธบ is_not_terminal = True while is_not_terminal: action = qfunc[state] next_state, _, is_terminal, _ = env.step(action) state = next_state env.render() is_not_terminal = not is_terminal if is_not_terminal: time.sleep(0.3) else: time.sleep(1) if __name__ == "__main__": main()
31.596273
105
0.500295
3,927
0.734705
0
0
0
0
0
0
981
0.183536
0e148b2e22f2b41098a22593e27a07d48422bed6
163
py
Python
website_multi_company/__init__.py
RL-OtherApps/website-addons
b0903daefa492c298084542de2c99f1ab13cd4b4
[ "MIT" ]
1
2020-03-01T03:04:21.000Z
2020-03-01T03:04:21.000Z
website_multi_company/__init__.py
RL-OtherApps/website-addons
b0903daefa492c298084542de2c99f1ab13cd4b4
[ "MIT" ]
null
null
null
website_multi_company/__init__.py
RL-OtherApps/website-addons
b0903daefa492c298084542de2c99f1ab13cd4b4
[ "MIT" ]
null
null
null
from . import models def post_load(): # use post_load to avoid overriding _get_search_domain when this module is not installed from . import controllers
23.285714
92
0.760736
0
0
0
0
0
0
0
0
88
0.539877
0e14aa7397011fb6549ac691e2e8a76643b7af57
2,107
py
Python
src/strategy/prepare_table.py
f304646673/scheduler_frame
0a9ba45a6523cbf9bd50e9fa8e08c8bfd2a9204a
[ "Apache-2.0" ]
9
2017-05-14T05:12:32.000Z
2022-01-13T08:11:07.000Z
src/strategy/prepare_table.py
f304646673/scheduler_frame
0a9ba45a6523cbf9bd50e9fa8e08c8bfd2a9204a
[ "Apache-2.0" ]
null
null
null
src/strategy/prepare_table.py
f304646673/scheduler_frame
0a9ba45a6523cbf9bd50e9fa8e08c8bfd2a9204a
[ "Apache-2.0" ]
7
2017-08-28T08:31:43.000Z
2020-03-03T07:18:37.000Z
#coding=utf-8 #-*- coding: utf-8 -*- import os import sys sys.path.append("../frame/") from loggingex import LOG_INFO from loggingex import LOG_ERROR from loggingex import LOG_WARNING from mysql_manager import mysql_manager class prepare_table(): def __init__(self, conn_name, table_template_name): self._conn_name = conn_name self._table_template_name = table_template_name self._create_table_format = "" def prepare(self, table_name): self._create_table_if_not_exist(table_name) def _get_table_template(self): file_path = "./conf/table_template/" + self._table_template_name + ".ttpl" if False == os.path.isfile(file_path): LOG_WARNING("can't read %s" %(file_path)) return fobj = open(file_path) try: self._create_table_format = fobj.read() except: self._create_table_format = "" LOG_WARNING("get table_template file error.path: %s" % (file_path)) finally: fobj.close() def _create_table_if_not_exist(self, table_name): db_manager = mysql_manager() conn = db_manager.get_mysql_conn(self._conn_name) if False == conn.has_table(table_name): if len(self._create_table_format) == 0: self._get_table_template() if len(self._create_table_format) == 0: return sql = self._create_table_format % (table_name) data = conn.execute(sql) conn.refresh_tables_info() if __name__ == "__main__": import os os.chdir("../../") sys.path.append("./src/frame/") import sys reload(sys) sys.setdefaultencoding("utf8") from j_load_mysql_conf import j_load_mysql_conf from scheduler_frame_conf_inst import scheduler_frame_conf_inst frame_conf_inst = scheduler_frame_conf_inst() frame_conf_inst.load("./conf/frame.conf") j_load_mysql_conf_obj = j_load_mysql_conf() j_load_mysql_conf_obj.run() a = prepare_table("daily_temp", "today_market_maker") a.prepare("test")
30.1
82
0.65401
1,322
0.627432
0
0
0
0
0
0
231
0.109635
0e14cf2f5e13c579c96107e8e4c16365f6b6c29e
175
py
Python
Usage.py
josephworks/PythonWS
7391580de63291018094037f87b930fe44c6eae8
[ "MIT" ]
null
null
null
Usage.py
josephworks/PythonWS
7391580de63291018094037f87b930fe44c6eae8
[ "MIT" ]
3
2019-02-23T00:30:07.000Z
2020-09-28T05:25:20.000Z
Usage.py
josephworks/PythonWS
7391580de63291018094037f87b930fe44c6eae8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
25
57
0.52
0
0
0
0
0
0
0
0
166
0.948571
0e157e46738a2ac4c1910719044fabebfba253a4
1,118
py
Python
pythran/tests/cases/diffusion_pure_python.py
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/tests/cases/diffusion_pure_python.py
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/tests/cases/diffusion_pure_python.py
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
# Reference: http://continuum.io/blog/the-python-and-the-complied-python #pythran export diffusePurePython(float [][], float [][], int) #runas import numpy as np;lx,ly=(2**7,2**7);u=np.zeros([lx,ly],dtype=np.double);u[int(lx/2),int(ly/2)]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double);diffusePurePython(u,tempU,500) #bench import numpy as np;lx,ly=(2**6,2**6);u=np.zeros([lx,ly],dtype=np.double);u[int(lx/2),int(ly/2)]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double);diffusePurePython(u,tempU,55) import numpy as np def diffusePurePython(u, tempU, iterNum): """ Apply nested iteration for the Forward-Euler Approximation """ mu = .1 row = u.shape[0] col = u.shape[1] for n in range(iterNum): for i in range(1, row - 1): for j in range(1, col - 1): tempU[i, j] = u[i, j] + mu * ( u[i + 1, j] - 2 * u[i, j] + u[i - 1, j] + u[i, j + 1] - 2 * u[i, j] + u[i, j - 1]) for i in range(1, row - 1): for j in range(1, col - 1): u[i, j] = tempU[i, j] tempU[i, j] = 0.0
41.407407
180
0.545617
0
0
0
0
0
0
0
0
567
0.507156
0e1611a439cc500182af60fc5b7313268d89e061
50
py
Python
Python/Uti1016_Distancia.py
bragabriel/Beecrowd
a71dd9926b422b5e82ae84bb5ccd76cf3ebd292b
[ "MIT" ]
null
null
null
Python/Uti1016_Distancia.py
bragabriel/Beecrowd
a71dd9926b422b5e82ae84bb5ccd76cf3ebd292b
[ "MIT" ]
null
null
null
Python/Uti1016_Distancia.py
bragabriel/Beecrowd
a71dd9926b422b5e82ae84bb5ccd76cf3ebd292b
[ "MIT" ]
null
null
null
km = int(input()) print('{} minutos'.format(km*2))
25
32
0.62
0
0
0
0
0
0
0
0
12
0.24
0e1612123e14f431ace50f65fe276956a0f82853
815
py
Python
tests/test_use_profile.py
popadi/git-profile
ca20173f63f57c21868c4c49c1e5c515d4bc87fd
[ "MIT" ]
3
2019-08-24T19:24:49.000Z
2019-08-30T09:44:46.000Z
tests/test_use_profile.py
sturmianseq/git-profiles
ca20173f63f57c21868c4c49c1e5c515d4bc87fd
[ "MIT" ]
9
2019-09-01T13:25:25.000Z
2019-09-05T19:52:25.000Z
tests/test_use_profile.py
popadi/git-profile
ca20173f63f57c21868c4c49c1e5c515d4bc87fd
[ "MIT" ]
2
2020-09-14T16:22:26.000Z
2021-08-15T08:24:09.000Z
import os import sys import pytest from random import randrange myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + "/../") import src.utils.messages as msg from src.executor import executor, parser from src.git_manager.git_manager import GitManager @pytest.fixture(autouse=True) def prepare(): git = GitManager({}) yield git class TestUseProfiles: def test_use_not_exist(self, capsys): arg_parser = parser.get_arguments_parser() # Set an account locally fake_profile = "profile-{0}".format(randrange(100000)) arguments = arg_parser.parse_args(["use", fake_profile]) executor.execute_command(arguments) out, err = capsys.readouterr() assert not err assert msg.ERR_NO_PROFILE.format(fake_profile) in out
25.46875
64
0.710429
446
0.547239
53
0.065031
83
0.10184
0
0
48
0.058896
3850ec7be1a92046c96a2377fc82bb0172a1239a
1,150
py
Python
src/old_code_feb_12/supervised/supervised_learning.py
suresh-guttikonda/sim-environment
cc8faec17714d58c0e1f0227c8b7d4cf8817a136
[ "Apache-2.0" ]
null
null
null
src/old_code_feb_12/supervised/supervised_learning.py
suresh-guttikonda/sim-environment
cc8faec17714d58c0e1f0227c8b7d4cf8817a136
[ "Apache-2.0" ]
null
null
null
src/old_code_feb_12/supervised/supervised_learning.py
suresh-guttikonda/sim-environment
cc8faec17714d58c0e1f0227c8b7d4cf8817a136
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import sys def set_path(path: str): try: sys.path.index(path) except ValueError: sys.path.insert(0, path) # set programatically the path to 'sim-environment' directory (alternately can also set PYTHONPATH) set_path('/media/suresh/research/awesome-robotics/active-slam/catkin_ws/src/sim-environment/src') import measurement as m import utils.constants as constants import numpy as np import torch import random from pathlib import Path np.random.seed(constants.RANDOM_SEED) random.seed(constants.RANDOM_SEED) torch.cuda.manual_seed(constants.RANDOM_SEED) torch.manual_seed(constants.RANDOM_SEED) np.set_printoptions(precision=3) Path("saved_models").mkdir(parents=True, exist_ok=True) Path("best_models").mkdir(parents=True, exist_ok=True) if __name__ == '__main__': print('running measurement model training') measurement = m.Measurement(render=False, pretrained=False) train_epochs = 500 eval_epochs = 5 measurement.train(train_epochs, eval_epochs) # file_name = '../bckp/dec_13/best_models/likelihood_mse_best.pth' # measurement.test(file_name) del measurement
28.75
99
0.765217
0
0
0
0
0
0
0
0
376
0.326957
3851d980a5efbf62939503a79d5a3c1ef1ba74bc
2,413
py
Python
nio/crypto/key_request.py
BURG3R5/matrix-nio
8b3d7fc0dde6f5f03124a39299f9d7c735731861
[ "Apache-2.0" ]
null
null
null
nio/crypto/key_request.py
BURG3R5/matrix-nio
8b3d7fc0dde6f5f03124a39299f9d7c735731861
[ "Apache-2.0" ]
null
null
null
nio/crypto/key_request.py
BURG3R5/matrix-nio
8b3d7fc0dde6f5f03124a39299f9d7c735731861
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright ยฉ 2020 Damir Jeliฤ‡ <poljar@termina.org.uk> # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from dataclasses import dataclass, field from typing import Dict from ..event_builders import RoomKeyRequestMessage, ToDeviceMessage from ..responses import RoomKeyRequestResponse @dataclass class OutgoingKeyRequest: """Key request that we sent out.""" request_id: str = field() session_id: str = field() room_id: str = field() algorithm: str = field() @classmethod def from_response(cls, response): # type: (RoomKeyRequestResponse) -> OutgoingKeyRequest """Create a key request object from a RoomKeyRequestResponse.""" return cls( response.request_id, response.session_id, response.room_id, response.algorithm, ) @classmethod def from_message(cls, message): # type: (RoomKeyRequestMessage) -> OutgoingKeyRequest """Create a key request object from a RoomKeyRequestMessage.""" return cls( message.request_id, message.session_id, message.room_id, message.algorithm, ) @classmethod def from_database(cls, row): """Create a key request object from a database row.""" return cls.from_response(row) def as_cancellation(self, user_id, requesting_device_id): """Turn the key request into a cancellation to-device message.""" content = { "action": "request_cancellation", "request_id": self.request_id, "requesting_device_id": requesting_device_id, } return ToDeviceMessage("m.room_key_request", user_id, "*", content)
34.971014
79
0.684625
1,417
0.586749
0
0
1,428
0.591304
0
0
1,262
0.522567
385257dce453f9dc6b74ab4ff222f4ac8563e40e
1,997
py
Python
server/editors/views.py
nickdotreid/opioid-mat-decision-aid
bbc2a0d8931d59cd6ab64b0b845e88c8dc1af5d1
[ "MIT" ]
null
null
null
server/editors/views.py
nickdotreid/opioid-mat-decision-aid
bbc2a0d8931d59cd6ab64b0b845e88c8dc1af5d1
[ "MIT" ]
27
2018-09-30T07:59:21.000Z
2020-11-05T19:25:41.000Z
server/editors/views.py
nickdotreid/opioid-mat-decision-aid
bbc2a0d8931d59cd6ab64b0b845e88c8dc1af5d1
[ "MIT" ]
null
null
null
from django.contrib.auth import authenticate from django.shortcuts import render from rest_framework import serializers from rest_framework import status from rest_framework.views import APIView from rest_framework.authtoken.models import Token from rest_framework.response import Response from .models import Editor from .models import User class EditorAuthTokenSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField( trim_whitespace = False ) class EditorLogin(APIView): def post(self, request, *args, **kwargs): serializer = EditorAuthTokenSerializer( data=request.data ) if not serializer.is_valid(): return Response( data = serializer.errors, status = status.HTTP_400_BAD_REQUEST ) email = serializer.validated_data['email'] password = serializer.validated_data['password'] try: user = User.objects.get(email = email) except User.DoesNotExist: return Response( 'User does not exist', status = status.HTTP_401_UNAUTHORIZED ) if not user.is_staff: try: editor = Editor.objects.get(user__email=email) except Editor.DoesNotExist: return Response( 'Editor does not exist', status = status.HTTP_401_UNAUTHORIZED ) user = authenticate( request=request, username=user.username, password=password ) if not user: return Response( 'Incorrect password', status = status.HTTP_401_UNAUTHORIZED ) token, created = Token.objects.get_or_create(user=user) return Response( data = { 'email': user.email, 'token': token.key } )
31.203125
63
0.589885
1,649
0.825739
0
0
0
0
0
0
95
0.047571
38550991c5a6866344d99b7c34b1049931dfba9f
12,440
py
Python
LAUG/nlu/jointBERT_new/train.py
wise-east/LAUG
c5fc674e76a0a20622a77301f9986ad58713d58d
[ "Apache-2.0" ]
10
2021-07-10T12:40:42.000Z
2022-03-14T07:51:06.000Z
LAUG/nlu/jointBERT_new/train.py
wise-east/LAUG
c5fc674e76a0a20622a77301f9986ad58713d58d
[ "Apache-2.0" ]
5
2021-07-01T11:23:58.000Z
2021-09-09T05:51:02.000Z
LAUG/nlu/jointBERT_new/train.py
wise-east/LAUG
c5fc674e76a0a20622a77301f9986ad58713d58d
[ "Apache-2.0" ]
2
2021-09-13T16:26:42.000Z
2021-11-16T09:26:54.000Z
import argparse import os import json from torch.utils.tensorboard import SummaryWriter import random import numpy as np import zipfile import torch from transformers import AdamW, get_linear_schedule_with_warmup from LAUG.nlu.jointBERT_new.dataloader import Dataloader from LAUG.nlu.jointBERT_new.jointBERT import JointBERT def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) parser = argparse.ArgumentParser(description="Train a model.") parser.add_argument('--config_path', help='path to config file') if __name__ == '__main__': args = parser.parse_args() config = json.load(open(args.config_path)) data_dir = config['data_dir'] output_dir = config['output_dir'] log_dir = config['log_dir'] DEVICE = config['DEVICE'] set_seed(config['seed']) if 'multiwoz' in data_dir: print('-'*20 + 'dataset:multiwoz' + '-'*20) from LAUG.nlu.jointBERT_new.multiwoz.postprocess import is_slot_da, calculateF1, recover_intent elif 'camrest' in data_dir: print('-' * 20 + 'dataset:camrest' + '-' * 20) from LAUG.nlu.jointBERT_new.camrest.postprocess import is_slot_da, calculateF1, recover_intent elif 'crosswoz' in data_dir: print('-' * 20 + 'dataset:crosswoz' + '-' * 20) from LAUG.nlu.jointBERT_new.crosswoz.postprocess import is_slot_da, calculateF1, recover_intent elif 'frames' in data_dir: print('-' * 20 + 'dataset:frames' + '-' * 20) from LAUG.nlu.jointBERT_new.frames.postprocess import is_slot_da, calculateF1, recover_intent intent_vocab = json.load(open(os.path.join(data_dir, 'intent_vocab.json'))) tag_vocab = json.load(open(os.path.join(data_dir, 'tag_vocab.json'))) req_vocab = json.load(open(os.path.join(data_dir, 'req_vocab.json'))) req_slot_vocab = json.load(open(os.path.join(data_dir, 'req_slot_vocab.json'))) slot_intent_vocab = json.load(open(os.path.join(data_dir,'slot_intent_vocab.json'))) print('intent_vocab = ',intent_vocab) print('tag_vocab = ', tag_vocab) print('req_vocab = ', req_vocab) print('req_slot_vocab = ', req_slot_vocab) print('='*100) dataloader = Dataloader(intent_vocab=intent_vocab, tag_vocab=tag_vocab, req_vocab=req_vocab, req_slot_vocab=req_slot_vocab, slot_intent_vocab=slot_intent_vocab, pretrained_weights=config['model']['pretrained_weights']) print('intent num:', len(intent_vocab)) print('tag num:', len(tag_vocab)) print('req num:', len(req_vocab)) for data_key in ['train', 'val', 'test']: dataloader.load_data(json.load(open(os.path.join(data_dir, '{}_data.json'.format(data_key)))), data_key, cut_sen_len=config['cut_sen_len'], use_bert_tokenizer=config['use_bert_tokenizer']) print('{} set size: {}'.format(data_key, len(dataloader.data[data_key]))) if not os.path.exists(output_dir): os.makedirs(output_dir) if not os.path.exists(log_dir): os.makedirs(log_dir) writer = SummaryWriter(log_dir) model = JointBERT(config['model'], DEVICE, dataloader.tag_dim, dataloader.intent_dim, dataloader.req_dim, dataloader, dataloader.intent_weight, dataloader.req_weight) model.to(DEVICE) if config['model']['finetune']: no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and p.requires_grad], 'weight_decay': config['model']['weight_decay']}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and p.requires_grad], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=config['model']['learning_rate'], eps=config['model']['adam_epsilon']) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=config['model']['warmup_steps'], num_training_steps=config['model']['max_step']) else: for n, p in model.named_parameters(): if 'bert' in n: p.requires_grad = False optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=config['model']['learning_rate']) for name, param in model.named_parameters(): print(name, param.shape, param.device, param.requires_grad) max_step = config['model']['max_step'] check_step = config['model']['check_step'] batch_size = config['model']['batch_size'] print('check_step = {}, batch_size = {}'.format(check_step, batch_size)) model.zero_grad() train_slot_loss, train_intent_loss, train_req_loss = 0, 0, 0 best_val_f1 = 0. writer.add_text('config', json.dumps(config)) for step in range(1, max_step + 1): model.train() batched_data = dataloader.get_train_batch(batch_size) batched_data = tuple(t.to(DEVICE) for t in batched_data) word_seq_tensor, tag_seq_tensor, intent_tensor, req_tensor, req_mask_tensor, word_mask_tensor, tag_mask_tensor,base_tag_mask_tensor, context_seq_tensor, context_mask_tensor = batched_data if not config['model']['context']: context_seq_tensor, context_mask_tensor = None, None _, _, _, slot_loss, intent_loss, req_loss = model.forward(word_seq_tensor, word_mask_tensor, tag_seq_tensor, tag_mask_tensor, intent_tensor, req_tensor, req_mask_tensor, context_seq_tensor, context_mask_tensor) train_slot_loss += slot_loss.item() train_intent_loss += intent_loss.item() train_req_loss += req_loss.item() loss = slot_loss + intent_loss + req_loss loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() if config['model']['finetune']: scheduler.step() # Update learning rate schedule model.zero_grad() if step % check_step == 0: train_slot_loss = train_slot_loss / check_step train_intent_loss = train_intent_loss / check_step train_req_loss = train_req_loss / check_step print('[%d|%d] step' % (step, max_step)) print('\t slot loss:', train_slot_loss) print('\t intent loss:', train_intent_loss) print('\t request loss:', train_req_loss) predict_golden = {'intent': [], 'slot': [], 'req':[],'overall': []} val_slot_loss, val_intent_loss,val_req_loss = 0, 0,0 model.eval() for pad_batch, ori_batch, real_batch_size in dataloader.yield_batches(batch_size, data_key='val'): pad_batch = tuple(t.to(DEVICE) for t in pad_batch) word_seq_tensor, tag_seq_tensor, intent_tensor, req_tensor, req_mask_tensor, word_mask_tensor, tag_mask_tensor, base_tag_mask_tensor, context_seq_tensor, context_mask_tensor = pad_batch if not config['model']['context']: context_seq_tensor, context_mask_tensor = None, None with torch.no_grad(): slot_logits, intent_logits, req_logits,slot_loss, intent_loss,req_loss = model.forward(word_seq_tensor, word_mask_tensor, tag_seq_tensor, tag_mask_tensor, intent_tensor, req_tensor, req_mask_tensor, context_seq_tensor, context_mask_tensor) val_slot_loss += slot_loss.item() * real_batch_size val_intent_loss += intent_loss.item() * real_batch_size val_req_loss += req_loss.item() * real_batch_size for j in range(real_batch_size): predict_intent, predict_req, predict_slot, predict_overall = recover_intent(dataloader, intent_logits[j], req_logits[j*dataloader.req_dim: (j+1)*dataloader.req_dim], slot_logits[j*dataloader.slot_intent_dim:(j+1)*dataloader.slot_intent_dim], base_tag_mask_tensor[j*dataloader.slot_intent_dim:(j+1)*dataloader.slot_intent_dim], ori_batch[j][0], ori_batch[j][-4]) #assert(ori_batch[j][3] != []) predict_golden['overall'].append({ 'predict': predict_overall, 'golden': ori_batch[j][3] }) predict_golden['req'].append({ 'predict':predict_req, 'golden':ori_batch[j][5] #req }) ''' predict_golden['slot'].append({ 'predict': predict_slot,#[x for x in predicts if is_slot_da(x)], 'golden': ori_batch[j][1]#tag }) ''' predict_golden['intent'].append({ 'predict': predict_intent, 'golden': ori_batch[j][2]#intent }) for j in range(10): writer.add_text('val_sample_{}'.format(j), json.dumps(predict_golden['overall'][j], indent=2, ensure_ascii=False), global_step=step) total = len(dataloader.data['val']) val_slot_loss /= total val_intent_loss /= total val_req_loss /= total print('%d samples val' % total) print('\t slot loss:', val_slot_loss) print('\t intent loss:', val_intent_loss) print('\t req loss:', val_req_loss) writer.add_scalar('intent_loss/train', train_intent_loss, global_step=step) writer.add_scalar('intent_loss/val', val_intent_loss, global_step=step) writer.add_scalar('req_loss/train', train_req_loss, global_step=step) writer.add_scalar('req_loss/val', val_req_loss, global_step=step) writer.add_scalar('slot_loss/train', train_slot_loss, global_step=step) writer.add_scalar('slot_loss/val', val_slot_loss, global_step=step) for x in ['intent','req','overall']: #for x in ['intent', 'slot', 'req','overall']:# pass slot precision, recall, F1 = calculateF1(predict_golden[x], x=='overall') print('-' * 20 + x + '-' * 20) print('\t Precision: %.2f' % (100 * precision)) print('\t Recall: %.2f' % (100 * recall)) print('\t F1: %.2f' % (100 * F1)) writer.add_scalar('val_{}/precision'.format(x), precision, global_step=step) writer.add_scalar('val_{}/recall'.format(x), recall, global_step=step) writer.add_scalar('val_{}/F1'.format(x), F1, global_step=step) if F1 > best_val_f1: best_val_f1 = F1 torch.save(model.state_dict(), os.path.join(output_dir, 'pytorch_model.bin')) print('best val F1 %.4f' % best_val_f1) print('save on', output_dir) train_slot_loss, train_intent_loss = 0, 0 writer.add_text('val overall F1', '%.2f' % (100 * best_val_f1)) writer.close() model_path = os.path.join(output_dir, 'pytorch_model.bin') zip_path = config['zipped_model_path'] print('zip model to', zip_path) with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: zf.write(model_path)
52.268908
347
0.573392
0
0
0
0
0
0
0
0
1,909
0.153457
3855ed738db4b64cfe3b9d2b137100a80877de8c
19,361
py
Python
app.py
Baiyuetribe/2019nCovGlobalDashboard
129a1be9b1c5e50a6891ee3d1b1f81a4b95dc888
[ "MIT" ]
8
2020-02-18T08:21:00.000Z
2020-05-11T15:37:24.000Z
app.py
Baiyuetribe/2019nCovGlobalDashboard
129a1be9b1c5e50a6891ee3d1b1f81a4b95dc888
[ "MIT" ]
1
2020-03-26T07:31:54.000Z
2020-03-26T07:31:54.000Z
app.py
Baiyuetribe/2019nCovGlobalDashboard
129a1be9b1c5e50a6891ee3d1b1f81a4b95dc888
[ "MIT" ]
2
2020-03-13T04:18:06.000Z
2020-06-05T14:27:52.000Z
import json import time import requests import re from flask import Flask, render_template, jsonify from pyecharts.charts import Map, Timeline,Kline,Line,Bar,WordCloud from pyecharts import options as opts from pyecharts.globals import SymbolType app = Flask(__name__) #ๅญ—ๅ…ธ๏ผŒๅ—้™ไบŽ่ฐทๆญŒ่ฐƒ็”จ้™ๅˆถ cn_to_en = {'ๅฎ‰ๅ“ฅๆ‹‰': 'Angola', '้˜ฟๅฏŒๆฑ—': 'Afghanistan', '้˜ฟๅฐ”ๅทดๅฐผไบš': 'Albania', '้˜ฟๅฐ”ๅŠๅˆฉไบš': 'Algeria', 'ๅฎ‰้“ๅฐ”ๅ…ฑๅ’Œๅ›ฝ': 'Andorra', 'ๅฎ‰ๅœญๆ‹‰ๅฒ›': 'Anguilla', 'ๅฎ‰ๆ็“œๅ’Œๅทดๅธƒ่พพ': 'Antigua and Barbuda', '้˜ฟๆ นๅปท': 'Argentina', 'ไบš็พŽๅฐผไบš': 'Armenia', '้˜ฟๆฃฎๆพ': 'Ascension', 'ๆพณๅคงๅˆฉไบš': 'Australia', 'ๅฅฅๅœฐๅˆฉ': 'Austria', '้˜ฟๅกžๆ‹œ็–†': 'Azerbaijan', 'ๅทดๅ“ˆ้ฉฌ': 'Bahamas', 'ๅทดๆž—': 'Bahrain', 'ๅญŸๅŠ ๆ‹‰ๅ›ฝ': 'Bangladesh', 'ๅทดๅทดๅคšๆ–ฏ': 'Barbados', '็™ฝไฟ„็ฝ—ๆ–ฏ': 'Belarus', 'ๆฏ”ๅˆฉๆ—ถ': 'Belgium', 'ไผฏๅˆฉๅ…น': 'Belize', '่ดๅฎ': 'Benin', '็™พๆ…•ๅคง็พคๅฒ›': 'Bermuda Is', '็Žปๅˆฉ็ปดไบš': 'Bolivia', 'ๅš่Œจ็“ฆ็บณ': 'Botswana', 'ๅทด่ฅฟ': 'Brazil', 'ๆ–‡่Žฑ': 'Brunei', 'ไฟๅŠ ๅˆฉไบš': 'Bulgaria', 'ๅธƒๅŸบ็บณๆณ•็ดข': 'Burkina Faso', '็ผ…็”ธ': 'Burma', 'ๅธƒ้š†่ฟช': 'Burundi', 'ๅ–€้บฆ้š†': 'Cameroon', 'ๅŠ ๆ‹ฟๅคง': 'Canada', 'ๅผ€ๆ›ผ็พคๅฒ›': 'Cayman Is', 'ไธญ้žๅ…ฑๅ’Œๅ›ฝ': 'Central African Republic', 'ไนๅพ—': 'Chad', 'ๆ™บๅˆฉ': 'Chile', 'ไธญๅ›ฝ': 'China', 'ๅ“ฅไผฆๆฏ”ไบš': 'Colombia', 'ๅˆšๆžœ': 'Congo', 'ๅบ“ๅ…‹็พคๅฒ›': 'Cook Is', 'ๅ“ฅๆ–ฏ่พพ้ปŽๅŠ ': 'Costa Rica', 'ๅคๅทด': 'Cuba', 'ๅกžๆตฆ่ทฏๆ–ฏ': 'Cyprus', 'ๆทๅ…‹': 'Czech Republic', 'ไธน้บฆ': 'Denmark', 'ๅ‰ๅธƒๆ': 'Djibouti', 'ๅคš็ฑณๅฐผๅŠ ๅ…ฑๅ’Œๅ›ฝ': 'Dominica Rep', 'ๅŽ„็“œๅคšๅฐ”': 'Ecuador', 'ๅŸƒๅŠ': 'Egypt', '่จๅฐ”็“ฆๅคš': 'EI Salvador', '็ˆฑๆฒ™ๅฐผไบš': 'Estonia', 'ๅŸƒๅกžไฟ„ๆฏ”ไบš': 'Ethiopia', 'ๆ–ๆตŽ': 'Fiji', '่Šฌๅ…ฐ': 'Finland', 'ๆณ•ๅ›ฝ': 'France', 'ๆณ•ๅฑžๅœญไบš้‚ฃ': 'French Guiana', 'ๆณ•ๅฑž็Žปๅˆฉๅฐผ่ฅฟไบš': 'French Polynesia', 'ๅŠ ่“ฌ': 'Gabon', 'ๅ†ˆๆฏ”ไบš': 'Gambia', 'ๆ ผ้ฒๅ‰ไบš': 'Georgia', 'ๅพทๅ›ฝ': 'Germany', 'ๅŠ ็บณ': 'Ghana', '็›ดๅธƒ็ฝ—้™€': 'Gibraltar', 'ๅธŒ่…Š': 'Greece', 'ๆ ผๆž—็บณ่พพ': 'Grenada', 'ๅ…ณๅฒ›': 'Guam', 'ๅฑๅœฐ้ฉฌๆ‹‰': 'Guatemala', 'ๅ‡ ๅ†…ไบš': 'Guinea', 'ๅœญไบš้‚ฃ': 'Guyana', 'ๆตทๅœฐ': 'Haiti', 'ๆดช้ƒฝๆ‹‰ๆ–ฏ': 'Honduras', '้ฆ™ๆธฏ': 'Hongkong', 'ๅŒˆ็‰™ๅˆฉ': 'Hungary', 'ๅ†ฐๅฒ›': 'Iceland', 'ๅฐๅบฆ': 'India', 'ๅฐๅบฆๅฐผ่ฅฟไบš': 'Indonesia', 'ไผŠๆœ—': 'Iran', 'ไผŠๆ‹‰ๅ…‹': 'Iraq', '็ˆฑๅฐ”ๅ…ฐ':'Ireland', 'ไปฅ่‰ฒๅˆ—': 'Israel', 'ๆ„ๅคงๅˆฉ': 'Italy', '็ง‘็‰น่ฟช็“ฆ': 'Ivory Coast', '็‰™ไนฐๅŠ ': 'Jamaica', 'ๆ—ฅๆœฌ': 'Japan', '็บฆๆ—ฆ': 'Jordan', 'ๆŸฌๅŸ”ๅฏจ': 'Kampuchea (Cambodia )', 'ๅ“ˆ่จๅ…‹ๆ–ฏๅฆ': 'Kazakstan', '่‚ฏๅฐผไบš': 'Kenya', '้Ÿฉๅ›ฝ': 'Korea', '็ง‘ๅจ็‰น': 'Kuwait', 'ๅ‰ๅฐ”ๅ‰ๆ–ฏๅฆ': 'Kyrgyzstan', '่€ๆŒ': 'Laos', 'ๆ‹‰่„ฑ็ปดไบš': 'Latvia', '้ปŽๅทดๅซฉ': 'Lebanon', '่Žฑ็ดขๆ‰˜': 'Lesotho', 'ๅˆฉๆฏ”้‡Œไบš': 'Liberia', 'ๅˆฉๆฏ”ไบš': 'Libya', 'ๅˆ—ๆ”ฏๆ•ฆๅฃซ็™ป': 'Liechtenstein', '็ซ‹้™ถๅฎ›': 'Lithuania', 'ๅขๆฃฎๅ ก': 'Luxembourg', 'ๆพณ้—จ': 'Macao', '้ฉฌ่พพๅŠ ๆ–ฏๅŠ ': 'Madagascar', '้ฉฌๆ‹‰็ปด': 'Malawi', '้ฉฌๆฅ่ฅฟไบš': 'Malaysia', '้ฉฌๅฐ”ไปฃๅคซ': 'Maldives', '้ฉฌ้‡Œ': 'Mali', '้ฉฌ่€ณไป–': 'Malta', '้ฉฌ้‡Œไบš้‚ฃ็พคๅฒ›': 'Mariana Is', '้ฉฌๆๅฐผๅ…‹': 'Martinique', 'ๆฏ›้‡Œๆฑ‚ๆ–ฏ': 'Mauritius', 'ๅขจ่ฅฟๅ“ฅ': 'Mexico', 'ๆ‘ฉๅฐ”ๅคš็“ฆ': 'Moldova', 'ๆ‘ฉ็บณๅ“ฅ': 'Monaco', '่’™ๅค': 'Mongolia', '่’™็‰นๅกžๆ‹‰็‰นๅฒ›': 'Montserrat Is', 'ๆ‘ฉๆด›ๅ“ฅ': 'Morocco', '่Žซๆก‘ๆฏ”ๅ…‹': 'Mozambique', '็บณ็ฑณๆฏ”ไบš': 'Namibia', '็‘™้ฒ': 'Nauru', 'ๅฐผๆณŠๅฐ”': 'Nepal', '่ทๅฑžๅฎ‰็š„ๅˆ—ๆ–ฏ': 'Netheriands Antilles', '่ทๅ…ฐ': 'Netherlands', 'ๆ–ฐ่ฅฟๅ…ฐ': 'New Zealand', 'ๅฐผๅŠ ๆ‹‰็“œ': 'Nicaragua', 'ๅฐผๆ—ฅๅฐ”': 'Niger', 'ๅฐผๆ—ฅๅˆฉไบš': 'Nigeria', 'ๆœ้ฒœ': 'North Korea', 'ๆŒชๅจ': 'Norway', '้˜ฟๆ›ผ': 'Oman', 'ๅทดๅŸบๆ–ฏๅฆ': 'Pakistan', 'ๅทดๆ‹ฟ้ฉฌ':'Panama', 'ๅทดๅธƒไบšๆ–ฐๅ‡ ๅ†…ไบš': 'Papua New Cuinea', 'ๅทดๆ‹‰ๅœญ': 'Paraguay', '็ง˜้ฒ': 'Peru', '่ฒๅพ‹ๅฎพ': 'Philippines', 'ๆณขๅ…ฐ': 'Poland', '่‘ก่„็‰™': 'Portugal', 'ๆณขๅคš้ปŽๅ„': 'Puerto Rico', 'ๅกๅก”ๅฐ”': 'Qatar', '็•™ๅฐผๆ—บ': 'Reunion', '็ฝ—้ฉฌๅฐผไบš': 'Romania', 'ไฟ„็ฝ—ๆ–ฏ': 'Russia', 'ๅœฃๅข่ฅฟไบš': 'St.Lucia', 'ๅœฃๆ–‡ๆฃฎ็‰นๅฒ›': 'Saint Vincent', 'ไธœ่จๆ‘ฉไบš(็พŽ)': 'Samoa Eastern', '่ฅฟ่จๆ‘ฉไบš': 'Samoa Western', 'ๅœฃ้ฉฌๅŠ›่ฏบ': 'San Marino', 'ๅœฃๅคš็พŽๅ’Œๆ™ฎๆž—่ฅฟๆฏ”': 'Sao Tome and Principe', 'ๆฒ™็‰น้˜ฟๆ‹‰ไผฏ': 'Saudi Arabia', 'ๅกžๅ†…ๅŠ ๅฐ”': 'Senegal', 'ๅกž่ˆŒๅฐ”': 'Seychelles', 'ๅกžๆ‹‰ๅˆฉๆ˜‚': 'Sierra Leone', 'ๆ–ฐๅŠ ๅก': 'Singapore', 'ๆ–ฏๆด›ไผๅ…‹': 'Slovakia', 'ๆ–ฏๆด›ๆ–‡ๅฐผไบš': 'Slovenia', 'ๆ‰€็ฝ—้—จ็พคๅฒ›': 'Solomon Is', '็ดข้ฉฌ้‡Œ': 'Somali', 'ๅ—้ž': 'South Africa', '่ฅฟ็ญ็‰™': 'Spain', 'ๆ–ฏ้‡Œๅ…ฐๅก': 'SriLanka', 'ๅœฃๆ–‡ๆฃฎ็‰น': 'St.Vincent', '่‹ไธน': 'Sudan', '่‹้‡Œๅ—': 'Suriname', 'ๆ–ฏๅจๅฃซๅ…ฐ': 'Swaziland', '็‘žๅ…ธ': 'Sweden', '็‘žๅฃซ': 'Switzerland', 'ๅ™ๅˆฉไบš': 'Syria', 'ๅฐๆนพ็œ': 'Taiwan', 'ๅก”ๅ‰ๅ…‹ๆ–ฏๅฆ': 'Tajikstan', 'ๅฆๆก‘ๅฐผไบš': 'Tanzania', 'ๆณฐๅ›ฝ': 'Thailand', 'ๅคšๅ“ฅ': 'Togo', 'ๆฑคๅŠ ': 'Tonga', '็‰น็ซ‹ๅฐผ่พพๅ’Œๅคšๅทดๅ“ฅ': 'Trinidad and Tobago', '็ชๅฐผๆ–ฏ': 'Tunisia', 'ๅœŸ่€ณๅ…ถ': 'Turkey', 'ๅœŸๅบ“ๆ›ผๆ–ฏๅฆ': 'Turkmenistan', 'ไนŒๅนฒ่พพ': 'Uganda', 'ไนŒๅ…‹ๅ…ฐ': 'Ukraine', '้˜ฟ่”้…‹': 'United Arab Emirates', '่‹ฑๅ›ฝ': 'United Kiongdom', '็พŽๅ›ฝ': 'United States', 'ไนŒๆ‹‰ๅœญ': 'Uruguay', 'ไนŒๅ…นๅˆซๅ…‹ๆ–ฏๅฆ': 'Uzbekistan', 'ๅง”ๅ†…็‘žๆ‹‰': 'Venezuela', '่ถŠๅ—': 'Vietnam', 'ไนŸ้—จ': 'Yemen', 'ๅ—ๆ–ฏๆ‹‰ๅคซ': 'Yugoslavia', 'ๆดฅๅทดๅธƒ้Ÿฆ': 'Zimbabwe', 'ๆ‰ŽไผŠๅฐ”': 'Zaire', '่ตžๆฏ”ไบš': 'Zambia','ๅ…‹็ฝ—ๅœฐไบš':'Croatia','ๅŒ—้ฉฌๅ…ถ้กฟ':'North Macedonia'} def update_news(): url = 'https://opendata.baidu.com/data/inner?tn=reserved_all_res_tn&dspName=iphone&from_sf=1&dsp=iphone&resource_id=28565&alr=1&query=%E8%82%BA%E7%82%8E' r = json.loads(requests.get(url).text) top10 = r['Result'][0]['items_v2'][0]['aladdin_res']['DisplayData']['result']['items'][:5] #list news_data = [] for r in top10: news_data.append({ 'title': r['eventDescription'], 'sourceUrl': r['eventUrl'], 'infoSource': time.strftime('%m-%d %H:%M:%S', time.localtime(int(r['eventTime']))) + ' ' + r['siteName'] #ๆ—ถ้—ดๅฑžๆ€ง + ๆถˆๆฏๆฅๆบ }) #ๆž„ๅปบๆ–ฐ็š„ๅˆ—่กจ return news_data def update_overall(): url = 'http://lab.isaaclin.cn/nCoV/api/overall' overall_data = json.loads(requests.get(url).text) #ๆ ‡ๅ‡†็š„jsonๆ•ฐๆฎๆ ผๅผๅŒ– overall_data['time'] = time.strftime("%m-%d %H:%M", time.localtime(time.time())) #ๅฝ“ๅ‰ๆ—ถ้—ด # time.time() --> '1580232854.7124019' ## time.localtime(time.time()) --> 'time.struct_time(tm_year=2020, tm_mon=1, tm_mday=29, tm_hour=1, tm_min=34, tm_sec=36, tm_wday=2, tm_yday=29, tm_isdst=0)' ### time.strftime("%m-%d %H:%M", time.localtime(time.time())) ---> '01-29 01:37' ่Žทๅพ—ๅฝ“ๅ‰ๆœˆใ€ๆ—ฅใ€ๅฐๆ—ถใ€ๅˆ†้’Ÿ return overall_data # def update_hotnews(): url = 'https://i-lq.snssdk.com/api/feed/hotboard_online/v1/?is_in_channel=1&count=5&fe_source=news_hot&tab_name=stream&is_web_refresh=1&client_extra_params={%22hot_board_source%22:%22news_hot%22,%22fe_version%22:%22v10%22}&extra={%22CardStyle%22:0,%22JumpToWebList%22:true}&category=hotboard_online&update_version_code=75717' r = requests.get(url).text #ๆ ‡ๅ‡†็š„jsonๆ•ฐๆฎๆ ผๅผๅŒ– data = re.findall(r'title\\":\\"(.*?)\\',r)[:-1] # time.time() --> '1580232854.7124019' ## time.localtime(time.time()) --> 'time.struct_time(tm_year=2020, tm_mon=1, tm_mday=29, tm_hour=1, tm_min=34, tm_sec=36, tm_wday=2, tm_yday=29, tm_isdst=0)' ### time.strftime("%m-%d %H:%M", time.localtime(time.time())) ---> '01-29 01:37' ่Žทๅพ—ๅฝ“ๅ‰ๆœˆใ€ๆ—ฅใ€ๅฐๆ—ถใ€ๅˆ†้’Ÿ return data #list def word_cloud() -> WordCloud: url = 'https://i-lq.snssdk.com/api/feed/hotboard_online/v1/?is_in_channel=1&count=10&fe_source=news_hot&tab_name=stream&is_web_refresh=1&client_extra_params={%22hot_board_source%22:%22news_hot%22,%22fe_version%22:%22v10%22}&extra={%22CardStyle%22:0,%22JumpToWebList%22:true}&category=hotboard_online&update_version_code=75717' r = requests.get(url).text #ๆ ‡ๅ‡†็š„jsonๆ•ฐๆฎๆ ผๅผๅŒ– data = re.findall(r'title\\":\\"(.*?)\\',r)[:-1] datanum = [8,7,6,5,5,4,4,2,1,1] words = [w for w in zip(data,datanum)] c = ( WordCloud() .add("", words, word_size_range=[20, 100], shape=SymbolType.DIAMOND) .set_global_opts(title_opts=opts.TitleOpts(title="WordCloud-shape-diamond")) ) return c def update_china_data(unit=3600 * 2): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] p_data = {} #print(data['areaTree'][0]['children'][0]) for i in data['areaTree'][0]['children']: #ๅ„ไธช็œไปฝ p_data[i['name']] = i['total']['confirm'] # ๅ…ˆๅฏนๅญ—ๅ…ธ่ฟ›่กŒๆŽ’ๅบ,ๆŒ‰็…งvalueไปŽๅคงๅˆฐๅฐ p_data= sorted(p_data.items(), key=lambda x: x[1], reverse=True) #print(p_data) return p_data def update_china_heal_data(unit=3600 * 2): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] p_data = {} #print(data['areaTree'][0]['children'][0]) for i in data['areaTree'][0]['children']: #ๅ„ไธช็œไปฝ p_data[i['name']] = i['total']['confirm'] - i['total']['dead'] - i['total']['heal'] # ๅ…ˆๅฏนๅญ—ๅ…ธ่ฟ›่กŒๆŽ’ๅบ,ๆŒ‰็…งvalueไปŽๅคงๅˆฐๅฐ p_data= sorted(p_data.items(), key=lambda x: x[1], reverse=True) #print(p_data) return p_data def china_map(data)-> Map: opt= [ {"min":1001,"color":'#731919'}, {"min":500,"max":1000,"color":'red'}, {"min":100,"max":499,"color":'#e26061'}, {"min":10,"max":99,"color":'#f08f7f'}, {"min":1,"max":9,"color":'#ffb86a'}, {"value":0,"color":'#ffffff'} ] c = ( Map() .add( "็กฎ่ฏŠไบบๆ•ฐ", data, "china", is_map_symbol_show=False, ) .set_series_opts(label_opts=opts.LabelOpts(is_show=False,font_size=8)) .set_global_opts( visualmap_opts=opts.VisualMapOpts(max_=1000,is_piecewise=True,pieces=opt), legend_opts=opts.LegendOpts(is_show=False), #title_opts=opts.TitleOpts(title="ๅ…จๅ›ฝ็–ซๆƒ…(2019-nCov)") ) ) return c # ่Žทๅ–ไธ–็•Œๆ•ฐๆฎ def update_world_data(unit=3600 * 2): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #print(data['areaTree'][0]['children'][0]) countryEN = [] total_confirm = [] for i in data['areaTree']: if i['name'] != '้’ป็Ÿณๅท้‚ฎ่ฝฎ': if i['name'] == 'ๆ—ฅๆœฌๆœฌๅœŸ': countryEN.append('Japan') total_confirm.append(i['total']['confirm']) else: countryEN.append(cn_to_en[i['name']]) total_confirm.append(i['total']['confirm']) data = [list(z) for z in zip(countryEN, total_confirm)] return data def update_world_data1(unit=3600 * 2): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #print(data['areaTree'][0]['children'][0]) translate = Translator() country = [] #ไธญๆ–‡ๅ›ฝๅฎถๆๅ– total_confirm = [] for i in data['areaTree']: country.append(i['name']) total_confirm.append(i['total']['confirm']) countryEN = [] #็ฟป่ฏ‘ for i in country: countryEN.append(translate.translate(i).text) #ไปŠๆ—ฅๆ•ฐๆฎ data = [list(z) for z in zip(countryEN, total_confirm)] return data def world_map(data)-> Map: opt= [ {"min":1001,"color":'#731919'}, {"min":51,"max":1000,"color":'red'}, {"min":11,"max":50,"color":'#e26061'}, {"min":6,"max":10,"color":'#f08f7f'}, {"min":1,"max":5,"color":'#ffb86a'}, {"value":0,"color":'#ffffff'} ] c = ( Map() .add("็กฎ่ฏŠไบบๆ•ฐ", data, "world",is_map_symbol_show=False) #.add("ๅ•†ๅฎถA", [list(z) for z in zip(countryEN, total_confirm)], "world") .set_series_opts(label_opts=opts.LabelOpts(is_show=False,font_size=8),) .set_global_opts( visualmap_opts=opts.VisualMapOpts(max_=1000,is_piecewise=True,pieces=opt), legend_opts=opts.LegendOpts(is_show=False), #title_opts=opts.TitleOpts(title="ๅ…จ็ƒ็–ซๆƒ…(2019-nCov)") ) ) return c def kline()-> Kline: data = get_origin_data() #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #ๆฏๆ—ฅ็กฎ่ฏŠๅขžๅŠ ๆ•ฐ a = [] c = [x['confirm'] for x in data['chinaDayList']] for i in range(len(c)): if i == 0: a.append(0) else: a.append(int(c[i]) - int(c[i-1])) b = [] for i in range(len(a)): if i == 0: b.append([0,0,0,a[i]]) elif i == 1: b.append([0,0,a[i-1],a[i]]) elif i == 2: b.append([0,a[i-2],a[i-1],a[i]]) else: b.append([a[i-3],a[i-2],a[i-1],a[i]]) c = ( Kline() .add_xaxis([x['date'] for x in data['chinaDayList']]) .add_yaxis("kline", b) .set_global_opts( yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), xaxis_opts=opts.AxisOpts(is_scale=True), #title_opts=opts.TitleOpts(title="2019-nCov K็บฟๅ›พ"), datazoom_opts=[opts.DataZoomOpts(pos_bottom="-2%",range_end=100)], ) ) return c def get_origin_data(): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other' r = requests.get(url) data = json.loads(json.loads(r.text)['data']) return data def line_connect_null() -> Line: data = get_origin_data() #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #ๆฏๆ—ฅ็กฎ่ฏŠๅขžๅŠ ๆ•ฐ Dailyincrease = [] a = [x['confirm'] for x in data['chinaDayList']] for i in range(len(a)): if i == 0: Dailyincrease.append(0) else: Dailyincrease.append(int(a[i]) - int(a[i-1])) c = ( Line() .add_xaxis([x['date'] for x in data['chinaDayList']]) #็›ดๆŽฅๅˆ—่กจ .add_yaxis('็กฎ่ฏŠ',[x['confirm'] for x in data['chinaDayList']],label_opts=opts.LabelOpts(is_show=False)) #โ€˜ๅˆ—่กจๅ๏ผŒ[]โ€™ .add_yaxis('็–‘ไผผ',[x['suspect'] for x in data['chinaDayList']],label_opts=opts.LabelOpts(is_show=False)) .add_yaxis('ๆฒปๆ„ˆ',[x['heal'] for x in data['chinaDayList']],label_opts=opts.LabelOpts(is_show=False)) .add_yaxis('ๆญปไบก',[x['dead'] for x in data['chinaDayList']],label_opts=opts.LabelOpts(is_show=False)) .add_yaxis('ๆฏๆ—ฅ็กฎ่ฏŠๅขžๅŠ ๆ•ฐ',Dailyincrease,areastyle_opts=opts.AreaStyleOpts(opacity=0.5),label_opts=opts.LabelOpts(is_show=False)) #areastyle_opts=opts.AreaStyleOpts(opacity=0.5) ๆŠ•ๅฐ„้ข็งฏ .set_global_opts( #title_opts=opts.TitleOpts(title="2019-nCov"), datazoom_opts=opts.DataZoomOpts(range_end=100), ) ) return c def line_heal() -> Line: url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #ๆฏๆ—ฅ็กฎ่ฏŠๅขžๅŠ ๆ•ฐ Dailyincrease = [] a = [x['confirm'] for x in data['chinaDayList']] for i in range(len(a)): if i == 0: Dailyincrease.append(0) else: Dailyincrease.append(int(a[i]) - int(a[i-1])) #ๆฏๆ—ฅ็–‘ไผผๅขžๅŠ ๆ•ฐ Dailysuspect = [] a = [x['suspect'] for x in data['chinaDayList']] for i in range(len(a)): if i == 0: Dailysuspect.append(0) else: Dailysuspect.append(int(a[i]) - int(a[i-1])) c = ( Line() .add_xaxis([x['date'] for x in data['chinaDayList']]) #็›ดๆŽฅๅˆ—่กจ .add_yaxis('ๆฒปๆ„ˆ',[x['heal'] for x in data['chinaDayList']]) .add_yaxis('ๆญปไบก',[x['dead'] for x in data['chinaDayList']]) .set_global_opts( #title_opts=opts.TitleOpts(title="2019-nCov"), datazoom_opts=opts.DataZoomOpts(range_end=100), ) ) return c #ๆตทๅค–ๅ›ฝๅฎถ็ปŸ่ฎก def world_bar() -> Bar: url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] country = [] numbers = [] for i in data['areaTree']: country.append(i['name']) numbers.append(i['total']['confirm']) country.reverse() numbers.reverse() c = ( Bar() .add_xaxis(country[:-1]) .add_yaxis("็กฎ่ฏŠไบบๆ•ฐ", numbers[:-1]) .reversal_axis() .set_series_opts(label_opts=opts.LabelOpts(position="right",color="black")) .set_global_opts( #title_opts=opts.TitleOpts(title="ๆตทๅค–ๅ›ฝๅฎถ็ปŸ่ฎกๆ•ฐๆฎ"), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45,font_size=11)), ) ) return c #ๆตทๅค–ๅ›ฝๅฎถ่ถ‹ๅŠฟ def other_line() -> Line: url = 'https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/cases_time_v3/FeatureServer/0/query?f=json&where=1%3D1&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=*&orderByFields=Report_Date_String%20asc&resultOffset=0&resultRecordCount=2000&cacheHint=true' r_data = json.loads(requests.get(url).text) data = r_data['features'] #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] dates = [] numbers = [] for i in data: date = time.strftime("%m.%d", time.localtime(i['attributes']['Report_Date'] / 1000)) dates.append(date) numbers.append(i['attributes']['Other_Locations']) c = ( Line() .add_xaxis(dates) #็›ดๆŽฅๅˆ—่กจ .add_yaxis('็กฎ่ฏŠ',numbers) .set_global_opts( #title_opts=opts.TitleOpts(title="ๆตทๅค–ๅ›ฝๅฎถ็–ซๆƒ…่ถ‹ๅŠฟ", subtitle=""), ) ) return c def china_online(): url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5' r_data = json.loads(requests.get(url).text) data = json.loads(r_data['data']) #ๅˆๅง‹ๅŒ–jsonๆ•ฐๆฎ๏ผŒไธบdict ['chinaTotal'] #ๆฏๆ—ฅ็กฎ่ฏŠๅขžๅŠ ๆ•ฐ # chinaTotal = data['chinaTotal'] #็ป“ๆžœไธบๅˆ—่กจ # chinaAdd = data['chinaAdd'] # lastUpdateTime = data['lastUpdateTime'] return data @app.route("/") def index(): other_data = get_origin_data() return render_template("index.html") # ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ @app.route("/map") def get_map(): data = update_china_data() return china_map(data).dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ # ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎๅพ…ๆฒปๆ„ˆ @app.route("/map2") def get_map2(): data = update_china_heal_data() return china_map(data).dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ #ไธ–็•Œๅœฐๅ›พ @app.route("/maps") def get_maps(): #countryEN,total_confirm = update_world_data() data = update_world_data() return world_map(data).dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚ #็–ซๆƒ…ๆ’ญๆŠฅ @app.route("/news") def get_news(): news = update_news() return jsonify(news) #ๅ…จๅ›ฝ็ปŸ่ฎกๆ•ฐ้‡ @app.route("/online") def get_online(): onlines = china_online() return jsonify(onlines) #ๅฎžๆ—ถ็ƒญๆฆœ @app.route("/hotnews") def get_hotnews(): hotnews = update_hotnews() return jsonify(hotnews) @app.route("/wordcloud") def get_word_cloud(): word = word_cloud() return word.dump_options_with_quotes() # K็บฟ @app.route("/kline") def get_kline(): c = kline() return c.dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ @app.route("/line") def get_line(): c = line_connect_null() return c.dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ @app.route("/worldbar") def get_worldbar(): c = world_bar() return c.dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ @app.route("/worldline") def get_worldline(): c = other_line() return c.dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ @app.route("/heal") def get_heal(): c = line_heal() return c.dump_options_with_quotes() #ๅ…ถไธญdump_options_with_quotes()ๆ˜ฏๅฟ…ๅค‡๏ผŒไปปๆ„ๅ›พๅฝขใ€‚# ๅ…จๅ›ฝๅœฐๅ›พๆ•ฐๆฎ # @app.route("/overall") # def get_overall(): # overall = update_overall() # return jsonify(overall) if __name__ == "__main__": #app.run(debug=True) app.run(host="0.0.0.0",port=5000,debug=True)
43.216518
330
0.594597
0
0
0
0
2,072
0.095453
0
0
10,893
0.50182
385a1293e848a01d5e145a500532168c2c1b01d7
752
py
Python
game/migrations/0002_table.py
koualsky/texas-holdem
b0c4f84ae5d4b679c870a9312376cfa1e208ec16
[ "MIT" ]
4
2019-09-05T21:22:46.000Z
2020-12-19T19:23:08.000Z
game/migrations/0002_table.py
koualsky/texas-holdem
b0c4f84ae5d4b679c870a9312376cfa1e208ec16
[ "MIT" ]
34
2019-08-07T11:58:07.000Z
2021-06-10T21:49:00.000Z
game/migrations/0002_table.py
koualsky/texas-holdem
b0c4f84ae5d4b679c870a9312376cfa1e208ec16
[ "MIT" ]
4
2020-04-05T03:42:10.000Z
2022-03-03T03:04:40.000Z
# Generated by Django 2.2.4 on 2019-08-03 15:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('game', '0001_initial'), ] operations = [ migrations.CreateModel( name='Table', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('players', models.CharField(max_length=500)), ('dealer', models.CharField(max_length=200)), ('pool', models.IntegerField(default=0)), ('deck', models.CharField(max_length=500)), ('cards_on_table', models.CharField(max_length=100)), ], ), ]
30.08
114
0.56383
659
0.87633
0
0
0
0
0
0
127
0.168883
385af8dbd8e654da5aeddc36ed67c47b4de8fade
10,913
py
Python
tests/activity/test_activity_post_digest_jats.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
17
2015-02-10T07:10:29.000Z
2021-05-14T22:24:45.000Z
tests/activity/test_activity_post_digest_jats.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
459
2015-03-31T18:24:23.000Z
2022-03-30T19:44:40.000Z
tests/activity/test_activity_post_digest_jats.py
elifesciences/elife-bot
d3a102c8030e4b7ec83cbd45e5f839dba4f9ffd9
[ "MIT" ]
9
2015-04-18T16:57:31.000Z
2020-10-30T11:49:13.000Z
# coding=utf-8 import unittest from mock import patch from ddt import ddt, data from digestparser.objects import Digest import activity.activity_PostDigestJATS as activity_module from activity.activity_PostDigestJATS import activity_PostDigestJATS as activity_object import tests.activity.settings_mock as settings_mock from tests.activity.classes_mock import FakeLogger, FakeResponse import tests.test_data as test_case_data from tests.activity.classes_mock import FakeStorageContext from tests.classes_mock import FakeSMTPServer import provider.digest_provider as digest_provider def input_data(file_name_to_change=""): activity_data = test_case_data.ingest_digest_data activity_data["file_name"] = file_name_to_change return activity_data @ddt class TestPostDigestJats(unittest.TestCase): def setUp(self): fake_logger = FakeLogger() self.activity = activity_object(settings_mock, fake_logger, None, None, None) def tearDown(self): # clean the temporary directory self.activity.clean_tmp_dir() @patch.object(activity_module.email_provider, "smtp_connect") @patch("requests.post") @patch.object(activity_module.download_helper, "storage_context") @patch.object(activity_module.digest_provider, "storage_context") @data( { "comment": "digest docx file example", "filename": "DIGEST+99999.docx", "post_status_code": 200, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": True, "expected_build_status": True, "expected_jats_status": True, "expected_post_status": True, "expected_email_status": True, "expected_digest_doi": u"https://doi.org/10.7554/eLife.99999", }, { "comment": "digest zip file example", "filename": "DIGEST+99999.zip", "post_status_code": 200, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": True, "expected_build_status": True, "expected_jats_status": True, "expected_post_status": True, "expected_email_status": True, "expected_digest_doi": u"https://doi.org/10.7554/eLife.99999", }, { "comment": "digest file does not exist example", "filename": "", "post_status_code": 200, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": None, "expected_build_status": False, "expected_jats_status": None, "expected_post_status": None, }, { "comment": "bad digest docx file example", "filename": "DIGEST+99998.docx", "post_status_code": 200, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": None, "expected_build_status": False, "expected_jats_status": None, "expected_post_status": None, "expected_email_status": None, }, { "comment": "digest author name encoding file example", "filename": "DIGEST+99997.zip", "post_status_code": 200, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": True, "expected_build_status": True, "expected_jats_status": True, "expected_post_status": True, "expected_email_status": True, "expected_digest_doi": u"https://doi.org/10.7554/eLife.99997", }, { "comment": "digest bad post response", "filename": "DIGEST+99999.docx", "post_status_code": 500, "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": True, "expected_build_status": True, "expected_jats_status": True, "expected_post_status": False, "expected_email_status": None, "expected_digest_doi": u"https://doi.org/10.7554/eLife.99999", }, { "comment": "digest silent deposit example", "filename": "DIGEST+99999+SILENT.zip", "expected_result": activity_object.ACTIVITY_SUCCESS, "expected_activity_status": None, "expected_build_status": None, "expected_jats_status": None, "expected_post_status": None, "expected_email_status": None, }, ) def test_do_activity( self, test_data, fake_storage_context, fake_download_storage_context, requests_method_mock, fake_email_smtp_connect, ): # copy XML files into the input directory using the storage context fake_storage_context.return_value = FakeStorageContext() fake_download_storage_context.return_value = FakeStorageContext() fake_email_smtp_connect.return_value = FakeSMTPServer( self.activity.get_tmp_dir() ) # POST response requests_method_mock.return_value = FakeResponse( test_data.get("post_status_code"), None ) # do the activity result = self.activity.do_activity(input_data(test_data.get("filename"))) filename_used = input_data(test_data.get("filename")).get("file_name") # check assertions self.assertEqual( result, test_data.get("expected_result"), ( "failed in {comment}, got {result}, filename {filename}, " + "input_file {input_file}, digest {digest}" ).format( comment=test_data.get("comment"), result=result, input_file=self.activity.input_file, filename=filename_used, digest=self.activity.digest, ), ) self.assertEqual( self.activity.statuses.get("build"), test_data.get("expected_build_status"), "failed in {comment}".format(comment=test_data.get("comment")), ) self.assertEqual( self.activity.statuses.get("jats"), test_data.get("expected_jats_status"), "failed in {comment}".format(comment=test_data.get("comment")), ) self.assertEqual( self.activity.statuses.get("post"), test_data.get("expected_post_status"), "failed in {comment}".format(comment=test_data.get("comment")), ) self.assertEqual( self.activity.statuses.get("email"), test_data.get("expected_email_status"), "failed in {comment}".format(comment=test_data.get("comment")), ) # check digest values if self.activity.digest and test_data.get("expected_digest_doi"): self.assertEqual( self.activity.digest.doi, test_data.get("expected_digest_doi"), "failed in {comment}".format(comment=test_data.get("comment")), ) @patch.object(activity_module.email_provider, "smtp_connect") @patch.object(activity_module.download_helper, "storage_context") @patch.object(activity_module.digest_provider, "storage_context") @patch.object(digest_provider, "digest_jats") def test_do_activity_jats_failure( self, fake_digest_jats, fake_storage_context, fake_download_storage_context, fake_email_smtp_connect, ): fake_storage_context.return_value = FakeStorageContext() fake_download_storage_context.return_value = FakeStorageContext() fake_email_smtp_connect.return_value = FakeSMTPServer( self.activity.get_tmp_dir() ) activity_data = input_data("DIGEST+99999.zip") fake_digest_jats.return_value = None result = self.activity.do_activity(activity_data) self.assertEqual(result, activity_object.ACTIVITY_SUCCESS) @patch.object(activity_module.email_provider, "smtp_connect") @patch.object(activity_module.download_helper, "storage_context") @patch.object(activity_module.digest_provider, "storage_context") @patch.object(activity_module.requests_provider, "jats_post_payload") def test_do_activity_post_failure( self, fake_post_jats, fake_storage_context, fake_download_storage_context, fake_email_smtp_connect, ): fake_storage_context.return_value = FakeStorageContext() fake_download_storage_context.return_value = FakeStorageContext() fake_email_smtp_connect.return_value = FakeSMTPServer( self.activity.get_tmp_dir() ) activity_data = input_data("DIGEST+99999.zip") fake_post_jats.side_effect = Exception("Something went wrong!") result = self.activity.do_activity(activity_data) self.assertEqual(result, activity_object.ACTIVITY_SUCCESS) class TestPostDigestJatsNoEndpoint(unittest.TestCase): def test_do_activity_no_endpoint(self): """test returning True if the endpoint is not specified in the settings""" activity = activity_object(settings_mock, FakeLogger(), None, None, None) # now can safely alter the settings del activity.settings.typesetter_digest_endpoint result = activity.do_activity() self.assertEqual(result, activity_object.ACTIVITY_SUCCESS) def test_do_activity_blank_endpoint(self): """test returning True if the endpoint is blank""" activity = activity_object(settings_mock, FakeLogger(), None, None, None) # now can safely alter the settings activity.settings.typesetter_digest_endpoint = "" result = activity.do_activity() self.assertEqual(result, activity_object.ACTIVITY_SUCCESS) class TestEmailErrorReport(unittest.TestCase): def setUp(self): fake_logger = FakeLogger() self.activity = activity_object(settings_mock, fake_logger, None, None, None) def tearDown(self): # clean the temporary directory self.activity.clean_tmp_dir() @patch.object(activity_module.email_provider, "smtp_connect") def test_email_error_report(self, fake_email_smtp_connect): """test sending an email error""" fake_email_smtp_connect.return_value = FakeSMTPServer( self.activity.get_tmp_dir() ) digest_content = Digest() digest_content.doi = "10.7554/eLife.99999" jats_content = {} error_messages = ["An error"] settings_mock.typesetter_digest_endpoint = "" result = self.activity.email_error_report( digest_content, jats_content, error_messages ) self.assertEqual(result, True) if __name__ == "__main__": unittest.main()
40.269373
87
0.647668
10,093
0.92486
0
0
8,932
0.818473
0
0
2,967
0.271878
385c79e6128ba15d725a285dc68b5ab163c633e5
3,718
py
Python
torrent_client/algorithms/uploader.py
x0x/polygon
a3df41594d3590b99a3b17cc0fe68d8da6ebe5bb
[ "MIT" ]
141
2016-05-24T19:33:07.000Z
2022-03-21T11:56:28.000Z
torrent_client/algorithms/uploader.py
x0x/polygon
a3df41594d3590b99a3b17cc0fe68d8da6ebe5bb
[ "MIT" ]
11
2017-11-20T12:11:41.000Z
2022-01-04T15:42:19.000Z
torrent_client/algorithms/uploader.py
x0x/polygon
a3df41594d3590b99a3b17cc0fe68d8da6ebe5bb
[ "MIT" ]
39
2017-01-13T05:19:25.000Z
2022-02-19T06:40:31.000Z
import asyncio import itertools import logging import random import time from typing import List, Iterable, cast from torrent_client.algorithms.peer_manager import PeerManager from torrent_client.models import Peer, TorrentInfo from torrent_client.utils import humanize_size class Uploader: def __init__(self, torrent_info: TorrentInfo, logger: logging.Logger, peer_manager: PeerManager): self._download_info = torrent_info.download_info self._statistics = self._download_info.session_statistics self._logger = logger self._peer_manager = peer_manager CHOKING_CHANGING_TIME = 10 UPLOAD_PEER_COUNT = 4 ITERS_PER_OPTIMISTIC_UNCHOKING = 3 CONNECTED_RECENTLY_THRESHOLD = 60 CONNECTED_RECENTLY_COEFF = 3 def _select_optimistically_unchoked(self, peers: Iterable[Peer]) -> Peer: cur_time = time.time() connected_recently = [] remaining_peers = [] peer_data = self._peer_manager.peer_data for peer in peers: if cur_time - peer_data[peer].connected_time <= Uploader.CONNECTED_RECENTLY_THRESHOLD: connected_recently.append(peer) else: remaining_peers.append(peer) max_index = len(remaining_peers) + Uploader.CONNECTED_RECENTLY_COEFF * len(connected_recently) - 1 index = random.randint(0, max_index) if index < len(remaining_peers): return remaining_peers[index] return connected_recently[(index - len(remaining_peers)) % len(connected_recently)] def get_peer_upload_rate(self, peer: Peer) -> int: data = self._peer_manager.peer_data[peer] rate = data.client.downloaded # We owe them for downloading if self._download_info.complete: rate += data.client.uploaded # To reach maximal upload speed return rate async def execute(self): prev_unchoked_peers = set() optimistically_unchoked = None for i in itertools.count(): peer_data = self._peer_manager.peer_data alive_peers = list(sorted(peer_data.keys(), key=self.get_peer_upload_rate, reverse=True)) cur_unchoked_peers = set() interested_count = 0 if Uploader.UPLOAD_PEER_COUNT: if i % Uploader.ITERS_PER_OPTIMISTIC_UNCHOKING == 0: if alive_peers: optimistically_unchoked = self._select_optimistically_unchoked(alive_peers) else: optimistically_unchoked = None if optimistically_unchoked is not None and optimistically_unchoked in peer_data: cur_unchoked_peers.add(optimistically_unchoked) if peer_data[optimistically_unchoked].client.peer_interested: interested_count += 1 for peer in cast(List[Peer], alive_peers): if interested_count == Uploader.UPLOAD_PEER_COUNT: break if peer_data[peer].client.peer_interested: interested_count += 1 cur_unchoked_peers.add(peer) for peer in prev_unchoked_peers - cur_unchoked_peers: if peer in peer_data: peer_data[peer].client.am_choking = True for peer in cur_unchoked_peers: peer_data[peer].client.am_choking = False self._logger.debug('now %s peers are unchoked (total_uploaded = %s)', len(cur_unchoked_peers), humanize_size(self._statistics.total_uploaded)) await asyncio.sleep(Uploader.CHOKING_CHANGING_TIME) prev_unchoked_peers = cur_unchoked_peers
39.978495
106
0.654115
3,439
0.92496
0
0
0
0
1,855
0.498924
109
0.029317
385d6856a9a5bd3cc3198cc6a148973209e3fb30
1,898
py
Python
game/Tableros.py
GeinerGV/TS1_ProyectoFinal
b433a9b7a9bafe82186fa6b90b37fbbe35cbf12d
[ "MIT" ]
null
null
null
game/Tableros.py
GeinerGV/TS1_ProyectoFinal
b433a9b7a9bafe82186fa6b90b37fbbe35cbf12d
[ "MIT" ]
null
null
null
game/Tableros.py
GeinerGV/TS1_ProyectoFinal
b433a9b7a9bafe82186fa6b90b37fbbe35cbf12d
[ "MIT" ]
null
null
null
from pygame import sprite, surface, Color from game.Bloques import CeldasTablero from game.Snake import Snake class AreaTablero(sprite.Sprite): def __init__(self, size, pos, bgcolor, estructura = None): sprite.Sprite.__init__(self) self.image = surface.Surface(size) self.image.fill(Color(bgcolor)) self.rect = self.image.get_rect() self.rect.move_ip(pos) self.tableroCnt = TableroCnt() tablero = Tablero([42, 48], size, estructura) self.tableroCnt.add(tablero) # self.tableroCnt.add(Snake(tablero, 0, pos=(3,0))) self.tableroCnt.draw(self.image) # print(sprite.groupcollide(tablero.celdas.filas[2], tablero.celdas.columnas[3], False, False)) self.actualizar = False def update(self, *args): self.tableroCnt.update(*args) class TableroCnt(sprite.GroupSingle): pass class Tablero(sprite.Sprite): def __init__(self, rangoCelda, maxSize, estructura = dict()): sprite.Sprite.__init__(self) self.rangeSize = (rangoCelda[0], rangoCelda[1]) self.sizeCelda = self.rangeSize[0] self.dimension = (int(maxSize[0]/self.sizeCelda), int(maxSize[1]/self.sizeCelda)) color = estructura["color"] if "color" in estructura else dict() bgcolor = color.pop("0") if len(color) and "0" in color else "gray" self.celdas = CeldasTablero(self.sizeCelda, self.dimension, colors=color, estructura=estructura["celdas"] if "celdas" in estructura else None) del color sizeSurf = tuple(map(lambda val: val*self.sizeCelda, self.dimension)) self.image = surface.Surface(sizeSurf) self.image.fill(Color(bgcolor)) del sizeSurf, bgcolor self.celdas.draw(self.image) self.rect = self.image.get_rect() self.rect.center = (int(maxSize[0]/2), int(maxSize[1]/2)) # Draw Serpiente self.snake = Snake(self, 0, pos=(5,5), velocidad=estructura["vel"] if "vel" in estructura else None) self.snake.draw(self.image) def update(self, *args): self.snake.update(*args)
37.215686
144
0.727608
1,783
0.93941
0
0
0
0
0
0
214
0.11275
385fbc5a17a50e64c4dcfcdc7d4027af3cdc018a
1,688
py
Python
Modules/Projects/models/project.py
Carlosma7/Odoo
c234fcc18d15d4d8369e237286bee610fd76ceee
[ "CC0-1.0" ]
null
null
null
Modules/Projects/models/project.py
Carlosma7/Odoo
c234fcc18d15d4d8369e237286bee610fd76ceee
[ "CC0-1.0" ]
null
null
null
Modules/Projects/models/project.py
Carlosma7/Odoo
c234fcc18d15d4d8369e237286bee610fd76ceee
[ "CC0-1.0" ]
null
null
null
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.exceptions import ValidationError # Class for project management and their relationships class Projects(models.Model): # Name of table _name = "projects.project" # Simple fields of the object name = fields.Char(string="Project title", required=True) identifier = fields.Char(string="ID", required=True) locality = fields.Char(string="Locality") province = fields.Char(string="Province") start_date = fields.Date(string="Start date") # Relational fields with other classes department_ids = fields.Many2one('projects.department', string="Department") # department_id employee_id = fields.Many2many('projects.employee', string="Employees") # employee_ids # Constraint of the employees working in the project @api.constrains('employee_id') @api.multi def _check_department(self): for record in self: # If we have a department if record.department_ids: # Iterate over all employees selected for the project for employee_x in record.employee_id: # If any of the employees doesn't belong to the same department of the project, then raise a ValidationError if employee_x.department_id.name is not record.department_ids.name: raise ValidationError("Employee %s is not valid because he doesn't belong to the project's department." % employee_x.name) # Extension Class for the project class class PriorityProjects(models.Model): # We inherit from the project class and use the same table _inherit = 'projects.project' # Add a new field to save the deadline of a project limit_date = fields.Date(string="Limit date", required=True)
41.170732
129
0.742299
1,475
0.873815
0
0
578
0.342417
0
0
844
0.5
385fcab1d94b44c44b147f9d7caf4a23de41ae7a
402
py
Python
models/food.py
ByK95/food_order
c3a40f00128cc381894b80b61ca6b919bbf49c4e
[ "MIT" ]
1
2022-01-20T10:30:05.000Z
2022-01-20T10:30:05.000Z
models/food.py
ByK95/food_order
c3a40f00128cc381894b80b61ca6b919bbf49c4e
[ "MIT" ]
null
null
null
models/food.py
ByK95/food_order
c3a40f00128cc381894b80b61ca6b919bbf49c4e
[ "MIT" ]
null
null
null
from app.shared.models import db from app.models.mixins import ModelMixin class Food(ModelMixin, db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False) restourant_id = db.Column( db.Integer, db.ForeignKey("restourant.id"), nullable=False )
33.5
85
0.716418
325
0.808458
0
0
0
0
0
0
28
0.069652
3860c236069152282ade2ef47710a9608a5cce61
452
py
Python
Solutions.py/2563/r1_bird.py
TianTcl/KU01-challenge
5a0069840e26d9a8cf8fa592679341154fcb3a15
[ "MIT" ]
2
2021-10-30T06:27:48.000Z
2021-10-30T08:14:50.000Z
Solutions.py/2563/r1_bird.py
TianTcl/KU01-challenge
5a0069840e26d9a8cf8fa592679341154fcb3a15
[ "MIT" ]
null
null
null
Solutions.py/2563/r1_bird.py
TianTcl/KU01-challenge
5a0069840e26d9a8cf8fa592679341154fcb3a15
[ "MIT" ]
null
null
null
tree_count, tree_hinput, tree_chosen = int(input()), input().split(), 0 tree_height = [int(x) for x in tree_hinput] for each_tree in range(tree_count): if each_tree==0 and tree_height[0]>tree_height[1]:tree_chosen+=1 elif each_tree==tree_count-1 and tree_height[each_tree]>tree_height[each_tree-1]:tree_chosen+=1 elif tree_height[each_tree-1]<tree_height[each_tree]>tree_height[each_tree+1]:tree_chosen+=1 print(tree_chosen) # Passed
56.5
100
0.75885
0
0
0
0
0
0
0
0
8
0.017699
3860cb5cba14b8fecfed007842043e8fa3e05ff6
2,230
py
Python
code/ExperimentModules/dataset_manager.py
PAL-ML/CLIPPER
c971c89a9315d27ddb007082ff209153859f5906
[ "MIT" ]
3
2021-06-05T05:00:54.000Z
2021-06-16T21:17:52.000Z
code/ExperimentModules/dataset_manager.py
PAL-ML/CLIPPER
c971c89a9315d27ddb007082ff209153859f5906
[ "MIT" ]
null
null
null
code/ExperimentModules/dataset_manager.py
PAL-ML/CLIPPER
c971c89a9315d27ddb007082ff209153859f5906
[ "MIT" ]
null
null
null
from . import datasets class DatasetManager: def __init__(self): self.available_datasets = { 'omniglot': datasets.OmniglotDataset(), 'lfw': datasets.LfwDataset(), 'clevr': datasets.ClevrDataset(), 'caltech_birds2011': datasets.CUBDataset(), 'imagenet_a': datasets.ImagenetADataset(), 'imagenet_r': datasets.ImagenetRDataset(), 'mini_imagenet': datasets.MiniImagenetDataset(), 'imagenet_sketch': datasets.ImagenetSketchDataset(), 'imagenet_tiered': datasets.ImagenetTieredDataset(), 'ucf_101': datasets.UCF101Dataset(), 'indoor_scene_recognition': datasets.ISRDataset(), 'fgcv_imaterialist': datasets.IMaterialistDataset(), 'visda19': datasets.VisDA19Dataset(), # 'image_matching': datasets.ImageMatchingDataset(), 'sun397': datasets.SUN397Dataset(), 'cifar10': datasets.Cifar10Dataset(), 'coco/2017': datasets.COCO2017Dataset(), 'yale_faces': datasets.YaleFaces(), 'utk_faces': datasets.UTKFaces(), 'celeba_faces': datasets.CelebAFaces() } self.dataset = None def get_supported_datasets(self): return self.available_datasets.keys() def get_class_names(self): if not self.dataset: raise Exception("Make sure load_dataset is run before get_class_names is run...") return self.dataset.get_class_names() def load_dataset(self, dataset_name, split='test', domain='clipart', img_width=224, img_height=224): if dataset_name in self.available_datasets.keys(): self.dataset = self.available_datasets[dataset_name] if dataset_name == "visda19": data = self.dataset.load(split=split, domain=domain, img_width=img_width, img_height=img_height) else: data = self.dataset.load(split=split, img_width=img_width, img_height=img_height) return data else: print("Dataset not implemented") print("Please choose from the following:") print(self.get_supported_datasets())
41.296296
112
0.622422
2,206
0.989238
0
0
0
0
0
0
442
0.198206
386175f2b9107f26e003609e3390ad4e1d9fa916
1,574
py
Python
setup.py
sjkingo/ticketus
90f2781af9418e9e2c6470ca50c9a6af9ce098ff
[ "BSD-2-Clause" ]
3
2019-02-09T10:52:55.000Z
2021-09-19T14:14:36.000Z
setup.py
sjkingo/ticketus
90f2781af9418e9e2c6470ca50c9a6af9ce098ff
[ "BSD-2-Clause" ]
null
null
null
setup.py
sjkingo/ticketus
90f2781af9418e9e2c6470ca50c9a6af9ce098ff
[ "BSD-2-Clause" ]
3
2018-03-04T18:05:02.000Z
2021-09-19T14:14:38.000Z
from setuptools import find_packages, setup from ticketus import __version__ as version setup( name='ticketus', version=version, license='BSD', author='Sam Kingston', author_email='sam@sjkwi.com.au', description='Ticketus is a simple, no-frills ticketing system for helpdesks.', url='https://github.com/sjkingo/ticketus', install_requires=[ 'Django >= 1.6.10', 'IMAPClient', 'django-grappelli', 'email-reply-parser', 'mistune', 'psycopg2', 'python-dateutil', ], zip_safe=False, include_package_data=True, packages=find_packages(exclude=['ticketus_settings']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', 'Topic :: Communications :: Email', 'Topic :: Software Development :: Bug Tracking', 'Topic :: System :: Systems Administration', ], scripts=[ 'import_scripts/ticketus_import_freshdesk', 'import_scripts/ticketus_import_github', 'bin_scripts/ticketus_mailgw_imap4', 'bin_scripts/ticketus-admin', ], )
32.791667
82
0.625159
0
0
0
0
0
0
0
0
952
0.604828
38621c0d16222e67db6c7b5b3f98915d36505bc9
35,178
py
Python
pygame_gui/elements/ui_window.py
OleksiiBulba/pygame_gui
6751b2796612f8b2ed6cc8b093507eeef7d106c5
[ "MIT" ]
null
null
null
pygame_gui/elements/ui_window.py
OleksiiBulba/pygame_gui
6751b2796612f8b2ed6cc8b093507eeef7d106c5
[ "MIT" ]
null
null
null
pygame_gui/elements/ui_window.py
OleksiiBulba/pygame_gui
6751b2796612f8b2ed6cc8b093507eeef7d106c5
[ "MIT" ]
null
null
null
from typing import Union, Tuple import pygame from pygame_gui._constants import UI_WINDOW_CLOSE, UI_WINDOW_MOVED_TO_FRONT, UI_BUTTON_PRESSED from pygame_gui._constants import OldType from pygame_gui.core import ObjectID from pygame_gui.core.interfaces import IContainerLikeInterface, IUIContainerInterface from pygame_gui.core.interfaces import IWindowInterface, IUIManagerInterface from pygame_gui.core import UIElement, UIContainer from pygame_gui.core.drawable_shapes import RectDrawableShape, RoundedRectangleShape from pygame_gui.elements.ui_button import UIButton class UIWindow(UIElement, IContainerLikeInterface, IWindowInterface): """ A base class for window GUI elements, any windows should inherit from this class. :param rect: A rectangle, representing size and position of the window (including title bar, shadow and borders). :param manager: The UIManager that manages this UIWindow. :param window_display_title: A string that will appear in the windows title bar if it has one. :param element_id: An element ID for this window, if one is not supplied it defaults to 'window'. :param object_id: An optional object ID for this window, useful for distinguishing different windows. :param resizable: Whether this window is resizable or not, defaults to False. :param visible: Whether the element is visible by default. Warning - container visibility may override this. """ def __init__(self, rect: pygame.Rect, manager: IUIManagerInterface, window_display_title: str = "", element_id: Union[str, None] = None, object_id: Union[ObjectID, str, None] = None, resizable: bool = False, visible: int = 1): self.window_display_title = window_display_title self._window_root_container = None # type: Union[UIContainer, None] self.resizable = resizable self.minimum_dimensions = (100, 100) self.edge_hovering = [False, False, False, False] super().__init__(rect, manager, container=None, starting_height=1, layer_thickness=1, visible=visible) if element_id is None: element_id = 'window' self._create_valid_ids(container=None, parent_element=None, object_id=object_id, element_id=element_id) self.set_image(self.ui_manager.get_universal_empty_surface()) self.bring_to_front_on_focused = True self.is_blocking = False # blocks all clicking events from interacting beyond this window self.resizing_mode_active = False self.start_resize_point = (0, 0) self.start_resize_rect = None # type: Union[pygame.Rect, None] self.grabbed_window = False self.starting_grab_difference = (0, 0) self.background_colour = None self.border_colour = None self.shape = 'rectangle' self.enable_title_bar = True self.enable_close_button = True self.title_bar_height = 28 self.title_bar_close_button_width = self.title_bar_height # UI elements self.window_element_container = None # type: Union[UIContainer, None] self.title_bar = None # type: Union[UIButton, None] self.close_window_button = None # type: Union[UIButton, None] self.rebuild_from_changed_theme_data() self.window_stack = self.ui_manager.get_window_stack() self.window_stack.add_new_window(self) def set_blocking(self, state: bool): """ Sets whether this window being open should block clicks to the rest of the UI or not. Defaults to False. :param state: True if this window should block mouse clicks. """ self.is_blocking = state def set_minimum_dimensions(self, dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]]): """ If this window is resizable, then the dimensions we set here will be the minimum that users can change the window to. They are also used as the minimum size when 'set_dimensions' is called. :param dimensions: The new minimum dimension for the window. """ self.minimum_dimensions = (min(self.ui_container.rect.width, int(dimensions[0])), min(self.ui_container.rect.height, int(dimensions[1]))) if ((self.rect.width < self.minimum_dimensions[0]) or (self.rect.height < self.minimum_dimensions[1])): new_width = max(self.minimum_dimensions[0], self.rect.width) new_height = max(self.minimum_dimensions[1], self.rect.height) self.set_dimensions((new_width, new_height)) def set_dimensions(self, dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]]): """ Set the size of this window and then re-sizes and shifts the contents of the windows container to fit the new size. :param dimensions: The new dimensions to set. """ # clamp to minimum dimensions and container size dimensions = (min(self.ui_container.rect.width, max(self.minimum_dimensions[0], int(dimensions[0]))), min(self.ui_container.rect.height, max(self.minimum_dimensions[1], int(dimensions[1])))) # Don't use a basic gate on this set dimensions method because the container may be a # different size to the window super().set_dimensions(dimensions) if self._window_root_container is not None: new_container_dimensions = (self.relative_rect.width - (2 * self.shadow_width), self.relative_rect.height - (2 * self.shadow_width)) if new_container_dimensions != self._window_root_container.relative_rect.size: self._window_root_container.set_dimensions(new_container_dimensions) container_pos = (self.relative_rect.x + self.shadow_width, self.relative_rect.y + self.shadow_width) self._window_root_container.set_relative_position(container_pos) def set_relative_position(self, position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]]): """ Method to directly set the relative rect position of an element. :param position: The new position to set. """ super().set_relative_position(position) if self._window_root_container is not None: container_pos = (self.relative_rect.x + self.shadow_width, self.relative_rect.y + self.shadow_width) self._window_root_container.set_relative_position(container_pos) def set_position(self, position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]]): """ Method to directly set the absolute screen rect position of an element. :param position: The new position to set. """ super().set_position(position) if self._window_root_container is not None: container_pos = (self.relative_rect.x + self.shadow_width, self.relative_rect.y + self.shadow_width) self._window_root_container.set_relative_position(container_pos) def process_event(self, event: pygame.event.Event) -> bool: """ Handles resizing & closing windows. Gives UI Windows access to pygame events. Derived windows should super() call this class if they implement their own process_event method. :param event: The event to process. :return bool: Return True if this element should consume this event and not pass it to the rest of the UI. """ consumed_event = False if self.is_blocking and event.type == pygame.MOUSEBUTTONDOWN: consumed_event = True if (self is not None and event.type == pygame.MOUSEBUTTONDOWN and event.button in [pygame.BUTTON_LEFT, pygame.BUTTON_MIDDLE, pygame.BUTTON_RIGHT]): scaled_mouse_pos = self.ui_manager.calculate_scaled_mouse_position(event.pos) edge_hovered = (self.edge_hovering[0] or self.edge_hovering[1] or self.edge_hovering[2] or self.edge_hovering[3]) if (self.is_enabled and event.button == pygame.BUTTON_LEFT and edge_hovered): self.resizing_mode_active = True self.start_resize_point = scaled_mouse_pos self.start_resize_rect = self.rect.copy() consumed_event = True elif self.hover_point(scaled_mouse_pos[0], scaled_mouse_pos[1]): consumed_event = True if (self is not None and event.type == pygame.MOUSEBUTTONUP and event.button == pygame.BUTTON_LEFT and self.resizing_mode_active): self.resizing_mode_active = False if event.type == UI_BUTTON_PRESSED and event.ui_element == self.close_window_button: self.on_close_window_button_pressed() return consumed_event def check_clicked_inside_or_blocking(self, event: pygame.event.Event) -> bool: """ A quick event check outside of the normal event processing so that this window is brought to the front of the window stack if we click on any of the elements contained within it. :param event: The event to check. :return: returns True if the event represents a click inside this window or the window is blocking. """ consumed_event = False if self.is_blocking and event.type == pygame.MOUSEBUTTONDOWN: consumed_event = True if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: scaled_mouse_pos = self.ui_manager.calculate_scaled_mouse_position(event.pos) if self.hover_point(scaled_mouse_pos[0], scaled_mouse_pos[1]) or (self.edge_hovering[0] or self.edge_hovering[1] or self.edge_hovering[2] or self.edge_hovering[3]): if self.is_enabled and self.bring_to_front_on_focused: self.window_stack.move_window_to_front(self) consumed_event = True return consumed_event def update(self, time_delta: float): """ A method called every update cycle of our application. Designed to be overridden by derived classes but also has a little functionality to make sure the window's layer 'thickness' is accurate and to handle window resizing. :param time_delta: time passed in seconds between one call to this method and the next. """ super().update(time_delta) # This is needed to keep the window in sync with the container after adding elements to it if self._window_root_container.layer_thickness != self.layer_thickness: self.layer_thickness = self._window_root_container.layer_thickness if self.title_bar is not None: if self.title_bar.held: mouse_x, mouse_y = self.ui_manager.get_mouse_position() if not self.grabbed_window: self.window_stack.move_window_to_front(self) self.grabbed_window = True self.starting_grab_difference = (mouse_x - self.rect.x, mouse_y - self.rect.y) current_grab_difference = (mouse_x - self.rect.x, mouse_y - self.rect.y) adjustment_required = (current_grab_difference[0] - self.starting_grab_difference[0], current_grab_difference[1] - self.starting_grab_difference[1]) self.set_relative_position((self.relative_rect.x + adjustment_required[0], self.relative_rect.y + adjustment_required[1])) else: self.grabbed_window = False if self.resizing_mode_active: self._update_drag_resizing() def _update_drag_resizing(self): """ Re-sizes a window that is being dragged around its the edges by the mouse. """ x_pos = self.rect.left y_pos = self.rect.top x_dimension = self.rect.width y_dimension = self.rect.height mouse_x, mouse_y = self.ui_manager.get_mouse_position() x_diff = mouse_x - self.start_resize_point[0] y_diff = mouse_y - self.start_resize_point[1] if y_dimension >= self.minimum_dimensions[1]: y_pos = self.start_resize_rect.y y_dimension = self.start_resize_rect.height if self.edge_hovering[1]: y_dimension = self.start_resize_rect.height - y_diff y_pos = self.start_resize_rect.y + y_diff elif self.edge_hovering[3]: y_dimension = self.start_resize_rect.height + y_diff if y_dimension < self.minimum_dimensions[1]: if y_diff > 0: y_pos = self.rect.bottom - self.minimum_dimensions[1] else: y_pos = self.rect.top if x_dimension >= self.minimum_dimensions[0]: x_pos = self.start_resize_rect.x x_dimension = self.start_resize_rect.width if self.edge_hovering[0]: x_dimension = self.start_resize_rect.width - x_diff x_pos = self.start_resize_rect.x + x_diff elif self.edge_hovering[2]: x_dimension = self.start_resize_rect.width + x_diff if x_dimension < self.minimum_dimensions[0]: if x_diff > 0: x_pos = self.rect.right - self.minimum_dimensions[0] else: x_pos = self.rect.left x_dimension = max(self.minimum_dimensions[0], min(self.ui_container.rect.width, x_dimension)) y_dimension = max(self.minimum_dimensions[1], min(self.ui_container.rect.height, y_dimension)) self.set_position((x_pos, y_pos)) self.set_dimensions((x_dimension, y_dimension)) def get_container(self) -> IUIContainerInterface: """ Returns the container that should contain all the UI elements in this window. :return UIContainer: The window's container. """ return self.window_element_container def can_hover(self) -> bool: """ Called to test if this window can be hovered. """ return not (self.resizing_mode_active or (self.title_bar is not None and self.title_bar.held)) # noinspection PyUnusedLocal def check_hover(self, time_delta: float, hovered_higher_element: bool) -> bool: """ For the window the only hovering we care about is the edges if this is a resizable window. :param time_delta: time passed in seconds between one call to this method and the next. :param hovered_higher_element: Have we already hovered an element/window above this one. """ hovered = False if not self.resizing_mode_active: self.edge_hovering = [False, False, False, False] if self.alive() and self.can_hover() and not hovered_higher_element and self.resizable: mouse_x, mouse_y = self.ui_manager.get_mouse_position() # Build a temporary rect just a little bit larger than our container rect. resize_rect = pygame.Rect(self._window_root_container.rect.left - 4, self._window_root_container.rect.top - 4, self._window_root_container.rect.width + 8, self._window_root_container.rect.height + 8) if resize_rect.collidepoint(mouse_x, mouse_y): if resize_rect.right > mouse_x > resize_rect.right - 6: self.edge_hovering[2] = True hovered = True if resize_rect.left + 6 > mouse_x > resize_rect.left: self.edge_hovering[0] = True hovered = True if resize_rect.bottom > mouse_y > resize_rect.bottom - 6: self.edge_hovering[3] = True hovered = True if resize_rect.top + 6 > mouse_y > resize_rect.top: self.edge_hovering[1] = True hovered = True elif self.resizing_mode_active: hovered = True if self.is_blocking: hovered = True if hovered: hovered_higher_element = True self.hovered = True else: self.hovered = False return hovered_higher_element def get_top_layer(self) -> int: """ Returns the 'highest' layer used by this window so that we can correctly place other windows on top of it. :return: The top layer for this window as a number (greater numbers are higher layers). """ return self._layer + self.layer_thickness def change_layer(self, new_layer: int): """ Move this window, and it's contents, to a new layer in the UI. :param new_layer: The layer to move to. """ if new_layer != self._layer: super().change_layer(new_layer) if self._window_root_container is not None: self._window_root_container.change_layer(new_layer) if self._window_root_container.layer_thickness != self.layer_thickness: self.layer_thickness = self._window_root_container.layer_thickness def on_close_window_button_pressed(self): """ Override this method to call 'hide()' instead if you want to hide a window when the close button is pressed. """ self.kill() def kill(self): """ Overrides the basic kill() method of a pygame sprite so that we also kill all the UI elements in this window, and remove if from the window stack. """ # old event - to be removed in 0.8.0 window_close_event = pygame.event.Event(pygame.USEREVENT, {'user_type': OldType(UI_WINDOW_CLOSE), 'ui_element': self, 'ui_object_id': self.most_specific_combined_id}) pygame.event.post(window_close_event) # new event window_close_event = pygame.event.Event(UI_WINDOW_CLOSE, {'ui_element': self, 'ui_object_id': self.most_specific_combined_id}) pygame.event.post(window_close_event) self.window_stack.remove_window(self) self._window_root_container.kill() super().kill() def rebuild(self): """ Rebuilds the window when the theme has changed. """ if self._window_root_container is None: self._window_root_container = UIContainer(pygame.Rect(self.relative_rect.x + self.shadow_width, self.relative_rect.y + self.shadow_width, self.relative_rect.width - (2 * self.shadow_width), self.relative_rect.height - (2 * self.shadow_width)), manager=self.ui_manager, starting_height=1, is_window_root_container=True, container=None, parent_element=self, object_id="#window_root_container", visible=self.visible) if self.window_element_container is None: window_container_rect = pygame.Rect(self.border_width, self.title_bar_height, (self._window_root_container.relative_rect.width - (2 * self.border_width)), (self._window_root_container.relative_rect.height - (self.title_bar_height + self.border_width))) self.window_element_container = UIContainer(window_container_rect, self.ui_manager, starting_height=0, container=self._window_root_container, parent_element=self, object_id="#window_element_container", anchors={'top': 'top', 'bottom': 'bottom', 'left': 'left', 'right': 'right'}) theming_parameters = {'normal_bg': self.background_colour, 'normal_border': self.border_colour, 'border_width': self.border_width, 'shadow_width': self.shadow_width, 'shape_corner_radius': self.shape_corner_radius} if self.shape == 'rectangle': self.drawable_shape = RectDrawableShape(self.rect, theming_parameters, ['normal'], self.ui_manager) elif self.shape == 'rounded_rectangle': self.drawable_shape = RoundedRectangleShape(self.rect, theming_parameters, ['normal'], self.ui_manager) self.set_image(self.drawable_shape.get_fresh_surface()) self.set_dimensions(self.relative_rect.size) if self.window_element_container is not None: element_container_width = (self._window_root_container.relative_rect.width - (2 * self.border_width)) element_container_height = (self._window_root_container.relative_rect.height - (self.title_bar_height + self.border_width)) self.window_element_container.set_dimensions((element_container_width, element_container_height)) self.window_element_container.set_relative_position((self.border_width, self.title_bar_height)) if self.enable_title_bar: if self.title_bar is not None: self.title_bar.set_dimensions((self._window_root_container.relative_rect.width - self.title_bar_close_button_width, self.title_bar_height)) else: title_bar_width = (self._window_root_container.relative_rect.width - self.title_bar_close_button_width) self.title_bar = UIButton(relative_rect=pygame.Rect(0, 0, title_bar_width, self.title_bar_height), text=self.window_display_title, manager=self.ui_manager, container=self._window_root_container, parent_element=self, object_id='#title_bar', anchors={'top': 'top', 'bottom': 'top', 'left': 'left', 'right': 'right'} ) self.title_bar.set_hold_range((100, 100)) if self.enable_close_button: if self.close_window_button is not None: close_button_pos = (-self.title_bar_close_button_width, 0) self.close_window_button.set_dimensions((self.title_bar_close_button_width, self.title_bar_height)) self.close_window_button.set_relative_position(close_button_pos) else: close_rect = pygame.Rect((-self.title_bar_close_button_width, 0), (self.title_bar_close_button_width, self.title_bar_height)) self.close_window_button = UIButton(relative_rect=close_rect, text='โ•ณ', manager=self.ui_manager, container=self._window_root_container, parent_element=self, object_id='#close_button', anchors={'top': 'top', 'bottom': 'top', 'left': 'right', 'right': 'right'} ) else: if self.close_window_button is not None: self.close_window_button.kill() self.close_window_button = None else: if self.title_bar is not None: self.title_bar.kill() self.title_bar = None if self.close_window_button is not None: self.close_window_button.kill() self.close_window_button = None def rebuild_from_changed_theme_data(self): """ Called by the UIManager to check the theming data and rebuild whatever needs rebuilding for this element when the theme data has changed. """ super().rebuild_from_changed_theme_data() has_any_changed = False if self._check_misc_theme_data_changed(attribute_name='shape', default_value='rectangle', casting_func=str, allowed_values=['rectangle', 'rounded_rectangle']): has_any_changed = True if self._check_shape_theming_changed(defaults={'border_width': 1, 'shadow_width': 15, 'shape_corner_radius': 2}): has_any_changed = True background_colour = self.ui_theme.get_colour_or_gradient('dark_bg', self.combined_element_ids) if background_colour != self.background_colour: self.background_colour = background_colour has_any_changed = True border_colour = self.ui_theme.get_colour_or_gradient('normal_border', self.combined_element_ids) if border_colour != self.border_colour: self.border_colour = border_colour has_any_changed = True if self._check_title_bar_theming_changed(): has_any_changed = True if has_any_changed: self.rebuild() def _check_title_bar_theming_changed(self): """ Check to see if any theming parameters for the title bar have changed. :return: True if any of the theming parameters have changed. """ has_any_changed = False def parse_to_bool(str_data: str): return bool(int(str_data)) if self._check_misc_theme_data_changed(attribute_name='enable_title_bar', default_value=True, casting_func=parse_to_bool): has_any_changed = True if self.enable_title_bar: if self._check_misc_theme_data_changed(attribute_name='title_bar_height', default_value=28, casting_func=int): has_any_changed = True self.title_bar_close_button_width = self.title_bar_height if self._check_misc_theme_data_changed(attribute_name='enable_close_button', default_value=True, casting_func=parse_to_bool): has_any_changed = True if not self.enable_close_button: self.title_bar_close_button_width = 0 else: self.title_bar_height = 0 return has_any_changed def should_use_window_edge_resize_cursor(self) -> bool: """ Returns true if this window is in a state where we should display one of the resizing cursors :return: True if a resizing cursor is needed. """ return (self.hovered or self.resizing_mode_active) and any(self.edge_hovering) def get_hovering_edge_id(self) -> str: """ Gets the ID of the combination of edges we are hovering for use by the cursor system. :return: a string containing the edge combination ID (e.g. xy,yx,xl,xr,yt,yb) """ if ((self.edge_hovering[0] and self.edge_hovering[1]) or (self.edge_hovering[2] and self.edge_hovering[3])): return 'xy' elif ((self.edge_hovering[0] and self.edge_hovering[3]) or (self.edge_hovering[2] and self.edge_hovering[1])): return 'yx' elif self.edge_hovering[0]: return 'xl' elif self.edge_hovering[2]: return 'xr' elif self.edge_hovering[3]: return 'yb' else: return 'yt' def on_moved_to_front(self): """ Called when a window is moved to the front of the stack. """ # old event - to be removed in 0.8.0 window_front_event = pygame.event.Event(pygame.USEREVENT, {'user_type': OldType(UI_WINDOW_MOVED_TO_FRONT), 'ui_element': self, 'ui_object_id': self.most_specific_combined_id}) pygame.event.post(window_front_event) # new event window_front_event = pygame.event.Event(UI_WINDOW_MOVED_TO_FRONT, {'ui_element': self, 'ui_object_id': self.most_specific_combined_id}) pygame.event.post(window_front_event) def set_display_title(self, new_title: str): """ Set the title of the window. :param new_title: The title to set. """ self.window_display_title = new_title self.title_bar.set_text(self.window_display_title) def disable(self): """ Disables the window and it's contents so it is no longer interactive. """ if self.is_enabled: self.is_enabled = False self._window_root_container.disable() def enable(self): """ Enables the window and it's contents so it is interactive again. """ if not self.is_enabled: self.is_enabled = True self._window_root_container.enable() def show(self): """ In addition to the base UIElement.show() - show the _window_root_container which will propagate and show all the children. """ super().show() self._window_root_container.show() def hide(self): """ In addition to the base UIElement.hide() - hide the _window_root_container which will propagate and hide all the children. """ super().hide() self._window_root_container.hide() def get_relative_mouse_pos(self): """ Returns the current mouse position relative to the inside of this window. If the cursor is outside the window contents area it returns None :return: tuple of relative mouse co-ords or None """ abs_mouse_pos = pygame.mouse.get_pos() rel_mouse_pos = None inside_window_rect = self.get_container().get_rect() if inside_window_rect.contains(pygame.Rect(abs_mouse_pos, (1, 1))): window_contents_top_left = inside_window_rect.topleft rel_mouse_pos = (abs_mouse_pos[0] - window_contents_top_left[0], abs_mouse_pos[1] - window_contents_top_left[1]) return rel_mouse_pos
45.924282
100
0.541844
34,603
0.983599
0
0
0
0
0
0
7,375
0.209636
386222fd913fe9177b311050c4eb50f381d14d63
714
py
Python
_pytest/test_interpreter.py
awesome-archive/rasa_nlu
f58df5d86bac470e3a579ea07232bea0d90708b3
[ "Apache-2.0" ]
2
2016-12-20T13:19:44.000Z
2017-01-16T10:44:35.000Z
_pytest/test_interpreter.py
awesome-archive/rasa_nlu
f58df5d86bac470e3a579ea07232bea0d90708b3
[ "Apache-2.0" ]
null
null
null
_pytest/test_interpreter.py
awesome-archive/rasa_nlu
f58df5d86bac470e3a579ea07232bea0d90708b3
[ "Apache-2.0" ]
1
2017-01-02T15:16:49.000Z
2017-01-02T15:16:49.000Z
from rasa_nlu.interpreters.simple_interpreter import HelloGoodbyeInterpreter interpreter = HelloGoodbyeInterpreter() def test_samples(): samples = [ ("Hey there", {'text': "Hey there", 'intent': 'greet', 'entities': {}}), ("good bye for now", {'text': "good bye for now", 'intent': 'goodbye', 'entities': {}}) ] for text, result in samples: assert interpreter.parse(text) == result, "text : {0} \nresult : {1}, expected {2}".format(text, interpreter.parse( text), result)
44.625
117
0.460784
0
0
0
0
0
0
0
0
163
0.228291
38622882e267e4da59ec73aecc06c60747233d97
355
py
Python
Python/XGBoost/feature-importance.py
James-McNeill/Learning
3c4fe1a64240cdf5614db66082bd68a2f16d2afb
[ "MIT" ]
null
null
null
Python/XGBoost/feature-importance.py
James-McNeill/Learning
3c4fe1a64240cdf5614db66082bd68a2f16d2afb
[ "MIT" ]
null
null
null
Python/XGBoost/feature-importance.py
James-McNeill/Learning
3c4fe1a64240cdf5614db66082bd68a2f16d2afb
[ "MIT" ]
null
null
null
# Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {'objective':'reg:linear', 'max_depth':4} # Train the model: xg_reg xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10) # Plot the feature importances xgb.plot_importance(xg_reg) plt.show()
27.307692
77
0.771831
0
0
0
0
0
0
0
0
167
0.470423
3863f84f9600ae0034635596fd41e100463bc7f4
646
py
Python
Camera.py
ArnaBannonymus/Arnab
a6949a43817bd9ce44f5318f558a8066d735ecc4
[ "MIT" ]
null
null
null
Camera.py
ArnaBannonymus/Arnab
a6949a43817bd9ce44f5318f558a8066d735ecc4
[ "MIT" ]
null
null
null
Camera.py
ArnaBannonymus/Arnab
a6949a43817bd9ce44f5318f558a8066d735ecc4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 13:22:02 2018 @author: Arnab Bhowmik """ import cv2 import numpy as np cap=cv2.VideoCapture(1) while True: _,frame=cap.read() hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) #hsv hue sat value lower_red=np.array([0,0,0]) upper_red=np.array([255,255,255]) mask=cv2.inRange(hsv,lower_red,upper_red) res=cv2.bitwise_and(frame,mask=mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k=cv2.waitKey(5) & 0xFF if (k==27): break cv2.destroyAllWindows() cap.release()
20.83871
46
0.595975
0
0
0
0
0
0
0
0
132
0.204334
38648d598f12e3c1199c23af373d46072e83069c
811
py
Python
tests/api/circulation/test_loan_item_resolver.py
NRodriguezcuellar/invenio-app-ils
144a25a6c56330b214c6fd0b832220fa71f2e68a
[ "MIT" ]
41
2018-09-04T13:00:46.000Z
2022-03-24T20:45:56.000Z
tests/api/circulation/test_loan_item_resolver.py
NRodriguezcuellar/invenio-app-ils
144a25a6c56330b214c6fd0b832220fa71f2e68a
[ "MIT" ]
720
2017-03-10T08:02:41.000Z
2022-01-14T15:36:37.000Z
tests/api/circulation/test_loan_item_resolver.py
NRodriguezcuellar/invenio-app-ils
144a25a6c56330b214c6fd0b832220fa71f2e68a
[ "MIT" ]
54
2017-03-09T16:05:29.000Z
2022-03-17T08:34:51.000Z
# -*- coding: utf-8 -*- # # Copyright (C) 2019 CERN. # # Invenio-Circulation is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Tests for loan item resolver.""" from invenio_circulation.api import Loan def test_loan_item_resolver(app, testdata): """Test item resolving from loan.""" loan_pid = testdata["loans"][1]["pid"] loan = Loan.get_record_by_pid(loan_pid) loan = loan.replace_refs() assert loan["item"]["pid"] == loan["item_pid"]["value"] def test_loan_item_resolver_for_empty_item_pid(app, testdata): """Test item resolving from loan.""" loan_pid = testdata["loans"][0]["pid"] loan = Loan.get_record_by_pid(loan_pid) loan = loan.replace_refs() assert loan["item"] == dict()
30.037037
77
0.690506
0
0
0
0
0
0
0
0
368
0.453761
38654864183d04c052061939c5a348db4ef0dd54
2,611
py
Python
tools/coverage_helper.py
cohortfsllc/cohort-cocl2-sandbox
0ac6669d1a459d65a52007b80d5cffa4ef330287
[ "BSD-3-Clause" ]
6
2015-02-06T23:41:01.000Z
2015-10-21T03:08:51.000Z
tools/coverage_helper.py
cohortfsllc/cohort-cocl2-sandbox
0ac6669d1a459d65a52007b80d5cffa4ef330287
[ "BSD-3-Clause" ]
null
null
null
tools/coverage_helper.py
cohortfsllc/cohort-cocl2-sandbox
0ac6669d1a459d65a52007b80d5cffa4ef330287
[ "BSD-3-Clause" ]
1
2019-10-02T08:41:50.000Z
2019-10-02T08:41:50.000Z
#!/usr/bin/python # Copyright (c) 2011 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os # # CoverageHelper # # The CoverageHelper is an object which defines lists used by the coverage # scripts for grouping or filtering source by path, as well as filtering sources # by name. class CoverageHelper(object): def __init__(self): self.ignore_set = self.Ignore() self.path_filter = self.Filter() self.groups = self.Groups() # # Return a list of fully qualified paths for the directories availible # at the input path specified. # def GetDirList(self, startpath): paths = [] realpath = os.path.realpath(startpath) for name in os.listdir(realpath): path = os.path.join(realpath, name) if os.path.isdir(path): paths.append(path) return paths # # Set of results to ignore by path. # def Filter(self): filters = [ 'src/trusted/sel_universal', 'src/third_party/valgrind', 'src/tools'] return set([os.path.realpath(path) for path in filters]) # # Set of files to ignore because they are in the TCB but used by the # validator. # def Ignore(self): return set([ 'cpu_x86_test.c', 'defsize64.c', 'lock_insts.c', 'lock_insts.h', 'long_mode.c', 'long_mode.h', 'nacl_illegal.c', 'nacl_illegal.h', 'nc_read_segment.c', 'nc_read_segment.h', 'nc_rep_prefix.c', 'nc_rep_prefix.h', 'ncdecodeX87.c', 'ncdecode_OF.c', 'ncdecode_forms.c', 'ncdecode_forms.h', 'ncdecode_onebyte.c', 'ncdecode_sse.c', 'ncdecode_st.c', 'ncdecode_st.h', 'ncdecode_table.c', 'ncdecode_tablegen.c', 'ncdecode_tablegen.h', 'ncdecode_tests.c', 'ncdis.c', 'ncdis_segments.c', 'ncdis_segments.h', 'ncdis_util.c', 'ncdis_util.h', 'ncenuminsts.c', 'ncenuminsts.h', 'ncval.c', 'ncval_driver.c', 'ncval_driver.h', 'ncval_tests.c', 'ze64.h', 'zero_extends.c', 'zero_extends.h', ]) # # Set of results to group by path. # def Groups(self): groups = [] groups.append(os.path.realpath('scons-out')) groups.append(os.path.realpath('src/include')) groups.append(os.path.realpath('src/tools')) groups.extend(self.GetDirList('src/trusted')) groups.extend(self.GetDirList('src/shared')) groups.extend(self.GetDirList('src/third_party')) groups.extend(self.GetDirList('..')) return groups
26.11
80
0.630793
2,221
0.850632
0
0
0
0
0
0
1,365
0.522788
38688d8d8a376d1c2a562646fe27e88fb821e1f8
414
py
Python
pylayers/antprop/tests/test_subarray.py
usmanwardag/pylayers
2e8a9bdc993b2aacc92610a9c7edf875c6c7b24a
[ "MIT" ]
143
2015-01-09T07:50:20.000Z
2022-03-02T11:26:53.000Z
pylayers/antprop/tests/test_subarray.py
usmanwardag/pylayers
2e8a9bdc993b2aacc92610a9c7edf875c6c7b24a
[ "MIT" ]
148
2015-01-13T04:19:34.000Z
2022-03-11T23:48:25.000Z
pylayers/antprop/tests/test_subarray.py
usmanwardag/pylayers
2e8a9bdc993b2aacc92610a9c7edf875c6c7b24a
[ "MIT" ]
95
2015-05-01T13:22:42.000Z
2022-03-15T11:22:28.000Z
from pylayers.antprop.aarray import * import matplotlib.pyplot as plt import pdb print('--------------') print('antprop/test_subarray.py') print('--------------') fcGHz = 60 lamda = 0.3/fcGHz N1 = [ 4,4,1] N2 = [ 2,2,1] dm1 = [lamda/2.,lamda/2.,0] dm2 = [3*lamda,3*lamda,0] A1 = AntArray(fGHz=np.array([fcGHz]),N=N1,dm=dm1,typant='Omni') A2 = AntArray(fGHz=np.array([fcGHz]),N=N2,dm=dm2,array=A1) #A1.eval()
25.875
63
0.618357
0
0
0
0
0
0
0
0
74
0.178744
38689a46aa034aebe36b6be45065cc5c708473a6
5,789
py
Python
speckle/base/resource.py
pjkottke/PySpeckle
e332c5e4c76960ab5b698f120c07d0eb15ac2262
[ "MIT" ]
24
2018-11-16T03:17:58.000Z
2021-11-19T11:32:01.000Z
speckle/base/resource.py
pjkottke/PySpeckle
e332c5e4c76960ab5b698f120c07d0eb15ac2262
[ "MIT" ]
43
2019-01-15T17:48:24.000Z
2020-12-02T19:09:55.000Z
speckle/base/resource.py
pjkottke/PySpeckle
e332c5e4c76960ab5b698f120c07d0eb15ac2262
[ "MIT" ]
12
2019-02-06T20:54:17.000Z
2020-12-01T21:49:06.000Z
import json from requests import Request from pydantic import BaseModel from pydoc import locate from typing import List, Optional import dataclasses from dataclasses import dataclass from datetime import datetime SCHEMAS = {} class ResourceBaseSchema(BaseModel): id: Optional[str] private: Optional[bool] canRead: Optional[List[str]] canWrite: Optional[List[str]] owner: Optional[str] anonymousComments: Optional[bool] comments: Optional[List[str]] createdAt: Optional[str] updatedAt: Optional[str] class Config: fields = {'id': '_id'} class ResourceInfo(BaseModel): resourceType: str resourceId: str class Comment(BaseModel): id: Optional[str] owner: Optional[str] comments: Optional[List[str]] text: Optional[str] flagged: Optional[bool] resource: Optional[ResourceInfo] otherResources: Optional[List[ResourceInfo]] closed: Optional[bool] assignedTo: Optional[List[str]] labels: Optional[List[str]] priority: Optional[str] status: Optional[str] view: Optional[dict] screenshot: Optional[str] class Config: fields = {'id': '_id'} def clean_empty(d): if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_empty(v) for v in d) if v is not None] return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v is not None} class ResourceBase(object): def __init__(self, session, basepath, me, name, methods): self.s = session self._path = basepath + '/' + name self.me = me self._comment_path = basepath + '/comments/' + name self.name = name self.methods = methods self.method_dict = { 'list': { 'method': 'GET', }, 'create': { 'method': 'POST', }, 'get': { 'method': 'GET', }, 'update': { 'method': 'PUT', }, 'delete': { 'method': 'DELETE', }, 'comment_get': { 'method': 'GET', }, 'comment_create': { 'method': 'POST'} } for method in self.methods: if method == 'retrieve': self.__setattr__('retrieve', 'x') self.schema = None self.comment_schema = Comment def _prep_request(self, method, path, comment, data, params): assert method in self.methods, 'method {} not supported for {} calls'.format(method, self.name) if comment: url = self._comment_path + path if data: dataclass_instance = self.comment_schema.parse_obj(data) data = clean_empty(dataclass_instance.dict(by_alias=True)) else: url = self._path + path if data: if isinstance(data, list): data_list = [] if self.schema: for d in data: if isinstance(d, dict): dataclass_instance = self.schema.parse_obj(d) data_list.append(clean_empty(dataclass_instance.dict(by_alias=True))) elif isinstance(d, str): data_list.append(d) data = data_list elif self.schema: if isinstance(data, dict): dataclass_instance = self.schema.parse_obj(data) else: dataclass_instance = data data = clean_empty(dataclass_instance.dict(by_alias=True)) return self.s.prepare_request(Request(self.method_dict[method]['method'], url, json=data, params=params)) def _parse_response(self, response, comment=False, schema=None): """Parse the request response Arguments: response {Response} -- A response from the server comment {bool} -- Whether or not the response is a comment schema {Schema} -- Optional schema to parse the response with Returns: Schema / dict -- An object derived from SpeckleObject if possible, otherwise a dict of the response resource """ if schema: # If a schema is defined, then try to parse it with that return schema.parse_obj(response) elif comment: return self.comment_schema.parse_obj(response) elif 'type' in response: # Otherwise, check if the incoming type is within the dict of loaded schemas types = response['type'].split('/') for t in reversed(types): if t in SCHEMAS: return SCHEMAS[t].parse_obj(response) if self.schema: return self.schema.parse_obj(response) return response def make_request(self, method, path, data=None, comment=False, schema=None, params=None): r = self._prep_request(method, path, comment, data, params) resp = self.s.send(r) resp.raise_for_status() response_payload = resp.json() assert response_payload['success'] == True, json.dumps(response_payload) if 'resources' in response_payload: return [self._parse_response(resource, comment, schema) for resource in response_payload['resources']] elif 'resource' in response_payload: return self._parse_response(response_payload['resource'], comment, schema) else: return response_payload # Not sure what to do in this scenario or when it might occur
34.873494
114
0.566592
5,283
0.912593
0
0
0
0
0
0
941
0.16255
3869c52e550ca9f86c4f7c28797a767ac345488b
2,002
py
Python
alieninvaders/explosion.py
yatesmac/Alien-Invaders
152fbe43256a80905881055490167d6fe1e3e996
[ "MIT" ]
null
null
null
alieninvaders/explosion.py
yatesmac/Alien-Invaders
152fbe43256a80905881055490167d6fe1e3e996
[ "MIT" ]
null
null
null
alieninvaders/explosion.py
yatesmac/Alien-Invaders
152fbe43256a80905881055490167d6fe1e3e996
[ "MIT" ]
null
null
null
"""This module handles the creation of an Explosion instance.""" from os import pardir, path import pygame as pg from pygame.sprite import Sprite import color # Path template for the nine explosion images. IMG = path.join(pardir, "resources/images/explosions/explosion0{}.jpg") class Explosion(Sprite): """A class to simulate an explosion in the event of a collision.""" def __init__(self, center): """Create an explosion object in the rect center of the alien that was shot.""" super().__init__() self.frame = 0 # Corresponds to each image in the simulation. self.last_update = pg.time.get_ticks() self.frame_rate = 75 # The list of images that simulate the explosion. self.explosion_sim = [] self._prep_images() self.image = self.explosion_sim[0] # Corresponds to images in the simulation. self.rect = self.image.get_rect() self.rect.center = center def _prep_images(self): """Load each explosion image, remove background and add to explosion list.""" for i in range(9): # There are nine images. image = pg.image.load(IMG.format(i)).convert() image = pg.transform.scale(image, (55, 55)) image.set_colorkey(color.BLACK) self.explosion_sim.append(image) def update(self): """Cycle through the explosion images.""" now = pg.time.get_ticks() if now - self.last_update > self.frame_rate: self.last_update = now self.frame += 1 # Remove the sprite when it has cycled through all images. if self.frame == len(self.explosion_sim): self.kill() else: # Display the current image at the mid-point of where the alien was. center = self.rect.center self.image = self.explosion_sim[self.frame] self.rect = self.image.get_rect() self.rect.center = center
37.773585
87
0.62038
1,717
0.857642
0
0
0
0
0
0
707
0.353147
3869ffe900c403550a635fd5893cce20c49720b4
298
py
Python
infra/controllers/errors/NotFoundError.py
JVGC/MyFinancesPython
5e4ac02ea00c4ddab688dd0093eed3f3fb2ad826
[ "MIT" ]
null
null
null
infra/controllers/errors/NotFoundError.py
JVGC/MyFinancesPython
5e4ac02ea00c4ddab688dd0093eed3f3fb2ad826
[ "MIT" ]
null
null
null
infra/controllers/errors/NotFoundError.py
JVGC/MyFinancesPython
5e4ac02ea00c4ddab688dd0093eed3f3fb2ad826
[ "MIT" ]
null
null
null
from infra.controllers.contracts import HttpResponse class NotFoundError(HttpResponse): def __init__(self, message) -> None: status_code = 404 self.message = message body = { 'message': self.message } super().__init__(body, status_code)
19.866667
52
0.620805
242
0.812081
0
0
0
0
0
0
9
0.030201
386af50e69b05e3ea517743c301c1934214c6742
696
py
Python
workout_plan_server/adapters/mysql/impl/mysql_exercise_repository.py
vitorsm/workout-plan-server
74e315550c11a1afd684d1497693ff16afc4f9d8
[ "MIT" ]
null
null
null
workout_plan_server/adapters/mysql/impl/mysql_exercise_repository.py
vitorsm/workout-plan-server
74e315550c11a1afd684d1497693ff16afc4f9d8
[ "MIT" ]
null
null
null
workout_plan_server/adapters/mysql/impl/mysql_exercise_repository.py
vitorsm/workout-plan-server
74e315550c11a1afd684d1497693ff16afc4f9d8
[ "MIT" ]
null
null
null
from uuid import uuid4 from flask_sqlalchemy import SQLAlchemy from workout_plan_server.adapters.mysql.generic_repository import GenericRepository from workout_plan_server.adapters.mysql.models.exercise_model import ExerciseModel from workout_plan_server.domain.entities.exercise import Exercise from workout_plan_server.services.ports.exercise_repository import ExerciseRepository class MySQLExerciseRepository(GenericRepository[ExerciseModel], ExerciseRepository): def get_mapper(self): return def __init__(self, db: SQLAlchemy): super().__init__(db, ExerciseModel) def merge_model_with_persisted_model(self, new_model: object) -> object: return None
33.142857
85
0.817529
309
0.443966
0
0
0
0
0
0
0
0
386c3f2f2a4ebdfce03d0405cda3d156ec665a3d
2,149
py
Python
mysite/test/testperform.py
Cary19900111/locust
fac972685485049fc7d568208c8976c500da4407
[ "MIT" ]
null
null
null
mysite/test/testperform.py
Cary19900111/locust
fac972685485049fc7d568208c8976c500da4407
[ "MIT" ]
null
null
null
mysite/test/testperform.py
Cary19900111/locust
fac972685485049fc7d568208c8976c500da4407
[ "MIT" ]
null
null
null
from locust import HttpLocust,TaskSet,task #python crlocust.py -f mysite/test/testperform.py --no-web --run-time 5s --csv result -c 5 -r 1 from locust import events from gevent._semaphore import Semaphore import datetime '''ๅ†™็š„้’ฉๅญๅ‡ฝๆ•ฐ''' # from locust import Locust, TaskSet, events, task # mars_event = events.EventHook() # def mars_special_event(verb = '', content = ''): # print("mars {} {}".format(verb,content)) # mars_event += mars_special_event # class UserTask(TaskSet): # def on_stop(self): # print("stop the Usertask!") # @task(1) # def job1(self): # mars_event.fire(verb = 'love', content = 'locust') # @task(3) # def job2(self): # print("In job2") # class User(Locust): # task_set = UserTask # min_wait = 1000 # max_wait = 3000 # stop_timeout = 10000 '''่ฎพ็ฝฎ้›†ๅˆ็‚นSemaphore''' all_locusts_spawned = Semaphore()#ไฟกๅท้‡๏ผŒ็ญ‰ๅพ…ๅ…จ้ƒจๅฏๅŠจๅฎŒๆฏ•๏ผˆhatch_complete๏ผ‰ๅŽ๏ผŒ้‡Šๆ”พreleaseไฟกๅท้‡ all_locusts_spawned.acquire() def on_hatch_complete(**kwargs): all_locusts_spawned.release() events.hatch_complete += on_hatch_complete def request_success_hook(request_type, name, response_time, response_length): with open ("CRRstSucess.txt",'a+') as f: now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") msg = "{} {} {} {} {} {}\n".format(now_time,"SUCCESS",request_type,name,response_time,response_length) f.write(msg) def request_failure_hook(request_type, name, response_time, exception): with open ("CRRstFail.txt",'a+') as f: now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") msg = "{} {} {} {} {} {}\n".format(now_time,"FAIL",request_type,name,response_time,exception) f.write(msg) events.request_success+=request_success_hook events.request_failure+=request_failure_hook class TestPerform(TaskSet): def on_start(self): all_locusts_spawned.wait() @task def smoke(self): response = self.client.get(url="/perform",name="ๆต‹่ฏ•",catch_response=False) class WebUser(HttpLocust): # task_set = [ShoutTask,DonwTask] host = "http://127.0.0.1:8000" task_set = TestPerform # stop_timeout=60
33.578125
115
0.674732
351
0.158322
0
0
112
0.050519
0
0
1,030
0.464592
386cca9eb1e6638f6f9a9784464bc329651f71b7
34
py
Python
src/hackeme/backend/hackvm/type_codes.py
ThomasBollmeier/hackeme-native
1bd9eac3eb057661045bcc1a612f8fc704f6d809
[ "Apache-2.0" ]
null
null
null
src/hackeme/backend/hackvm/type_codes.py
ThomasBollmeier/hackeme-native
1bd9eac3eb057661045bcc1a612f8fc704f6d809
[ "Apache-2.0" ]
null
null
null
src/hackeme/backend/hackvm/type_codes.py
ThomasBollmeier/hackeme-native
1bd9eac3eb057661045bcc1a612f8fc704f6d809
[ "Apache-2.0" ]
null
null
null
class TypeCodes: LIST = 1
11.333333
16
0.558824
34
1
0
0
0
0
0
0
0
0
386e17eb42b38c18cf7a39804e238de49e4f6116
4,248
py
Python
src/data_preprocess.py
Umasangavi/Thyroid_Disorder_Prediction
6ef2b0a3f52e945b78dd756067cae01478e078a9
[ "MIT" ]
null
null
null
src/data_preprocess.py
Umasangavi/Thyroid_Disorder_Prediction
6ef2b0a3f52e945b78dd756067cae01478e078a9
[ "MIT" ]
1
2022-01-21T08:19:10.000Z
2022-01-21T08:22:47.000Z
src/data_preprocess.py
Umasangavi/Thyroid_disorder_prediction
6ef2b0a3f52e945b78dd756067cae01478e078a9
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np import yaml import os import argparse from sklearn.impute import KNNImputer from logger import App_Logger file_object=open("application_logging/Loggings.txt", 'a+') logger_object=App_Logger() def read_params(config_path): with open(config_path) as yaml_file: config=yaml.safe_load(yaml_file) return config def preprocessing(config_path): config= read_params(config_path) train_data_path= config["split_data"]["train_path"] test_data_path= config["split_data"]["test_path"] train_processed_path= config["processed"]["train_path"] test_processed_path= config["processed"]["test_path"] """ Method Name: preprocessing Description: This method replacing the missing values with Nan values and perform the imputer to both train and test Output: A pandas DataFrame .csv. On Failure: Raise Exception """ logger_object.log(file_object,'Entered the preprocessing') try: train_data=pd.read_csv(train_data_path) test_data=pd.read_csv(test_data_path) # ? is replaced with np.nan in train data for column in train_data.columns: count = train_data[column][ train_data[column]=='?'].count() if count!=0: train_data[column] = train_data[column].replace('?',np.nan) train_data['sex'] = train_data ['sex'].replace({'F' : 0, 'M' : 1}) for column in train_data.columns: if len(train_data[column].unique())==2: train_data[column] = train_data[column].replace({'f' : 0, 't' : 1}) elif len(train_data[column].unique())==1: train_data[column] = train_data[column].replace({'f' : 0}) train_data['Class'] = train_data['Class'].replace({'negative' : 0, 'compensated_hypothyroid' : 1,'primary_hypothyroid' :2,'secondary_hypothyroid':3}) train_data["Class"] = train_data["Class"].apply(lambda value : 1 if value >=1 else 0) imputer=KNNImputer(n_neighbors=3, weights='uniform',missing_values=np.nan) new_array=imputer.fit_transform(train_data) train_impu_data=pd.DataFrame(data=np.round(new_array), columns=train_data.columns) train_impu_data.to_csv(train_processed_path,index=False) ############################################################################################################################################# # ? is replaced with np.nan in test data for column in test_data.columns: count = test_data[column][ test_data[column]=='?'].count() if count!=0: test_data[column] = test_data[column].replace('?',np.nan) test_data['sex'] = test_data['sex'].replace({'F' : 0, 'M' : 1}) for column in test_data.columns: if len(test_data[column].unique())==2: test_data[column] = test_data[column].replace({'f' : 0, 't' : 1}) elif len(test_data[column].unique())==1: test_data[column] = test_data[column].replace({'f' : 0}) test_data['Class'] = test_data['Class'].replace({'negative' : 0, 'compensated_hypothyroid' : 1,'primary_hypothyroid' :2,'secondary_hypothyroid':3}) test_data["Class"] = test_data["Class"].apply(lambda value : 1 if value >=1 else 0) imputer=KNNImputer(n_neighbors=3, weights='uniform',missing_values=np.nan) new_array=imputer.fit_transform(test_data) test_impu_data=pd.DataFrame(data=np.round(new_array), columns=test_data.columns) test_impu_data.to_csv(test_processed_path,index=False) logger_object.log(file_object,'preprocessing was done Successful and Exited') except Exception as e: logger_object.log(file_object,'Exception occured in preprocessing . Exception message: '+str(e)) logger_object.log(file_object,'preprocessing Unsuccessful') raise Exception() if __name__=="__main__": args = argparse.ArgumentParser() args.add_argument("--config", default="params.yaml") parsed_args = args.parse_args() data = preprocessing(config_path=parsed_args.config)
40.846154
158
0.626412
0
0
0
0
0
0
0
0
1,078
0.253766
3872a2d42f8cfe8870011a179ccbd8a81f44a9f5
680
py
Python
first_year/lmd/python_tests/induccion_suma_impares.py
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
first_year/lmd/python_tests/induccion_suma_impares.py
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
first_year/lmd/python_tests/induccion_suma_impares.py
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
# -*- encoding:utf-8 -*- impar = lambda n : 2 * n - 1 header = """ Demostrar que es cierto: 1 + 3 + 5 + ... + (2*n)-1 = n ^ 2 Luego con este programa se busca probar dicha afirmacion. """ def suma_impares(n): suma = 0 for i in range(1, n+1): suma += impar(i) return suma def main(): print(header) num = int(input('Numero: ')) suma = suma_impares(num) cuadrado = num ** 2 print('Suma de los ', num, ' primeros impares = ', suma) print('Cuadrado del numero: ', cuadrado) if suma == cuadrado: print('Son iguales, luego se cumple la afirmacion') else: print('No son iguales, luego no se cumple la afirmacion') if __name__ == '__main__': main()
16.190476
59
0.617647
0
0
0
0
0
0
0
0
327
0.480882
3872e9a2f5c1058e44e25d6f8294aa9843e070f9
341
py
Python
Items/Armors/Chest.py
saisua/RAF-Game
79b2b618aa18c31a40c080865b58fac02c1cac68
[ "MIT" ]
null
null
null
Items/Armors/Chest.py
saisua/RAF-Game
79b2b618aa18c31a40c080865b58fac02c1cac68
[ "MIT" ]
null
null
null
Items/Armors/Chest.py
saisua/RAF-Game
79b2b618aa18c31a40c080865b58fac02c1cac68
[ "MIT" ]
null
null
null
from .Armor import Armor class Chest(Armor): LIFE_PER_LEVEL = 100 PROTECTION_PER_LEVEL = 5 DAMAGE_PART = 1.2 def __init__(self, owner, level:int=None, life:int=None, protection:int=None): self.name = "Chest armor" super().__init__(owner, owner.level if level is None else level, life, protection)
26.230769
90
0.668622
305
0.894428
0
0
0
0
0
0
13
0.038123
3873964e8f758df7dc184439da0225ce4f856058
2,436
py
Python
api_v1/helpers.py
machariamarigi/shopping_list_api
79effc34145b25413f84ce02704281ccadf214ca
[ "MIT" ]
2
2018-08-18T12:53:49.000Z
2020-06-19T23:31:11.000Z
api_v1/helpers.py
machariamarigi/shopping_list_api
79effc34145b25413f84ce02704281ccadf214ca
[ "MIT" ]
21
2017-09-04T19:49:18.000Z
2017-12-19T09:07:39.000Z
api_v1/helpers.py
machariamarigi/shopping_list_api
79effc34145b25413f84ce02704281ccadf214ca
[ "MIT" ]
2
2017-09-15T18:43:02.000Z
2017-10-09T10:48:36.000Z
"""This module contains helper functions used in the API""" import datetime import json import re import string import random from functools import wraps from flask import request from api_v1.models import User def name_validalidation(name, context): """Function used to validate various names""" if len(name.strip()) == 0 or not re.match("^[-a-zA-Z0-9_\\s]*$", name): message = "Name shouldn't be empty. No special characters" response = { "message": message + " for " + context + " names", context: "null" } return response, 400 def email_validation(email): """Function used to validate users emails""" if not re.match(r"(^[a-zA-Z0-9_.]+@[a-zA-Z0-9-]+\.[a-z]+$)", email): response = { 'message': 'Incorrect email format.', 'status': 'Registration failed' } return response, 400 def datetimeconverter(obj): """Function to convert datime objects to a string""" if isinstance(obj, datetime.datetime): return obj.__str__() def master_serializer(resource): """Function to return a resource json""" data = resource.serialize() user_json = json.dumps( data, default=datetimeconverter, sort_keys=True ) return user_json def token_required(funct): """Decorator method to check for jwt tokens""" @wraps(funct) def wrapper(*args, **kwargs): """Wrapper function to add pass down results of the token decoding""" if 'Authorization' in request.headers: access_token = request.headers.get('Authorization') data = User.decode_token(access_token) if not isinstance(data, str): user_id = data else: response = { 'message': data } return response, 401 return funct(*args, user_id, **kwargs) else: message = "No token found! Ensure that the request header" response = { 'message': message + ' has an authorization key value' } return response, 401 wrapper.__doc__ = funct.__doc__ wrapper.__name__ = funct.__name__ return wrapper def password_generator(size=8, chars=string.ascii_uppercase + string.digits): """Function to generate a random password""" return ''.join(random.choice(chars) for _ in range(size))
29.707317
77
0.607964
0
0
0
0
779
0.319787
0
0
735
0.301724
38741faa71519d517184c3c53ce4e0416df5b8e0
25,099
py
Python
lib/phidias/Runtime.py
corradosantoro/hephaestus
c40a534e3979cef7e6eeda1206aa93e25fdd55a8
[ "MIT" ]
4
2019-06-07T08:57:15.000Z
2021-08-30T10:40:23.000Z
lib/phidias/Runtime.py
corradosantoro/hephaestus
c40a534e3979cef7e6eeda1206aa93e25fdd55a8
[ "MIT" ]
null
null
null
lib/phidias/Runtime.py
corradosantoro/hephaestus
c40a534e3979cef7e6eeda1206aa93e25fdd55a8
[ "MIT" ]
1
2020-07-24T14:16:34.000Z
2020-07-24T14:16:34.000Z
# # Runtime.py # import types import threading #import copy from phidias.Types import * from phidias.Knowledge import * from phidias.Exceptions import * from phidias.Messaging import * DEFAULT_AGENT = "main" __all__ = [ 'DEFAULT_AGENT', 'Runtime', 'Plan' ] # ------------------------------------------------ class EventQueue: def __init__(self): self.__c = threading.Condition() self.__data = [] self.__size = 0 self.__subscriptions = { } def subscribe(self, uEvt): self.__c.acquire() self.__subscriptions[uEvt.name()] = True self.__c.release() def unsubscribe(self, uEvt): self.__c.acquire() if uEvt.name() in self.__subscriptions: del self.__subscriptions[uEvt.name()] self.__c.release() # put the event at queue tail def put(self, uEvent): self.__c.acquire() if uEvent.name() in self.__subscriptions: self.__data.append(uEvent) self.__size += 1 self.__c.notify() self.__c.release() # put the event at queue head (so, this will be the first event to be dequeued) def put_top(self, uEvent): self.__c.acquire() if uEvent.name() in self.__subscriptions: self.__data.insert(0, uEvent) self.__size += 1 self.__c.notify() self.__c.release() def get(self, timeout = None): self.__c.acquire() while self.__size == 0: self.__c.wait(timeout) if self.__size == 0: self.__c.release() return None item = self.__data.pop(0) self.__size -= 1 self.__c.release() return item def wait_item(self): self.__c.acquire() while self.__size == 0: self.__c.wait() self.__c.release() def empty(self): self.__c.acquire() retval = self.__size == 0 self.__c.release() return retval def find_and_remove_event(self, uType, uBel): self.__c.acquire() for e in self.__data: #print("%d,%d - %s,%s" % (e.event_type, uType, repr(e.get_belief()), uBel)) if (e.event_type == uType)and(e.get_belief() == uBel): #print(type(e)) self.__data.remove(e) self.__size -= 1 self.__c.release() return True self.__c.release() return False # ------------------------------------------------ class Plan: def __init__(self, uEvent, uContextCondition = None, uActions = []): self.__event = uEvent self.__context_condition = uContextCondition self.__actions = uActions def context_condition(self): return self.__context_condition def event(self): return self.__event def actions(self): return self.__actions def __repr__(self): if self.__context_condition is None: return repr(self.__event) + " >> " + repr(self.__actions) else: return repr(self.__event) + \ " / " + repr(self.__context_condition) + " >> " + repr(self.__actions) def __rshift__(self, actionList): if isinstance(actionList, list): self.__actions = actionList else: raise NotAnActionListException() # ------------------------------------------------ class PlanBase: def __init__(self): self.__plans = {} def __repr__(self): return repr(self.__plans) def add_plan(self, p): name = p.event().name() if name in self.__plans: self.__plans[name].append(p) else: self.__plans[name] = [ p ] def get_plans_from_event(self, uEvt): name = uEvt.name() if name in self.__plans: return self.__plans[name] else: return [] def list_all_plans(self): all_plans = [ ] for b in self.__plans: for p in self.__plans[b]: all_plans.append(p) return all_plans # ------------------------------------------------ class Intention: INTENTION_NEXT = 0 INTENTION_END = 1 INTENTION_PROC = 2 def __init__(self, uEngine, uCtx, uPlan): self.__engine = uEngine self.__context = uCtx self.__action_list = uPlan.actions() self.__action_index = 0 self.__action_len = len(self.__action_list) self.__return_value = None self.__pending_assignment = None def get_return_value(self): return self.__return_value def execute_next(self, last_ret_value): if self.__action_index == self.__action_len: return (Intention.INTENTION_END, None) # end of execution if self.__pending_assignment is not None: self.__context[self.__pending_assignment] = last_ret_value a = self.__action_list[self.__action_index] self.__action_index += 1 from phidias.Types import Action, AddBeliefEvent, DeleteBeliefEvent, Procedure, Variable if isinstance(a, Action): ret_val = a.do_execute(self.__context) if a.assignment is not None: self.__context[a.assignment.name] = ret_val elif isinstance(a, AddBeliefEvent): # FIXME! Check if the event queue has already a analogous "-" event #copied_b = copy.deepcopy(a.get_belief()) copied_b = a.get_belief().clone() copied_b.assign(self.__context) if copied_b.dest is None: self.__engine.add_belief(copied_b) else: if isinstance(copied_b.dest, Variable): d = copied_b.dest.value else: d = copied_b.dest (remote_agent, a_name, site_name) = Messaging.local_or_remote(d) if remote_agent: Messaging.send_belief(a_name, site_name, copied_b, self.__engine.agent()) #print("Remote messaging to {}@{} is not supported".format(a_name,site_name)) else: e = Runtime.get_engine(d) #copied_b.dest) copied_b.source_agent = self.__engine.agent() e.add_belief(copied_b) elif isinstance(a, DeleteBeliefEvent): # FIXME! Check if the event queue has already a analogous "+" event #copied_b = copy.deepcopy(a.get_belief()) copied_b = a.get_belief().clone() copied_b.assign(self.__context) self.__engine.remove_belief(copied_b) elif isinstance(a, Procedure): if a.assignment is not None: self.__pending_assignment = a.assignment.name # get variable name #copied_a = copy.deepcopy(a) copied_a = a.clone() copied_a.assign(self.__context) return (Intention.INTENTION_PROC, copied_a) elif isinstance(a, str): exec(a, self.__context) elif isinstance(a, Variable): self.__return_value = self.__context[a.name] return (Intention.INTENTION_NEXT, None) # ------------------------------------------------ class WaitingPlansCollection: def __init__(self, uEngine): self.__plans_by_proc = { } self.__plans_by_event = { } self.__engine = uEngine def all(self): return (self.__plans_by_proc, self.__plans_by_event) def add(self, uProcedure, uCtxsPlans): n = uProcedure.name() if n in self.__plans_by_proc: print("plan " + n + " is already in waiting") raise InvalidPlanException() else: self.__plans_by_proc[n] = uCtxsPlans for (c, p) in uCtxsPlans: e = p.event().additional_event() if e is None: print("Procedure plan " + n + " has not the waiting event which is instead expected") raise InvalidPlanException() self.__engine.queue().subscribe(e) n1 = e.name() #print("activating event ", n1) if n1 in self.__plans_by_event: self.__plans_by_event[n1].append(p) else: self.__plans_by_event[n1] = [ p ] def remove(self, uCtxPlan): (ctx, plan) = uCtxPlan # first find the plan in __plans_by_proc n = plan.event().name() self.remove_by_name(n) def remove_by_name(self, n): if n in self.__plans_by_proc: plans_to_remove = self.__plans_by_proc[n] del self.__plans_by_proc[n] for (c, p) in plans_to_remove: e = p.event().additional_event() if e is not None: self.__engine.queue().unsubscribe(e) n1 = e.name() #print("removing event ", n1) if n1 in self.__plans_by_event: self.__plans_by_event[n1].remove(p) def get_plans_from_event(self, uEvt): name = uEvt.name() if name in self.__plans_by_event: return self.__plans_by_event[name] else: return [] # ------------------------------------------------ class SensorCollection(object): def __init__(self, uEngine): self.__engine = uEngine self.__sensors = { } def add_sensor(self, uSensor): self.__sensors[uSensor.__class__.__name__] = uSensor def get_sensor(self, uSensor): name = uSensor.__class__.__name__ if name in self.__sensors: return self.__sensors[name] else: return None def del_sensor(self, uSensor): name = uSensor.__class__.__name__ if name in self.__sensors: del self.__sensors[name] # ------------------------------------------------ class Engine: def __init__(self, uAgentName): self.__kb = Knowledge() self.__plans = PlanBase() self.__goals = PlanBase() self.__event_queue = EventQueue() self.__running = False self.__intentions = [ ] self.__sensors = SensorCollection(self) self.__waiting_plans = WaitingPlansCollection(self) self.__agent = uAgentName def add_sensor(self, uSensor): self.__sensors.add_sensor(uSensor) def get_sensor(self, uSensor): return self.__sensors.get_sensor(uSensor) def del_sensor(self, uSensor): self.__sensors.del_sensor(uSensor) def queue(self): return self.__event_queue def agent(self): return self.__agent def add_plan(self, p): self.__plans.add_plan(p) self.__event_queue.subscribe(p.event()) def add_goal(self, g): self.__goals.add_plan(g) def plans(self): return self.__plans def goals(self): return self.__goals def add_belief(self, uB): from phidias.Types import AddBeliefEvent, DATA_TYPE_REACTOR if uB.data_type != DATA_TYPE_REACTOR: r = self.__kb.add_belief(uB) else: r = True if r: self.__generate_event(AddBeliefEvent(uB)) return r def remove_belief(self, uB): from phidias.Types import DeleteBeliefEvent, DATA_TYPE_REACTOR if uB.data_type != DATA_TYPE_REACTOR: r = self.__kb.remove_belief(uB) else: r = False if r: self.__generate_event(DeleteBeliefEvent(uB)) return r def achieve(self, uG): self.__generate_event(uG) def achieve_goal(self, uG): return self.__plans_from_goal(uG) def knowledge(self): return self.__kb def stop(self): self.__running = False def waiting_plans(self): return self.__waiting_plans def __unify(self, uVars, uContext_condition): #contexts = [{}] contexts = [ uVars ] result = True #print(uContext_condition) from phidias.Types import Belief, ActiveBelief, Goal for t in uContext_condition.terms(): match_result = False #print(t, type(t)) if isinstance(t, Belief): matching_beliefs = self.__kb.get_matching_beliefs(t) #print (matching_beliefs) # "matching_beliefs" contains ground terms # "t" contains variables #print("Term: ", t, " ----> ", matching_beliefs) # here we are sure that "t" and elements in matching_beliefs # contains the same number of terms, moreover constants are # already matched, so we must only check variables new_contexts = [] for m in matching_beliefs: # each matching belief must be tested with each context for c in contexts: new = c.copy() #print (t, m, new) m.bind(new) if m.match(t): #print(new) new_contexts.append(new) match_result = True #print t, new_contexts contexts = new_contexts elif type(t) == types.LambdaType: new_contexts = [] _bin = globals()['__builtins__'] for c in contexts: for (key,val) in c.items(): _bin[key] = val #print(_bin) if t(): new_contexts.append(c) match_result = True for (key,val) in c.items(): del _bin[key] contexts = new_contexts elif isinstance(t, ActiveBelief): new_contexts = [] for c in contexts: if t.do_evaluate(c): new_contexts.append(c) match_result = True contexts = new_contexts elif isinstance(t, Goal): new_contexts = [] for c in contexts: #print(c, t) #copied_t = copy.deepcopy(t) copied_t = t.clone() copied_t.assign_partial(c) matching_plans = self.__plans_from_goal(copied_t)#, c) #print(copied_t, matching_plans) if matching_plans != []: for (ctx,p) in matching_plans: copied_t.assign_vars_from_formula(ctx,p.event()) for (key,val) in c.items(): ctx[key] = val new_contexts.append(ctx) #print(ctx, p.event()) match_result = True del copied_t contexts = new_contexts else: raise NotABeliefException() result = result and match_result #print(uContext_condition, contexts, result) return (result, contexts) # returns the plans matching the triggering event def __plans_from_triggering_event(self, uEvt, uPlanBase, uIsWaiting): selected_plans = [ ] event_belief = uEvt.get_belief() for p in uPlanBase: context = { } if uIsWaiting: b = p.event().additional_event().get_belief() else: b = p.event().get_belief() from phidias.Types import Variable, AddBeliefEvent if isinstance(uEvt, AddBeliefEvent): if isinstance(b.source, Variable): v = b.source v.value = event_belief.source_agent context[v.name] = event_belief.source_agent else: if b.source != event_belief.source_agent: continue event_belief.bind(context) if event_belief.match(b): selected_plans.append( (context, p) ) return selected_plans # returns the plans matching the procedure def __plans_from_procedure(self, uP): non_event_plans = [ ] event_plans = [ ] for p in self.__plans.get_plans_from_event(uP): context = { } b = p.event() uP.bind(context) if uP.match(b): if p.event().additional_event() is None: non_event_plans.append( (context, p) ) else: event_plans.append( (context, p) ) return (non_event_plans, event_plans) # returns the plans matching the goal def __plans_from_goal(self, uG, initial_context = {}): goal_plans = [ ] for p in self.__goals.get_plans_from_event(uG): context = initial_context.copy() b = p.event() uG.bind(context) if uG.prolog_match(b): ok, ctxs = self.__unify(context, p.context_condition()) if ok: for c in ctxs: goal_plans.append( (c, p) ) return goal_plans # verify the conditions on plans and returns valid plans def find_applicable_plans(self, plans): resulting_plans = [ ] for (ctx, plan) in plans: pred = plan.context_condition() if pred is None: resulting_plans.append( (ctx, plan) ) else: ok, ctxs = self.__unify(ctx, pred) if ok: resulting_plans.append( (ctxs[0], plan) ) return resulting_plans # verify the conditions on plans and returns first valid plan def find_first_applicable_plan(self, plans): for (ctx, plan) in plans: pred = plan.context_condition() if pred is None: return ( [ctx], plan) else: ok, ctxs = self.__unify(ctx, pred) if ok: #print(plan.event(), ctxs) return (ctxs, plan) return (None, None) # verify the conditions on plans and returns first and second valid plans def find_first_and_second_applicable_plans(self, plans): ret_plans = [ ] for (ctx, plan) in plans: pred = plan.context_condition() if pred is None: ret_plans.append( ([ctx], plan) ) else: ok, ctxs = self.__unify(ctx, pred) if ok: #print(plan.event(), ctxs) ret_plans.append ( (ctxs, plan) ) if len(ret_plans) == 2: break return ret_plans def make_intention(self, pctx): (context, plan) = pctx self.__intentions.insert( 0, Intention (self, context, plan) ) def run(self): self.__running = True self.__last_return_value = None # This is the main loop of the PHIDIAS interpreter while self.__running: evt = None # self.__intentions contains the intention stack, # as soon as the intention stack contains plans to be executed # events are not processed, so first we execute intentions while self.__intentions != [ ]: top_intention = self.__intentions[0] (whats_next, evt) = top_intention.execute_next(self.__last_return_value) if whats_next == Intention.INTENTION_END: # end of actions of intentions # retrieve return value v = top_intention.get_return_value() if v is not None: self.__last_return_value = v self.__intentions.pop(0) elif whats_next == Intention.INTENTION_PROC: break if evt is None: evt = self.__event_queue.get(0.5) #500millis if evt is None: continue #print(self.__agent, evt) from_waiting_plans_flag = False from phidias.Types import AddBeliefEvent, DeleteBeliefEvent, Procedure if isinstance(evt, AddBeliefEvent): b = evt.get_belief() # ok... here we must first check if there are waiting plans plans = self.__plans_from_triggering_event(evt, self.__waiting_plans.get_plans_from_event(evt), True) if plans == []: # no waiting plans, let's check "normal" plans plans = self.__plans_from_triggering_event(evt, self.__plans.get_plans_from_event(evt), False) else: from_waiting_plans_flag = True elif isinstance(evt, DeleteBeliefEvent): b = evt.get_belief() plans = self.__plans_from_triggering_event(evt, self.__plans.get_plans_from_event(evt), False) elif isinstance(evt, Procedure): if evt.event_type == Procedure.PROC_CANCEL: self.__waiting_plans.remove_by_name(evt.basename()) (non_event_plans, event_plans) = self.__plans_from_procedure(evt) # now check if plans have also a triggering event if (non_event_plans != [])and(event_plans != []): print("Event plans cannot be combined with non-event plans") raise InvalidPlanException() if event_plans != [ ]: # the plans relevant to the Procedure call have waiting events, # so we process them by adding to the waiting queue and skip execution self.__waiting_plans.add(evt, event_plans) continue else: plans = non_event_plans else: continue #plans = self.find_applicable_plans(plans) first_and_second_plans = self.find_first_and_second_applicable_plans(plans) if first_and_second_plans == [ ]: continue (ctxs, plan) = first_and_second_plans[0] plan_to_execute = (ctxs[0], plan) if len(ctxs) > 1: if plan.event().iterate: if len(first_and_second_plans) > 1: # push the second plan first self.make_intention(first_and_second_plans[1]) # push the first plan with all contexts in reverse ctxs.reverse() for c in ctxs: self.make_intention( (c, plan) ) if from_waiting_plans_flag: self.__waiting_plans.remove(plan_to_execute) continue # select first plan and execute it self.make_intention(plan_to_execute) if from_waiting_plans_flag: self.__waiting_plans.remove(plan_to_execute) def __generate_event(self, uEvt): from phidias.Types import AddDelBeliefEvent, AddBeliefEvent, DeleteBeliefEvent if isinstance(uEvt, AddBeliefEvent): if self.__event_queue.find_and_remove_event(AddDelBeliefEvent.DEL, uEvt.get_belief()): return if isinstance(uEvt, DeleteBeliefEvent): if self.__event_queue.find_and_remove_event(AddDelBeliefEvent.ADD, uEvt.get_belief()): return self.__event_queue.put(uEvt) # ------------------------------------------------ class Runtime: engines = { DEFAULT_AGENT : Engine(DEFAULT_AGENT) } currentAgent = DEFAULT_AGENT @classmethod def run_net(cls, _globals, protocol_type, *args, **kwargs): SUPPORTED_PROTOCOL_TYPES = { 'http': start_message_server_http, 'gateway': start_message_server_gateway } protocol_impl = SUPPORTED_PROTOCOL_TYPES[protocol_type] protocol_impl(Runtime.engines, _globals, *args, **kwargs) @classmethod def agent(cls, a): cls.currentAgent = a if not(cls.currentAgent in cls.engines): cls.engines[cls.currentAgent] = Engine(cls.currentAgent) @classmethod def add_plan(cls, p): cls.engines[cls.currentAgent].add_plan(p) @classmethod def add_goal(cls, p): cls.engines[cls.currentAgent].add_goal(p) @classmethod def run_agent(cls, a): e = cls.engines[a] t = threading.Thread(target = e.run) t.start() @classmethod def run_agents(cls): for ag in cls.engines: e = cls.engines[ag] t = threading.Thread(target = e.run) t.start() @classmethod def stop_agent(cls, a): e = cls.engines[a] e.stop() @classmethod def get_engine(cls, a): return cls.engines[a] @classmethod def agents(cls): return cls.engines.keys()
34.241473
117
0.543408
24,411
0.972589
0
0
1,224
0.048767
0
0
3,081
0.122754
3875c54506abd3c3f854187b77048a2fc7f1b45c
245
py
Python
validators.py
mk-rn/django_cash_register
f317d94dd50817160e883e2f452f7b8e824f4a1c
[ "MIT" ]
null
null
null
validators.py
mk-rn/django_cash_register
f317d94dd50817160e883e2f452f7b8e824f4a1c
[ "MIT" ]
null
null
null
validators.py
mk-rn/django_cash_register
f317d94dd50817160e883e2f452f7b8e824f4a1c
[ "MIT" ]
null
null
null
from django.core.exceptions import ValidationError def positive_number(value): """Checking the value. Must be greater than 0.""" if value <= 0.0: raise ValidationError('Count must be greater than 0', params={'value': value},)
27.222222
87
0.693878
0
0
0
0
0
0
0
0
86
0.35102
3875f7aa99170c1b5624a5092f12b0b84b4930ad
3,059
py
Python
others.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
others.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
others.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
import sensor, image, time, pyb from pid import PID from pyb import Servo from pyb import UART uart = UART(3, 19200) usb = pyb.USB_VCP() led_red = pyb.LED(1) # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4. led_green = pyb.LED(2) pan_pid = PID(p=0.07, i=0, imax=90) #่„ฑๆœบ่ฟ่กŒๆˆ–่€…็ฆ็”จๅ›พๅƒไผ ่พ“๏ผŒไฝฟ็”จ่ฟ™ไธชPID tilt_pid = PID(p=0.05, i=0, imax=90) #่„ฑๆœบ่ฟ่กŒๆˆ–่€…็ฆ็”จๅ›พๅƒไผ ่พ“๏ผŒไฝฟ็”จ่ฟ™ไธชPID #pan_pid = PID(p=0.1, i=0, imax=90)#ๅœจ็บฟ่ฐƒ่ฏ•ไฝฟ็”จ่ฟ™ไธชPID #tilt_pid = PID(p=0.1, i=0, imax=90)#ๅœจ็บฟ่ฐƒ่ฏ•ไฝฟ็”จ่ฟ™ไธชPID sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) import sensor, image, time, pyb from pid import PID from pyb import Servo from pyb import Pin usb = pyb.USB_VCP() pan_servo=Servo(1) tilt_servo=Servo(2) led_red = pyb.LED(1) # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4. led_green = pyb.LED(2) pan_pid = PID(p=0.07, i=0, imax=90) #่„ฑๆœบ่ฟ่กŒๆˆ–่€…็ฆ็”จๅ›พๅƒไผ ่พ“๏ผŒไฝฟ็”จ่ฟ™ไธชPID tilt_pid = PID(p=0.05, i=0, imax=90) #่„ฑๆœบ่ฟ่กŒๆˆ–่€…็ฆ็”จๅ›พๅƒไผ ่พ“๏ผŒไฝฟ็”จ่ฟ™ไธชPID #pan_pid = PID(p=0.1, i=0, imax=90)#ๅœจ็บฟ่ฐƒ่ฏ•ไฝฟ็”จ่ฟ™ไธชPID #tilt_pid = PID(p=0.1, i=0, imax=90)#ๅœจ็บฟ่ฐƒ่ฏ•ไฝฟ็”จ่ฟ™ไธชPID p_out = Pin('P7', Pin.OUT_PP)#่ฎพ็ฝฎp_outไธบ่พ“ๅ‡บๅผ•่„š sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) sensor.skip_frames(time = 2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking clock = time.clock() dete_red = 0 dete_green = 0 while(dete_green != 1 or dete_red != 1): clock.tick() img = sensor.snapshot().lens_corr(1.8) pan_servo.angle(pan_servo.angle()+2) print(pan_servo.angle()) #tilt_servo.angle(tilt_servo.angle()+2) #print(tilt_servo.angle()) for r in img.find_rects(threshold = 10000): # for p in r.corners(): img.draw_circle(p[0], p[1], 5, color = (0, 255, 0)) # print(r) area = (r.x(), r.y(), r.w(), r.h()) statistics = img.get_statistics(roi=area)#ๅƒ็ด ้ขœ่‰ฒ็ปŸ่ฎก # print(statistics) if 17<statistics.l_mode()<87 and 30<statistics.a_mode()<123 and -49<statistics.b_mode()<50 and dete_red == 0:#if the circle is red img.draw_rectangle(area, color = (255, 0, 0)) dete_red = 1 #่ฏ†ๅˆซๅˆฐ็š„็บข่‰ฒๅœ†ๅฝข็”จ็บข่‰ฒ็š„ๅœ†ๆก†ๅ‡บๆฅ print("red") uart.write("red") j = 3 while(j): p_out.high()#่ฎพ็ฝฎp_outๅผ•่„šไธบ้ซ˜ j=j-1 p_out.low() i = 5 while(i): led_red.on() time.sleep(1000) led_red.off() i=i-1 elif 24<statistics.l_mode()<48 and -48<statistics.a_mode()<-24 and -1<statistics.b_mode()<49 and dete_green == 0: img.draw_rectangle(area, color = (0, 255, 0)) dete_green = 1 print("green") uart.write("green") j = 3 while(j): p_out.high()#่ฎพ็ฝฎp_outๅผ•่„šไธบ้ซ˜ j=j-1 p_out.low() i = 5 while(i): led_green.on() time.sleep(1000) led_green.off() i=i-1 # print("FPS %f" % clock.fps())
31.536082
138
0.590062
0
0
0
0
0
0
0
0
1,056
0.316073
3877c817f150e95b91b3d8ee611f5c78f11d6109
4,121
py
Python
executiontime_calculator.py
baumartig/paperboy
01659cda235508eac66a50a9c16c4a6c531015bd
[ "Apache-2.0" ]
3
2015-02-26T06:39:40.000Z
2017-07-04T14:56:18.000Z
executiontime_calculator.py
baumartig/paperboy
01659cda235508eac66a50a9c16c4a6c531015bd
[ "Apache-2.0" ]
null
null
null
executiontime_calculator.py
baumartig/paperboy
01659cda235508eac66a50a9c16c4a6c531015bd
[ "Apache-2.0" ]
1
2018-02-21T00:12:06.000Z
2018-02-21T00:12:06.000Z
from datetime import datetime from datetime import timedelta from job import WEEKDAYS from job import Job def calculateNextExecution(job, now=datetime.now()): executionTime = now.replace() if job.executionType == "weekly": diff = WEEKDAYS.index(job.executionDay) - now.weekday() if diff < 0 and now.day < (-1 * diff): diff += now.day executionTime.replace(month=executionTime.month - 1) executionTime = executionTime.replace(day=now.day + diff) elif job.executionType == "monthly": executionTime = executionTime.replace(day=job.executionDay) # add the calculated difference executionTime = executionTime.replace(hour=job.executionTime.hour, minute=job.executionTime.minute, second=job.executionTime.second, microsecond=job.executionTime.microsecond) addition = timedelta() if now > executionTime: #add interval if job.executionType == "daily": addition = timedelta(days=1) if job.executionType == "weekly": addition = timedelta(weeks=1) elif job.executionType == "monthly": if executionTime.month < 12: executionTime = executionTime.replace(month=executionTime.month + 1) else: executionTime = executionTime.replace(month=1) # add the delta executionTime = executionTime + addition # set the next execution date on the job job.nextExecution = executionTime def test(): test_monthly() test_weekly() testDaily() return def test_monthly(): print "TEST Monthly" job = Job("testRef") now = datetime(2014, 2, 2, 10) # execute later addition = timedelta(hours=1) job.setExecution("monthly", (now + addition).time(), now.day) calculateNextExecution(job, now) assert datetime(2014, 2, 2, 11) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) # execute tomorrow addition = timedelta(hours=-1) job.setExecution("monthly", (now + addition).time(), now.day) calculateNextExecution(job, now) assert datetime(2014, 3, 2, 9) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) print "OK" def test_weekly(): print "TEST Weekly" job = Job("testRef") now = datetime(2014, 2, 2, 10) # execute later addition = timedelta(hours=1) job.setExecution("weekly", (now + addition).time(), "So") calculateNextExecution(job, now) assert datetime(2014, 2, 2, 11) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) # execute tomorrow addition = timedelta(hours=-1) job.setExecution("weekly", (now + addition).time(), "So") calculateNextExecution(job, now) assert datetime(2014, 2, 9, 9) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) print "OK" def testDaily(): print "TEST Daily" job = Job("testRef") now = datetime(2014, 2, 2, 10) # execute later addition = timedelta(hours=1) job.setExecution("daily", (now + addition).time()) calculateNextExecution(job, now) assert datetime(2014, 2, 2, 11) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) # execute tomorrow addition = timedelta(hours=-1) job.setExecution("daily", (now + addition).time()) calculateNextExecution(job, now) assert datetime(2014, 2, 3, 9) == job.nextExecution, "Calculated wrong execution date: %s"\ % str(job.nextExecution) print "OK" if __name__ == '__main__': test()
33.504065
100
0.580199
0
0
0
0
0
0
0
0
605
0.146809