body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
5b2e6ca4bad42ba6d909e275476222b77b358c67dd88f639419d0acc31d2884d | def hyperpar_optimization(self, init_points, n_iter, n_jobs, model_run_name, overwrite):
' Applies bayesian hyperparameter optimization for XGBoost parameters '
if (os.path.isfile((('models/' + model_run_name) + '_optimized_parameter.txt')) and (not overwrite)):
print('Model was already optimized. Choose different model_run_name or load previous optimization results')
else:
random.seed(42)
xgboost_opt = optimize_xgboost(self.x_train, self.y_train, init_points, n_iter, n_jobs)
with open((('models/' + model_run_name) + '_optimized_parameter.txt'), 'w') as json_file:
json.dump(xgboost_opt.max, json_file)
print((('Optimized model parameters are saved in models/' + model_run_name) + '_optimized_parameter.txt'))
hyperpar_opt_results = list()
for (i, iteration) in enumerate(xgboost_opt.res):
iteration_results_unformated = pd.DataFrame(iteration).transpose()
iteration_results = iteration_results_unformated.iloc[1]
iteration_results['RMSE'] = (- iteration_results_unformated.iloc[(0, 0)])
hyperpar_opt_results.append(iteration_results.to_dict())
pd.DataFrame(hyperpar_opt_results).to_csv((('models/' + model_run_name) + '_hyperpar_search.csv'))
print((('Fully hyperparameter search results are saved in models/' + model_run_name) + '_hyperpar_search.csv')) | Applies bayesian hyperparameter optimization for XGBoost parameters | src/models.py | hyperpar_optimization | MoritzFeigl/Learning-from-mistakes | 0 | python | def hyperpar_optimization(self, init_points, n_iter, n_jobs, model_run_name, overwrite):
' '
if (os.path.isfile((('models/' + model_run_name) + '_optimized_parameter.txt')) and (not overwrite)):
print('Model was already optimized. Choose different model_run_name or load previous optimization results')
else:
random.seed(42)
xgboost_opt = optimize_xgboost(self.x_train, self.y_train, init_points, n_iter, n_jobs)
with open((('models/' + model_run_name) + '_optimized_parameter.txt'), 'w') as json_file:
json.dump(xgboost_opt.max, json_file)
print((('Optimized model parameters are saved in models/' + model_run_name) + '_optimized_parameter.txt'))
hyperpar_opt_results = list()
for (i, iteration) in enumerate(xgboost_opt.res):
iteration_results_unformated = pd.DataFrame(iteration).transpose()
iteration_results = iteration_results_unformated.iloc[1]
iteration_results['RMSE'] = (- iteration_results_unformated.iloc[(0, 0)])
hyperpar_opt_results.append(iteration_results.to_dict())
pd.DataFrame(hyperpar_opt_results).to_csv((('models/' + model_run_name) + '_hyperpar_search.csv'))
print((('Fully hyperparameter search results are saved in models/' + model_run_name) + '_hyperpar_search.csv')) | def hyperpar_optimization(self, init_points, n_iter, n_jobs, model_run_name, overwrite):
' '
if (os.path.isfile((('models/' + model_run_name) + '_optimized_parameter.txt')) and (not overwrite)):
print('Model was already optimized. Choose different model_run_name or load previous optimization results')
else:
random.seed(42)
xgboost_opt = optimize_xgboost(self.x_train, self.y_train, init_points, n_iter, n_jobs)
with open((('models/' + model_run_name) + '_optimized_parameter.txt'), 'w') as json_file:
json.dump(xgboost_opt.max, json_file)
print((('Optimized model parameters are saved in models/' + model_run_name) + '_optimized_parameter.txt'))
hyperpar_opt_results = list()
for (i, iteration) in enumerate(xgboost_opt.res):
iteration_results_unformated = pd.DataFrame(iteration).transpose()
iteration_results = iteration_results_unformated.iloc[1]
iteration_results['RMSE'] = (- iteration_results_unformated.iloc[(0, 0)])
hyperpar_opt_results.append(iteration_results.to_dict())
pd.DataFrame(hyperpar_opt_results).to_csv((('models/' + model_run_name) + '_hyperpar_search.csv'))
print((('Fully hyperparameter search results are saved in models/' + model_run_name) + '_hyperpar_search.csv'))<|docstring|>Applies bayesian hyperparameter optimization for XGBoost parameters<|endoftext|> |
abc45f8d7deadfd6790ff7f52083adcbfbf14d42e6f0b59869fccffdc2d48b34 | def fit(self, model_run_name):
' Fit XGBoost model with previously derived optimal hyperparameters '
with open((('models/' + model_run_name) + '_optimized_parameter.txt')) as f:
optimized_parameters = json.load(f)
parameters = {'objective': 'reg:squarederror', 'n_estimators': int(optimized_parameters['params']['n_estimators']), 'learning_rate': optimized_parameters['params']['learning_rate'], 'max_depth': int(optimized_parameters['params']['max_depth']), 'gamma': optimized_parameters['params']['gamma'], 'min_child_weight': optimized_parameters['params']['min_child_weight'], 'max_delta_step': int(optimized_parameters['params']['max_delta_step']), 'subsample': optimized_parameters['params']['subsample'], 'colsample_bytree': optimized_parameters['params']['colsample_bytree'], 'scale_pos_weight': optimized_parameters['params']['scale_pos_weight'], 'reg_alpha': optimized_parameters['params']['reg_alpha'], 'reg_lambda': optimized_parameters['params']['reg_lambda']}
print('Optimized parameters:')
pprint.pprint(parameters)
self.model = XGBRegressor(**parameters)
random.seed(42)
self.model.fit(self.x_train, self.y_train)
prediction = self.model.predict(self.x_test)
self.test_rmse = np.sqrt(metrics.mean_squared_error(self.y_test, prediction))
print(('Optimized model RMSE in test set: %f' % self.test_rmse))
feature_important = self.model.get_booster().get_score(importance_type='gain')
keys = list(feature_important.keys())
values = list(feature_important.values())
feature_data = pd.DataFrame(data=values, index=keys, columns=['score']).sort_values(by='score', ascending=True)
sns.set(rc={'figure.figsize': (17, 6)})
feature_data.plot(kind='barh', title='XGBoost feature importance')
print('Saved XGBoost feature importance in results/figures/06_xgboost_feature_importance')
plt.savefig('results/figures/06_xgboost_feature_importance') | Fit XGBoost model with previously derived optimal hyperparameters | src/models.py | fit | MoritzFeigl/Learning-from-mistakes | 0 | python | def fit(self, model_run_name):
' '
with open((('models/' + model_run_name) + '_optimized_parameter.txt')) as f:
optimized_parameters = json.load(f)
parameters = {'objective': 'reg:squarederror', 'n_estimators': int(optimized_parameters['params']['n_estimators']), 'learning_rate': optimized_parameters['params']['learning_rate'], 'max_depth': int(optimized_parameters['params']['max_depth']), 'gamma': optimized_parameters['params']['gamma'], 'min_child_weight': optimized_parameters['params']['min_child_weight'], 'max_delta_step': int(optimized_parameters['params']['max_delta_step']), 'subsample': optimized_parameters['params']['subsample'], 'colsample_bytree': optimized_parameters['params']['colsample_bytree'], 'scale_pos_weight': optimized_parameters['params']['scale_pos_weight'], 'reg_alpha': optimized_parameters['params']['reg_alpha'], 'reg_lambda': optimized_parameters['params']['reg_lambda']}
print('Optimized parameters:')
pprint.pprint(parameters)
self.model = XGBRegressor(**parameters)
random.seed(42)
self.model.fit(self.x_train, self.y_train)
prediction = self.model.predict(self.x_test)
self.test_rmse = np.sqrt(metrics.mean_squared_error(self.y_test, prediction))
print(('Optimized model RMSE in test set: %f' % self.test_rmse))
feature_important = self.model.get_booster().get_score(importance_type='gain')
keys = list(feature_important.keys())
values = list(feature_important.values())
feature_data = pd.DataFrame(data=values, index=keys, columns=['score']).sort_values(by='score', ascending=True)
sns.set(rc={'figure.figsize': (17, 6)})
feature_data.plot(kind='barh', title='XGBoost feature importance')
print('Saved XGBoost feature importance in results/figures/06_xgboost_feature_importance')
plt.savefig('results/figures/06_xgboost_feature_importance') | def fit(self, model_run_name):
' '
with open((('models/' + model_run_name) + '_optimized_parameter.txt')) as f:
optimized_parameters = json.load(f)
parameters = {'objective': 'reg:squarederror', 'n_estimators': int(optimized_parameters['params']['n_estimators']), 'learning_rate': optimized_parameters['params']['learning_rate'], 'max_depth': int(optimized_parameters['params']['max_depth']), 'gamma': optimized_parameters['params']['gamma'], 'min_child_weight': optimized_parameters['params']['min_child_weight'], 'max_delta_step': int(optimized_parameters['params']['max_delta_step']), 'subsample': optimized_parameters['params']['subsample'], 'colsample_bytree': optimized_parameters['params']['colsample_bytree'], 'scale_pos_weight': optimized_parameters['params']['scale_pos_weight'], 'reg_alpha': optimized_parameters['params']['reg_alpha'], 'reg_lambda': optimized_parameters['params']['reg_lambda']}
print('Optimized parameters:')
pprint.pprint(parameters)
self.model = XGBRegressor(**parameters)
random.seed(42)
self.model.fit(self.x_train, self.y_train)
prediction = self.model.predict(self.x_test)
self.test_rmse = np.sqrt(metrics.mean_squared_error(self.y_test, prediction))
print(('Optimized model RMSE in test set: %f' % self.test_rmse))
feature_important = self.model.get_booster().get_score(importance_type='gain')
keys = list(feature_important.keys())
values = list(feature_important.values())
feature_data = pd.DataFrame(data=values, index=keys, columns=['score']).sort_values(by='score', ascending=True)
sns.set(rc={'figure.figsize': (17, 6)})
feature_data.plot(kind='barh', title='XGBoost feature importance')
print('Saved XGBoost feature importance in results/figures/06_xgboost_feature_importance')
plt.savefig('results/figures/06_xgboost_feature_importance')<|docstring|>Fit XGBoost model with previously derived optimal hyperparameters<|endoftext|> |
b2e156a2a2637813373ba2be8c9862ad93818f428a7162d2f206f52e8f84be22 | def compute_shap_values(self, loadings: pd.DataFrame):
'SHAP and PCA SHAP value computations\n\n Method to compute SHAP and PCA SHAP values for the given XGBoost model.\n\n Parameters\n ----------\n loadings: pd.DataFrame\n Data frame with PCA loadings used to compute PCA SHAP values.\n '
explainer = shap.Explainer(self.model)
shap_array = explainer.shap_values(self.x)
self.shap_values = pd.DataFrame(shap_array)
self.shap_values.columns = self.x.columns
self.shap_values.index = self.data.index
aggregated_shap_loadings = pd.DataFrame(0, index=self.shap_values.index, columns=loadings.index)
for pca_col in self.shap_values.columns:
col_shap = self.shap_values[pca_col]
col_loading = loadings[pca_col]
shap_loadings = []
for (i, loading) in enumerate(col_loading):
shap_loadings.append((col_shap * loading))
shap_loadings = pd.concat(shap_loadings, axis=1)
shap_loadings.columns = col_loading.index
aggregated_shap_loadings = aggregated_shap_loadings.add(shap_loadings, fill_value=0)
var_names = list(map((lambda v: re.split('_', v)[0]), self.model_variables))
lag_variables = [x for x in var_names if (x not in ['sin', 'cos'])]
self.model_variables_clean = list(map((lambda v: re.split(' \\(', v)[0]), lag_variables))
nlags = len(aggregated_shap_loadings.filter(regex=(self.model_variables_clean[0] + '*')).columns)
self.aggregated_shap_values = pd.DataFrame({'hour': ((aggregated_shap_loadings[['sin_hour', 'cos_hour']].sum(axis=1) * nlags) / 2)})
for variable in self.model_variables_clean:
self.aggregated_shap_values[variable] = aggregated_shap_loadings.filter(regex=(variable + '*')).sum(axis=1) | SHAP and PCA SHAP value computations
Method to compute SHAP and PCA SHAP values for the given XGBoost model.
Parameters
----------
loadings: pd.DataFrame
Data frame with PCA loadings used to compute PCA SHAP values. | src/models.py | compute_shap_values | MoritzFeigl/Learning-from-mistakes | 0 | python | def compute_shap_values(self, loadings: pd.DataFrame):
'SHAP and PCA SHAP value computations\n\n Method to compute SHAP and PCA SHAP values for the given XGBoost model.\n\n Parameters\n ----------\n loadings: pd.DataFrame\n Data frame with PCA loadings used to compute PCA SHAP values.\n '
explainer = shap.Explainer(self.model)
shap_array = explainer.shap_values(self.x)
self.shap_values = pd.DataFrame(shap_array)
self.shap_values.columns = self.x.columns
self.shap_values.index = self.data.index
aggregated_shap_loadings = pd.DataFrame(0, index=self.shap_values.index, columns=loadings.index)
for pca_col in self.shap_values.columns:
col_shap = self.shap_values[pca_col]
col_loading = loadings[pca_col]
shap_loadings = []
for (i, loading) in enumerate(col_loading):
shap_loadings.append((col_shap * loading))
shap_loadings = pd.concat(shap_loadings, axis=1)
shap_loadings.columns = col_loading.index
aggregated_shap_loadings = aggregated_shap_loadings.add(shap_loadings, fill_value=0)
var_names = list(map((lambda v: re.split('_', v)[0]), self.model_variables))
lag_variables = [x for x in var_names if (x not in ['sin', 'cos'])]
self.model_variables_clean = list(map((lambda v: re.split(' \\(', v)[0]), lag_variables))
nlags = len(aggregated_shap_loadings.filter(regex=(self.model_variables_clean[0] + '*')).columns)
self.aggregated_shap_values = pd.DataFrame({'hour': ((aggregated_shap_loadings[['sin_hour', 'cos_hour']].sum(axis=1) * nlags) / 2)})
for variable in self.model_variables_clean:
self.aggregated_shap_values[variable] = aggregated_shap_loadings.filter(regex=(variable + '*')).sum(axis=1) | def compute_shap_values(self, loadings: pd.DataFrame):
'SHAP and PCA SHAP value computations\n\n Method to compute SHAP and PCA SHAP values for the given XGBoost model.\n\n Parameters\n ----------\n loadings: pd.DataFrame\n Data frame with PCA loadings used to compute PCA SHAP values.\n '
explainer = shap.Explainer(self.model)
shap_array = explainer.shap_values(self.x)
self.shap_values = pd.DataFrame(shap_array)
self.shap_values.columns = self.x.columns
self.shap_values.index = self.data.index
aggregated_shap_loadings = pd.DataFrame(0, index=self.shap_values.index, columns=loadings.index)
for pca_col in self.shap_values.columns:
col_shap = self.shap_values[pca_col]
col_loading = loadings[pca_col]
shap_loadings = []
for (i, loading) in enumerate(col_loading):
shap_loadings.append((col_shap * loading))
shap_loadings = pd.concat(shap_loadings, axis=1)
shap_loadings.columns = col_loading.index
aggregated_shap_loadings = aggregated_shap_loadings.add(shap_loadings, fill_value=0)
var_names = list(map((lambda v: re.split('_', v)[0]), self.model_variables))
lag_variables = [x for x in var_names if (x not in ['sin', 'cos'])]
self.model_variables_clean = list(map((lambda v: re.split(' \\(', v)[0]), lag_variables))
nlags = len(aggregated_shap_loadings.filter(regex=(self.model_variables_clean[0] + '*')).columns)
self.aggregated_shap_values = pd.DataFrame({'hour': ((aggregated_shap_loadings[['sin_hour', 'cos_hour']].sum(axis=1) * nlags) / 2)})
for variable in self.model_variables_clean:
self.aggregated_shap_values[variable] = aggregated_shap_loadings.filter(regex=(variable + '*')).sum(axis=1)<|docstring|>SHAP and PCA SHAP value computations
Method to compute SHAP and PCA SHAP values for the given XGBoost model.
Parameters
----------
loadings: pd.DataFrame
Data frame with PCA loadings used to compute PCA SHAP values.<|endoftext|> |
ccbe6f18b8bcc998b4a9d672c36beeb4e407761897bee537923225e91ca4ce9a | def cluster_shap_values(self, chosen_algorithm: str, chosen_n_cluster: int, max_clusters: int=10, min_clusters: int=3, kmeans_seed: int=10):
' Cluster PCA SHAP values\n\n Method to Cluster the PCA SHAP values of the model with three type of clustering algorithms. The\n "chosen_algorithm" and "chosen_n_cluster" are the final values that will be stored in the model class.\n\n Parameters\n ----------\n chosen_algorithm: str\n Chosen cluster algorithm. Can be one of the following: "kmean", "hierarchical_ward", "hierarchical_complete"\n chosen_n_cluster: int\n Chosen number of clusters.\n max_clusters: int\n Maximum number of clusters that will be used for all clustering algorithms.\n min_clusters: int\n Minimum number of clusters that will be used for all clustering algorithms.\n kmeans_seed: int\n Random seed used for kmeans.\n '
range_n_clusters = range(min_clusters, (max_clusters + 1))
silhouette_scores = {'kmean': dict(), 'hierarchical_ward': dict(), 'hierarchical_complete': dict()}
print('Cluster results for number of clusters in 3-10 are saved under results/figures/07_clusterinf')
for n_clusters in range_n_clusters:
cluster_algorithms = [['kmean', KMeans(n_clusters=n_clusters, random_state=kmeans_seed, n_init=20)], ['hierarchical_ward', AgglomerativeClustering(n_clusters=n_clusters)], ['hierarchical_complete', AgglomerativeClustering(n_clusters=n_clusters, linkage='complete')]]
for cluster_alg in cluster_algorithms:
(fig, (ax1, ax2)) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
ax1.set_xlim([(- 0.1), 1])
ax1.set_ylim([0, (len(self.shap_values) + ((n_clusters + 1) * 10))])
clusterer = cluster_alg[1]
cluster_labels = clusterer.fit_predict(self.shap_values)
silhouette_avg = silhouette_score(self.shap_values, cluster_labels)
print('For n_clusters =', n_clusters, cluster_alg[0], 'The average silhouette_score is :', round(silhouette_avg, 3))
silhouette_scores[cluster_alg[0]][n_clusters] = silhouette_avg
sample_silhouette_values = silhouette_samples(self.shap_values, cluster_labels)
pca = PCA(n_components=2, svd_solver='full')
pca.fit(self.shap_values)
pca_X = pca.transform(self.shap_values)
y_lower = 10
colors = plt.cm.get_cmap('Set1', n_clusters)
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[(cluster_labels == i)]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = (y_lower + size_cluster_i)
color = tuple(colors.colors[i])
ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7)
ax1.text((- 0.05), (y_lower + (0.5 * size_cluster_i)), str((i + 1)))
y_lower = (y_upper + 10)
ax1.set_title('Silhouette plot')
ax1.set_xlabel('Silhouette coefficient values')
ax1.set_ylabel('Cluster')
ax1.axvline(x=silhouette_avg, color='red', linestyle='--')
ax1.set_yticks([])
ax1.set_xticks([(- 0.1), 0, 0.2, 0.4, 0.6, 0.8, 1])
color_array = np.array(list(map(tuple, colors.colors)))
point_col_array = np.empty(shape=(cluster_labels.shape[0], 4))
for row in range(cluster_labels.shape[0]):
point_col_array[(row, :)] = color_array[cluster_labels[row]]
ax2.scatter(pca_X[(:, 0)], pca_X[(:, 1)], marker='.', s=30, lw=0, alpha=0.7, c=point_col_array, edgecolor='k')
ax2.set_title('Clusters shown in Principal components of data')
ax2.set_xlabel(f'1st Principal Component ({(100 * pca.explained_variance_ratio_[0]):.3}%)')
ax2.set_ylabel(f'2st Principal Component ({(100 * pca.explained_variance_ratio_[1]):.3}%)')
plt.suptitle(f'Silhouette analysis for {cluster_alg[0]} clustering with {n_clusters} clusters', fontsize=14, fontweight='bold')
os.makedirs('results/figures/07_clustering', exist_ok=True)
plt.savefig(f'results/figures/07_clustering/cluster_shillouette_{cluster_alg[0]}_ncluster_{n_clusters}', dpi=600, bbox_inches='tight')
plt.close()
cluster_algorithms_ = [KMeans(n_clusters=chosen_n_cluster, random_state=kmeans_seed), AgglomerativeClustering(n_clusters=chosen_n_cluster), AgglomerativeClustering(n_clusters=chosen_n_cluster, linkage='complete')]
cluster_algorithms_names = ['kmean', 'hierarchical_ward', 'hierarchical_complete']
cluster_alg_id = cluster_algorithms_names.index(chosen_algorithm)
self.optimal_n_clusters = chosen_n_cluster
self.cluster_model = cluster_algorithms_[cluster_alg_id]
self.cluster_labels = self.cluster_model.fit_predict(self.shap_values)
print(f'Estimated clusters with {chosen_algorithm} with {self.optimal_n_clusters} clusters.') | Cluster PCA SHAP values
Method to Cluster the PCA SHAP values of the model with three type of clustering algorithms. The
"chosen_algorithm" and "chosen_n_cluster" are the final values that will be stored in the model class.
Parameters
----------
chosen_algorithm: str
Chosen cluster algorithm. Can be one of the following: "kmean", "hierarchical_ward", "hierarchical_complete"
chosen_n_cluster: int
Chosen number of clusters.
max_clusters: int
Maximum number of clusters that will be used for all clustering algorithms.
min_clusters: int
Minimum number of clusters that will be used for all clustering algorithms.
kmeans_seed: int
Random seed used for kmeans. | src/models.py | cluster_shap_values | MoritzFeigl/Learning-from-mistakes | 0 | python | def cluster_shap_values(self, chosen_algorithm: str, chosen_n_cluster: int, max_clusters: int=10, min_clusters: int=3, kmeans_seed: int=10):
' Cluster PCA SHAP values\n\n Method to Cluster the PCA SHAP values of the model with three type of clustering algorithms. The\n "chosen_algorithm" and "chosen_n_cluster" are the final values that will be stored in the model class.\n\n Parameters\n ----------\n chosen_algorithm: str\n Chosen cluster algorithm. Can be one of the following: "kmean", "hierarchical_ward", "hierarchical_complete"\n chosen_n_cluster: int\n Chosen number of clusters.\n max_clusters: int\n Maximum number of clusters that will be used for all clustering algorithms.\n min_clusters: int\n Minimum number of clusters that will be used for all clustering algorithms.\n kmeans_seed: int\n Random seed used for kmeans.\n '
range_n_clusters = range(min_clusters, (max_clusters + 1))
silhouette_scores = {'kmean': dict(), 'hierarchical_ward': dict(), 'hierarchical_complete': dict()}
print('Cluster results for number of clusters in 3-10 are saved under results/figures/07_clusterinf')
for n_clusters in range_n_clusters:
cluster_algorithms = [['kmean', KMeans(n_clusters=n_clusters, random_state=kmeans_seed, n_init=20)], ['hierarchical_ward', AgglomerativeClustering(n_clusters=n_clusters)], ['hierarchical_complete', AgglomerativeClustering(n_clusters=n_clusters, linkage='complete')]]
for cluster_alg in cluster_algorithms:
(fig, (ax1, ax2)) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
ax1.set_xlim([(- 0.1), 1])
ax1.set_ylim([0, (len(self.shap_values) + ((n_clusters + 1) * 10))])
clusterer = cluster_alg[1]
cluster_labels = clusterer.fit_predict(self.shap_values)
silhouette_avg = silhouette_score(self.shap_values, cluster_labels)
print('For n_clusters =', n_clusters, cluster_alg[0], 'The average silhouette_score is :', round(silhouette_avg, 3))
silhouette_scores[cluster_alg[0]][n_clusters] = silhouette_avg
sample_silhouette_values = silhouette_samples(self.shap_values, cluster_labels)
pca = PCA(n_components=2, svd_solver='full')
pca.fit(self.shap_values)
pca_X = pca.transform(self.shap_values)
y_lower = 10
colors = plt.cm.get_cmap('Set1', n_clusters)
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[(cluster_labels == i)]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = (y_lower + size_cluster_i)
color = tuple(colors.colors[i])
ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7)
ax1.text((- 0.05), (y_lower + (0.5 * size_cluster_i)), str((i + 1)))
y_lower = (y_upper + 10)
ax1.set_title('Silhouette plot')
ax1.set_xlabel('Silhouette coefficient values')
ax1.set_ylabel('Cluster')
ax1.axvline(x=silhouette_avg, color='red', linestyle='--')
ax1.set_yticks([])
ax1.set_xticks([(- 0.1), 0, 0.2, 0.4, 0.6, 0.8, 1])
color_array = np.array(list(map(tuple, colors.colors)))
point_col_array = np.empty(shape=(cluster_labels.shape[0], 4))
for row in range(cluster_labels.shape[0]):
point_col_array[(row, :)] = color_array[cluster_labels[row]]
ax2.scatter(pca_X[(:, 0)], pca_X[(:, 1)], marker='.', s=30, lw=0, alpha=0.7, c=point_col_array, edgecolor='k')
ax2.set_title('Clusters shown in Principal components of data')
ax2.set_xlabel(f'1st Principal Component ({(100 * pca.explained_variance_ratio_[0]):.3}%)')
ax2.set_ylabel(f'2st Principal Component ({(100 * pca.explained_variance_ratio_[1]):.3}%)')
plt.suptitle(f'Silhouette analysis for {cluster_alg[0]} clustering with {n_clusters} clusters', fontsize=14, fontweight='bold')
os.makedirs('results/figures/07_clustering', exist_ok=True)
plt.savefig(f'results/figures/07_clustering/cluster_shillouette_{cluster_alg[0]}_ncluster_{n_clusters}', dpi=600, bbox_inches='tight')
plt.close()
cluster_algorithms_ = [KMeans(n_clusters=chosen_n_cluster, random_state=kmeans_seed), AgglomerativeClustering(n_clusters=chosen_n_cluster), AgglomerativeClustering(n_clusters=chosen_n_cluster, linkage='complete')]
cluster_algorithms_names = ['kmean', 'hierarchical_ward', 'hierarchical_complete']
cluster_alg_id = cluster_algorithms_names.index(chosen_algorithm)
self.optimal_n_clusters = chosen_n_cluster
self.cluster_model = cluster_algorithms_[cluster_alg_id]
self.cluster_labels = self.cluster_model.fit_predict(self.shap_values)
print(f'Estimated clusters with {chosen_algorithm} with {self.optimal_n_clusters} clusters.') | def cluster_shap_values(self, chosen_algorithm: str, chosen_n_cluster: int, max_clusters: int=10, min_clusters: int=3, kmeans_seed: int=10):
' Cluster PCA SHAP values\n\n Method to Cluster the PCA SHAP values of the model with three type of clustering algorithms. The\n "chosen_algorithm" and "chosen_n_cluster" are the final values that will be stored in the model class.\n\n Parameters\n ----------\n chosen_algorithm: str\n Chosen cluster algorithm. Can be one of the following: "kmean", "hierarchical_ward", "hierarchical_complete"\n chosen_n_cluster: int\n Chosen number of clusters.\n max_clusters: int\n Maximum number of clusters that will be used for all clustering algorithms.\n min_clusters: int\n Minimum number of clusters that will be used for all clustering algorithms.\n kmeans_seed: int\n Random seed used for kmeans.\n '
range_n_clusters = range(min_clusters, (max_clusters + 1))
silhouette_scores = {'kmean': dict(), 'hierarchical_ward': dict(), 'hierarchical_complete': dict()}
print('Cluster results for number of clusters in 3-10 are saved under results/figures/07_clusterinf')
for n_clusters in range_n_clusters:
cluster_algorithms = [['kmean', KMeans(n_clusters=n_clusters, random_state=kmeans_seed, n_init=20)], ['hierarchical_ward', AgglomerativeClustering(n_clusters=n_clusters)], ['hierarchical_complete', AgglomerativeClustering(n_clusters=n_clusters, linkage='complete')]]
for cluster_alg in cluster_algorithms:
(fig, (ax1, ax2)) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
ax1.set_xlim([(- 0.1), 1])
ax1.set_ylim([0, (len(self.shap_values) + ((n_clusters + 1) * 10))])
clusterer = cluster_alg[1]
cluster_labels = clusterer.fit_predict(self.shap_values)
silhouette_avg = silhouette_score(self.shap_values, cluster_labels)
print('For n_clusters =', n_clusters, cluster_alg[0], 'The average silhouette_score is :', round(silhouette_avg, 3))
silhouette_scores[cluster_alg[0]][n_clusters] = silhouette_avg
sample_silhouette_values = silhouette_samples(self.shap_values, cluster_labels)
pca = PCA(n_components=2, svd_solver='full')
pca.fit(self.shap_values)
pca_X = pca.transform(self.shap_values)
y_lower = 10
colors = plt.cm.get_cmap('Set1', n_clusters)
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[(cluster_labels == i)]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = (y_lower + size_cluster_i)
color = tuple(colors.colors[i])
ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7)
ax1.text((- 0.05), (y_lower + (0.5 * size_cluster_i)), str((i + 1)))
y_lower = (y_upper + 10)
ax1.set_title('Silhouette plot')
ax1.set_xlabel('Silhouette coefficient values')
ax1.set_ylabel('Cluster')
ax1.axvline(x=silhouette_avg, color='red', linestyle='--')
ax1.set_yticks([])
ax1.set_xticks([(- 0.1), 0, 0.2, 0.4, 0.6, 0.8, 1])
color_array = np.array(list(map(tuple, colors.colors)))
point_col_array = np.empty(shape=(cluster_labels.shape[0], 4))
for row in range(cluster_labels.shape[0]):
point_col_array[(row, :)] = color_array[cluster_labels[row]]
ax2.scatter(pca_X[(:, 0)], pca_X[(:, 1)], marker='.', s=30, lw=0, alpha=0.7, c=point_col_array, edgecolor='k')
ax2.set_title('Clusters shown in Principal components of data')
ax2.set_xlabel(f'1st Principal Component ({(100 * pca.explained_variance_ratio_[0]):.3}%)')
ax2.set_ylabel(f'2st Principal Component ({(100 * pca.explained_variance_ratio_[1]):.3}%)')
plt.suptitle(f'Silhouette analysis for {cluster_alg[0]} clustering with {n_clusters} clusters', fontsize=14, fontweight='bold')
os.makedirs('results/figures/07_clustering', exist_ok=True)
plt.savefig(f'results/figures/07_clustering/cluster_shillouette_{cluster_alg[0]}_ncluster_{n_clusters}', dpi=600, bbox_inches='tight')
plt.close()
cluster_algorithms_ = [KMeans(n_clusters=chosen_n_cluster, random_state=kmeans_seed), AgglomerativeClustering(n_clusters=chosen_n_cluster), AgglomerativeClustering(n_clusters=chosen_n_cluster, linkage='complete')]
cluster_algorithms_names = ['kmean', 'hierarchical_ward', 'hierarchical_complete']
cluster_alg_id = cluster_algorithms_names.index(chosen_algorithm)
self.optimal_n_clusters = chosen_n_cluster
self.cluster_model = cluster_algorithms_[cluster_alg_id]
self.cluster_labels = self.cluster_model.fit_predict(self.shap_values)
print(f'Estimated clusters with {chosen_algorithm} with {self.optimal_n_clusters} clusters.')<|docstring|>Cluster PCA SHAP values
Method to Cluster the PCA SHAP values of the model with three type of clustering algorithms. The
"chosen_algorithm" and "chosen_n_cluster" are the final values that will be stored in the model class.
Parameters
----------
chosen_algorithm: str
Chosen cluster algorithm. Can be one of the following: "kmean", "hierarchical_ward", "hierarchical_complete"
chosen_n_cluster: int
Chosen number of clusters.
max_clusters: int
Maximum number of clusters that will be used for all clustering algorithms.
min_clusters: int
Minimum number of clusters that will be used for all clustering algorithms.
kmeans_seed: int
Random seed used for kmeans.<|endoftext|> |
af2688808fec7bd169d45fde51d4bec5fef94c2aa45f4a6166efd253f7d76da6 | def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, valueBoolean: Optional[FhirBoolean]=None, valueDecimal: Optional[FhirDecimal]=None, valueInteger: Optional[FhirInteger]=None, valueDate: Optional[FhirDate]=None, valueDateTime: Optional[FhirDateTime]=None, valueTime: Optional[FhirTime]=None, valueString: Optional[FhirString]=None, valueUri: Optional[FhirUri]=None, valueAttachment: Optional[Attachment]=None, valueCoding: Optional[Coding[GenericTypeCode]]=None, valueQuantity: Optional[Quantity]=None, valueReference: Optional[Reference[Resource]]=None, item: Optional[FhirList[QuestionnaireResponseItem]]=None) -> None:
"\n A structured set of questions and their answers. The questions are ordered and\n grouped into coherent subsets, corresponding to the structure of the grouping\n of the questionnaire being responded to.\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param valueBoolean: None\n :param valueDecimal: None\n :param valueInteger: None\n :param valueDate: None\n :param valueDateTime: None\n :param valueTime: None\n :param valueString: None\n :param valueUri: None\n :param valueAttachment: None\n :param valueCoding: None\n :param valueQuantity: None\n :param valueReference: None\n :param item: Nested groups and/or questions found within this particular answer.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, valueBoolean=valueBoolean, valueDecimal=valueDecimal, valueInteger=valueInteger, valueDate=valueDate, valueDateTime=valueDateTime, valueTime=valueTime, valueString=valueString, valueUri=valueUri, valueAttachment=valueAttachment, valueCoding=valueCoding, valueQuantity=valueQuantity, valueReference=valueReference, item=item) | A structured set of questions and their answers. The questions are ordered and
grouped into coherent subsets, corresponding to the structure of the grouping
of the questionnaire being responded to.
:param id_: None
:param extension: May be used to represent additional information that is not part of the basic
definition of the element. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
:param modifierExtension: May be used to represent additional information that is not part of the basic
definition of the element and that modifies the understanding of the element
in which it is contained and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer can define an extension, there is a set of requirements that SHALL
be met as part of the definition of the extension. Applications processing a
resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
:param valueBoolean: None
:param valueDecimal: None
:param valueInteger: None
:param valueDate: None
:param valueDateTime: None
:param valueTime: None
:param valueString: None
:param valueUri: None
:param valueAttachment: None
:param valueCoding: None
:param valueQuantity: None
:param valueReference: None
:param item: Nested groups and/or questions found within this particular answer. | spark_auto_mapper_fhir/backbone_elements/questionnaire_response_answer.py | __init__ | icanbwell/SparkAutoMapper.FHIR | 1 | python | def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, valueBoolean: Optional[FhirBoolean]=None, valueDecimal: Optional[FhirDecimal]=None, valueInteger: Optional[FhirInteger]=None, valueDate: Optional[FhirDate]=None, valueDateTime: Optional[FhirDateTime]=None, valueTime: Optional[FhirTime]=None, valueString: Optional[FhirString]=None, valueUri: Optional[FhirUri]=None, valueAttachment: Optional[Attachment]=None, valueCoding: Optional[Coding[GenericTypeCode]]=None, valueQuantity: Optional[Quantity]=None, valueReference: Optional[Reference[Resource]]=None, item: Optional[FhirList[QuestionnaireResponseItem]]=None) -> None:
"\n A structured set of questions and their answers. The questions are ordered and\n grouped into coherent subsets, corresponding to the structure of the grouping\n of the questionnaire being responded to.\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param valueBoolean: None\n :param valueDecimal: None\n :param valueInteger: None\n :param valueDate: None\n :param valueDateTime: None\n :param valueTime: None\n :param valueString: None\n :param valueUri: None\n :param valueAttachment: None\n :param valueCoding: None\n :param valueQuantity: None\n :param valueReference: None\n :param item: Nested groups and/or questions found within this particular answer.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, valueBoolean=valueBoolean, valueDecimal=valueDecimal, valueInteger=valueInteger, valueDate=valueDate, valueDateTime=valueDateTime, valueTime=valueTime, valueString=valueString, valueUri=valueUri, valueAttachment=valueAttachment, valueCoding=valueCoding, valueQuantity=valueQuantity, valueReference=valueReference, item=item) | def __init__(self, *, id_: Optional[FhirString]=None, extension: Optional[FhirList[ExtensionBase]]=None, modifierExtension: Optional[FhirList[ExtensionBase]]=None, valueBoolean: Optional[FhirBoolean]=None, valueDecimal: Optional[FhirDecimal]=None, valueInteger: Optional[FhirInteger]=None, valueDate: Optional[FhirDate]=None, valueDateTime: Optional[FhirDateTime]=None, valueTime: Optional[FhirTime]=None, valueString: Optional[FhirString]=None, valueUri: Optional[FhirUri]=None, valueAttachment: Optional[Attachment]=None, valueCoding: Optional[Coding[GenericTypeCode]]=None, valueQuantity: Optional[Quantity]=None, valueReference: Optional[Reference[Resource]]=None, item: Optional[FhirList[QuestionnaireResponseItem]]=None) -> None:
"\n A structured set of questions and their answers. The questions are ordered and\n grouped into coherent subsets, corresponding to the structure of the grouping\n of the questionnaire being responded to.\n\n :param id_: None\n :param extension: May be used to represent additional information that is not part of the basic\n definition of the element. To make the use of extensions safe and manageable,\n there is a strict set of governance applied to the definition and use of\n extensions. Though any implementer can define an extension, there is a set of\n requirements that SHALL be met as part of the definition of the extension.\n :param modifierExtension: May be used to represent additional information that is not part of the basic\n definition of the element and that modifies the understanding of the element\n in which it is contained and/or the understanding of the containing element's\n descendants. Usually modifier elements provide negation or qualification. To\n make the use of extensions safe and manageable, there is a strict set of\n governance applied to the definition and use of extensions. Though any\n implementer can define an extension, there is a set of requirements that SHALL\n be met as part of the definition of the extension. Applications processing a\n resource are required to check for modifier extensions.\n\n Modifier extensions SHALL NOT change the meaning of any elements on Resource\n or DomainResource (including cannot change the meaning of modifierExtension\n itself).\n :param valueBoolean: None\n :param valueDecimal: None\n :param valueInteger: None\n :param valueDate: None\n :param valueDateTime: None\n :param valueTime: None\n :param valueString: None\n :param valueUri: None\n :param valueAttachment: None\n :param valueCoding: None\n :param valueQuantity: None\n :param valueReference: None\n :param item: Nested groups and/or questions found within this particular answer.\n "
super().__init__(id_=id_, extension=extension, modifierExtension=modifierExtension, valueBoolean=valueBoolean, valueDecimal=valueDecimal, valueInteger=valueInteger, valueDate=valueDate, valueDateTime=valueDateTime, valueTime=valueTime, valueString=valueString, valueUri=valueUri, valueAttachment=valueAttachment, valueCoding=valueCoding, valueQuantity=valueQuantity, valueReference=valueReference, item=item)<|docstring|>A structured set of questions and their answers. The questions are ordered and
grouped into coherent subsets, corresponding to the structure of the grouping
of the questionnaire being responded to.
:param id_: None
:param extension: May be used to represent additional information that is not part of the basic
definition of the element. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
:param modifierExtension: May be used to represent additional information that is not part of the basic
definition of the element and that modifies the understanding of the element
in which it is contained and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer can define an extension, there is a set of requirements that SHALL
be met as part of the definition of the extension. Applications processing a
resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
:param valueBoolean: None
:param valueDecimal: None
:param valueInteger: None
:param valueDate: None
:param valueDateTime: None
:param valueTime: None
:param valueString: None
:param valueUri: None
:param valueAttachment: None
:param valueCoding: None
:param valueQuantity: None
:param valueReference: None
:param item: Nested groups and/or questions found within this particular answer.<|endoftext|> |
34ba660f3c30ea62768c70ce1244787c358e042e9c0ff0848f7c96b56c9a2e09 | def find_index(text, pattern, breadth=0, depth=0):
'Return the starting index of the first occurrence of pattern in text,\n or None if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
if ((breadth + len(pattern)) > len(text)):
return None
pchar = None
try:
pchar = pattern[depth]
except:
return breadth
if (not (text[(breadth + depth)] == pchar)):
if (depth == 0):
return find_index(text, pattern, (breadth + 1))
else:
return find_index(text, pattern, (breadth + 1), 0)
else:
if (depth == (len(pattern) - 1)):
return breadth
return find_index(text, pattern, breadth, (depth + 1)) | Return the starting index of the first occurrence of pattern in text,
or None if not found.
O(n) T*P time complexity
where T is length of text and P pattern length | Code/strings.py | find_index | type9/CS-1.3-Core-Data-Structures | 0 | python | def find_index(text, pattern, breadth=0, depth=0):
'Return the starting index of the first occurrence of pattern in text,\n or None if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
if ((breadth + len(pattern)) > len(text)):
return None
pchar = None
try:
pchar = pattern[depth]
except:
return breadth
if (not (text[(breadth + depth)] == pchar)):
if (depth == 0):
return find_index(text, pattern, (breadth + 1))
else:
return find_index(text, pattern, (breadth + 1), 0)
else:
if (depth == (len(pattern) - 1)):
return breadth
return find_index(text, pattern, breadth, (depth + 1)) | def find_index(text, pattern, breadth=0, depth=0):
'Return the starting index of the first occurrence of pattern in text,\n or None if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
if ((breadth + len(pattern)) > len(text)):
return None
pchar = None
try:
pchar = pattern[depth]
except:
return breadth
if (not (text[(breadth + depth)] == pchar)):
if (depth == 0):
return find_index(text, pattern, (breadth + 1))
else:
return find_index(text, pattern, (breadth + 1), 0)
else:
if (depth == (len(pattern) - 1)):
return breadth
return find_index(text, pattern, breadth, (depth + 1))<|docstring|>Return the starting index of the first occurrence of pattern in text,
or None if not found.
O(n) T*P time complexity
where T is length of text and P pattern length<|endoftext|> |
15789443adae5da5cb10caa3f92ef286f67da574a2e1c7dd54f2d1130def6813 | def contains(text, pattern):
'Return a boolean indicating whether pattern occurs in text.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
index = find_index(text, pattern)
if (index or (index == 0)):
return True
return False | Return a boolean indicating whether pattern occurs in text.
O(n) T*P time complexity
where T is length of text and P pattern length | Code/strings.py | contains | type9/CS-1.3-Core-Data-Structures | 0 | python | def contains(text, pattern):
'Return a boolean indicating whether pattern occurs in text.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
index = find_index(text, pattern)
if (index or (index == 0)):
return True
return False | def contains(text, pattern):
'Return a boolean indicating whether pattern occurs in text.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
index = find_index(text, pattern)
if (index or (index == 0)):
return True
return False<|docstring|>Return a boolean indicating whether pattern occurs in text.
O(n) T*P time complexity
where T is length of text and P pattern length<|endoftext|> |
09c924f139681763d4b3fc04d7e84f8d6072f9c249c351b3c7929f63792ed964 | def find_all_indexes(text, pattern):
'Return a list of starting indexes of all occurrences of pattern in text,\n or an empty list if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
indexes = []
last_breadth = 0
while ((last_breadth + len(pattern)) <= len(text)):
index = find_index(text, pattern, breadth=last_breadth)
if (index == None):
break
indexes.append(index)
last_breadth = (index + 1)
if (pattern == ''):
indexes.pop((- 1))
return indexes
return indexes | Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
O(n) T*P time complexity
where T is length of text and P pattern length | Code/strings.py | find_all_indexes | type9/CS-1.3-Core-Data-Structures | 0 | python | def find_all_indexes(text, pattern):
'Return a list of starting indexes of all occurrences of pattern in text,\n or an empty list if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
indexes = []
last_breadth = 0
while ((last_breadth + len(pattern)) <= len(text)):
index = find_index(text, pattern, breadth=last_breadth)
if (index == None):
break
indexes.append(index)
last_breadth = (index + 1)
if (pattern == ):
indexes.pop((- 1))
return indexes
return indexes | def find_all_indexes(text, pattern):
'Return a list of starting indexes of all occurrences of pattern in text,\n or an empty list if not found.\n O(n) T*P time complexity \n where T is length of text and P pattern length'
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
indexes = []
last_breadth = 0
while ((last_breadth + len(pattern)) <= len(text)):
index = find_index(text, pattern, breadth=last_breadth)
if (index == None):
break
indexes.append(index)
last_breadth = (index + 1)
if (pattern == ):
indexes.pop((- 1))
return indexes
return indexes<|docstring|>Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
O(n) T*P time complexity
where T is length of text and P pattern length<|endoftext|> |
6bab6217eef5936db693ebf9a1437fc487371b47717cf5b86b6f427e381f086d | def main():
'Read command-line arguments and test string searching algorithms.'
import sys
args = sys.argv[1:]
if (len(args) == 2):
text = args[0]
pattern = args[1]
test_string_algorithms(text, pattern)
else:
script = sys.argv[0]
print('Usage: {} text pattern'.format(script))
print('Searches for occurrences of pattern in text')
print("\nExample: {} 'abra cadabra' 'abra'".format(script))
print("contains('abra cadabra', 'abra') => True")
print("find_index('abra cadabra', 'abra') => 0")
print("find_all_indexes('abra cadabra', 'abra') => [0, 8]") | Read command-line arguments and test string searching algorithms. | Code/strings.py | main | type9/CS-1.3-Core-Data-Structures | 0 | python | def main():
import sys
args = sys.argv[1:]
if (len(args) == 2):
text = args[0]
pattern = args[1]
test_string_algorithms(text, pattern)
else:
script = sys.argv[0]
print('Usage: {} text pattern'.format(script))
print('Searches for occurrences of pattern in text')
print("\nExample: {} 'abra cadabra' 'abra'".format(script))
print("contains('abra cadabra', 'abra') => True")
print("find_index('abra cadabra', 'abra') => 0")
print("find_all_indexes('abra cadabra', 'abra') => [0, 8]") | def main():
import sys
args = sys.argv[1:]
if (len(args) == 2):
text = args[0]
pattern = args[1]
test_string_algorithms(text, pattern)
else:
script = sys.argv[0]
print('Usage: {} text pattern'.format(script))
print('Searches for occurrences of pattern in text')
print("\nExample: {} 'abra cadabra' 'abra'".format(script))
print("contains('abra cadabra', 'abra') => True")
print("find_index('abra cadabra', 'abra') => 0")
print("find_all_indexes('abra cadabra', 'abra') => [0, 8]")<|docstring|>Read command-line arguments and test string searching algorithms.<|endoftext|> |
0c9883723941f5d0f1b0b7046f830e3b88c40cbef3ad3603e4fbfec8d2f897de | def testSimple(self):
'\n def (var var var):\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, endFile])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, newline, unindent])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def (var var var):
return "hello" | language/testParser.py | testSimple | quasarbright/Subduce | 1 | python | def testSimple(self):
'\n def (var var var):\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, endFile])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, newline, unindent])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def testSimple(self):
'\n def (var var var):\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, endFile])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)
stream = TokenStream([defkw, startFunction, identifier, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, string, newline, unindent])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)]), Body([Return(String(string))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)<|docstring|>def (var var var):
return "hello"<|endoftext|> |
1e1e6ae4af9658ec884eb4dbc355a132a6c39c49dead5dfd6087e8ea70bcdf7a | def testComplex(self):
'\n def (var var):\n print var\n var = "hello"\n return 123\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, printkw, identifier, newline, identifier, equals, string, newline, returnkw, number])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([Print(VariableReference(identifier)), Assignment(identifier, String(string)), Return(Number(number))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def (var var):
print var
var = "hello"
return 123 | language/testParser.py | testComplex | quasarbright/Subduce | 1 | python | def testComplex(self):
'\n def (var var):\n print var\n var = "hello"\n return 123\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, printkw, identifier, newline, identifier, equals, string, newline, returnkw, number])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([Print(VariableReference(identifier)), Assignment(identifier, String(string)), Return(Number(number))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def testComplex(self):
'\n def (var var):\n print var\n var = "hello"\n return 123\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, printkw, identifier, newline, identifier, equals, string, newline, returnkw, number])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([Print(VariableReference(identifier)), Assignment(identifier, String(string)), Return(Number(number))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)<|docstring|>def (var var):
print var
var = "hello"
return 123<|endoftext|> |
8391a262b418794dbb5ef178fb4b2eed950fdab26983fb9cb9a68c9c63babac8 | def testFunctionInFunction(self):
'\n def (var var):\n def (var var):\n return 123\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, number, newline, unindent, returnkw, string, newline, unindent])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([FunctionDefinition(signature, Body([Return(Number(number))])), Return(String(string))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def (var var):
def (var var):
return 123
return "hello" | language/testParser.py | testFunctionInFunction | quasarbright/Subduce | 1 | python | def testFunctionInFunction(self):
'\n def (var var):\n def (var var):\n return 123\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, number, newline, unindent, returnkw, string, newline, unindent])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([FunctionDefinition(signature, Body([Return(Number(number))])), Return(String(string))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def testFunctionInFunction(self):
'\n def (var var):\n def (var var):\n return 123\n return "hello"\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, returnkw, number, newline, unindent, returnkw, string, newline, unindent])
signature = FunctionSignature(identifier, [VariableReference(identifier)])
body = Body([FunctionDefinition(signature, Body([Return(Number(number))])), Return(String(string))])
expected = FunctionDefinition(signature, body)
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)<|docstring|>def (var var):
def (var var):
return 123
return "hello"<|endoftext|> |
d8dd81714a5198631501e78c8f76bfbe7245b1719916676b1ccc8046cb62dc44 | def testMultilineFunctionCall(self):
'\n (var\n 123\n "hello")\n '
stream = TokenStream([startFunction, identifier, newline, indent, number, string, endFunction, unindent])
expected = FunctionCall(VariableReference(identifier), [Number(number), String(string)])
actual = parseFunctionCall(stream)
self.assertEqual(actual, expected) | (var
123
"hello") | language/testParser.py | testMultilineFunctionCall | quasarbright/Subduce | 1 | python | def testMultilineFunctionCall(self):
'\n (var\n 123\n "hello")\n '
stream = TokenStream([startFunction, identifier, newline, indent, number, string, endFunction, unindent])
expected = FunctionCall(VariableReference(identifier), [Number(number), String(string)])
actual = parseFunctionCall(stream)
self.assertEqual(actual, expected) | def testMultilineFunctionCall(self):
'\n (var\n 123\n "hello")\n '
stream = TokenStream([startFunction, identifier, newline, indent, number, string, endFunction, unindent])
expected = FunctionCall(VariableReference(identifier), [Number(number), String(string)])
actual = parseFunctionCall(stream)
self.assertEqual(actual, expected)<|docstring|>(var
123
"hello")<|endoftext|> |
2fe8b006ccca5d5f2b9b9a4cafc43b9bf4bff23e2747b6a76a96d9b3dffa4f74 | def testBig(self):
'\n def (var var):\n var = (var\n var)\n return var\n print var\n '
tokens = [defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, identifier, equals, startFunction, identifier, newline, indent, identifier, endFunction, newline, unindent, returnkw, identifier, newline, unindent, printkw, identifier]
signature = FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)])
body = Body([Assignment(identifier, VariableReference(identifier)), Return(VariableReference(identifier))])
expected = MainBody([FunctionDefinition(signature, body), Print(VariableReference(identifier))])
actual = parseTokens(tokens)
self.assertEqual(actual, expected) | def (var var):
var = (var
var)
return var
print var | language/testParser.py | testBig | quasarbright/Subduce | 1 | python | def testBig(self):
'\n def (var var):\n var = (var\n var)\n return var\n print var\n '
tokens = [defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, identifier, equals, startFunction, identifier, newline, indent, identifier, endFunction, newline, unindent, returnkw, identifier, newline, unindent, printkw, identifier]
signature = FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)])
body = Body([Assignment(identifier, VariableReference(identifier)), Return(VariableReference(identifier))])
expected = MainBody([FunctionDefinition(signature, body), Print(VariableReference(identifier))])
actual = parseTokens(tokens)
self.assertEqual(actual, expected) | def testBig(self):
'\n def (var var):\n var = (var\n var)\n return var\n print var\n '
tokens = [defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, indent, identifier, equals, startFunction, identifier, newline, indent, identifier, endFunction, newline, unindent, returnkw, identifier, newline, unindent, printkw, identifier]
signature = FunctionSignature(identifier, [VariableReference(identifier), VariableReference(identifier)])
body = Body([Assignment(identifier, VariableReference(identifier)), Return(VariableReference(identifier))])
expected = MainBody([FunctionDefinition(signature, body), Print(VariableReference(identifier))])
actual = parseTokens(tokens)
self.assertEqual(actual, expected)<|docstring|>def (var var):
var = (var
var)
return var
print var<|endoftext|> |
3aa6cd674457904a83119984a414bfc87b1a09cf0f3cb6867f00a5104c17ee51 | def testList(self):
'\n [\n 123\n 123\n ]\n '
stream = TokenStream([startList, newline, indent, number, newline, number, newline, unindent, endList])
expected = ListExpression([Number(number), Number(number)])
actual = parseList(stream)
self.assertEqual(actual, expected) | [
123
123
] | language/testParser.py | testList | quasarbright/Subduce | 1 | python | def testList(self):
'\n [\n 123\n 123\n ]\n '
stream = TokenStream([startList, newline, indent, number, newline, number, newline, unindent, endList])
expected = ListExpression([Number(number), Number(number)])
actual = parseList(stream)
self.assertEqual(actual, expected) | def testList(self):
'\n [\n 123\n 123\n ]\n '
stream = TokenStream([startList, newline, indent, number, newline, number, newline, unindent, endList])
expected = ListExpression([Number(number), Number(number)])
actual = parseList(stream)
self.assertEqual(actual, expected)<|docstring|>[
123
123
]<|endoftext|> |
a6094880645ea69a5cdce258f9c1677cffd2a8fec8f8d219128c23eb0305ad9c | def testAssignment(self):
'\n var = \n 123\n '
stream = TokenStream([identifier, equals, newline, indent, number])
expected = Assignment(identifier, Number(number))
actual = parseAssignment(stream)
self.assertEqual(actual, expected) | var =
123 | language/testParser.py | testAssignment | quasarbright/Subduce | 1 | python | def testAssignment(self):
'\n var = \n 123\n '
stream = TokenStream([identifier, equals, newline, indent, number])
expected = Assignment(identifier, Number(number))
actual = parseAssignment(stream)
self.assertEqual(actual, expected) | def testAssignment(self):
'\n var = \n 123\n '
stream = TokenStream([identifier, equals, newline, indent, number])
expected = Assignment(identifier, Number(number))
actual = parseAssignment(stream)
self.assertEqual(actual, expected)<|docstring|>var =
123<|endoftext|> |
28087c90de444df2d6d1b7c593f06cd6a561caf1379604a645573bcb8627ba25 | def testFirstLineInFuncEmpty(self):
'\n def (var var):\n\n return var\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, newline, indent, returnkw, identifier])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier)]), Body([Return(VariableReference(identifier))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def (var var):
return var | language/testParser.py | testFirstLineInFuncEmpty | quasarbright/Subduce | 1 | python | def testFirstLineInFuncEmpty(self):
'\n def (var var):\n\n return var\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, newline, indent, returnkw, identifier])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier)]), Body([Return(VariableReference(identifier))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected) | def testFirstLineInFuncEmpty(self):
'\n def (var var):\n\n return var\n '
stream = TokenStream([defkw, startFunction, identifier, identifier, endFunction, endSignature, newline, newline, indent, returnkw, identifier])
expected = FunctionDefinition(FunctionSignature(identifier, [VariableReference(identifier)]), Body([Return(VariableReference(identifier))]))
actual = parseFunctionDefinition(stream)
self.assertEqual(actual, expected)<|docstring|>def (var var):
return var<|endoftext|> |
46c1177c0b7031c23bf89785d17561b223432c461e63db1ad163dbf1e6723fe5 | def __init__(self, text: Text, token_weights: List[float], top_k_ratio: float=TOP_K_AVG_RATIO):
"Initializes with a text and a list of token weights.\n\n Args:\n text: A full-text input to a classifier with tokens separated with ' '.\n token_weights: A list of token weights (in the token position order).\n top_k_ratio: Rationale size in tokens is defined proportional to the input\n length (in tokens). The percentages are given for the ERASER datasets\n and are 10% on average.\n "
self.text = text
self.tokens = str.split(text)
assert (len(self.tokens) == len(token_weights)), 'Token count does not match.'
self.token_weights = token_weights
top_k_value = math.ceil((len(self.tokens) * top_k_ratio))
self.top_k_ids = np.argsort(token_weights)[(- top_k_value):]
self.top_k_ids = list(reversed(self.top_k_ids))
self.top_k_ids_set = set(self.top_k_ids) | Initializes with a text and a list of token weights.
Args:
text: A full-text input to a classifier with tokens separated with ' '.
token_weights: A list of token weights (in the token position order).
top_k_ratio: Rationale size in tokens is defined proportional to the input
length (in tokens). The percentages are given for the ERASER datasets
and are 10% on average. | lit_nlp/components/citrus/helpers.py | __init__ | eichinflo/lit | 2,854 | python | def __init__(self, text: Text, token_weights: List[float], top_k_ratio: float=TOP_K_AVG_RATIO):
"Initializes with a text and a list of token weights.\n\n Args:\n text: A full-text input to a classifier with tokens separated with ' '.\n token_weights: A list of token weights (in the token position order).\n top_k_ratio: Rationale size in tokens is defined proportional to the input\n length (in tokens). The percentages are given for the ERASER datasets\n and are 10% on average.\n "
self.text = text
self.tokens = str.split(text)
assert (len(self.tokens) == len(token_weights)), 'Token count does not match.'
self.token_weights = token_weights
top_k_value = math.ceil((len(self.tokens) * top_k_ratio))
self.top_k_ids = np.argsort(token_weights)[(- top_k_value):]
self.top_k_ids = list(reversed(self.top_k_ids))
self.top_k_ids_set = set(self.top_k_ids) | def __init__(self, text: Text, token_weights: List[float], top_k_ratio: float=TOP_K_AVG_RATIO):
"Initializes with a text and a list of token weights.\n\n Args:\n text: A full-text input to a classifier with tokens separated with ' '.\n token_weights: A list of token weights (in the token position order).\n top_k_ratio: Rationale size in tokens is defined proportional to the input\n length (in tokens). The percentages are given for the ERASER datasets\n and are 10% on average.\n "
self.text = text
self.tokens = str.split(text)
assert (len(self.tokens) == len(token_weights)), 'Token count does not match.'
self.token_weights = token_weights
top_k_value = math.ceil((len(self.tokens) * top_k_ratio))
self.top_k_ids = np.argsort(token_weights)[(- top_k_value):]
self.top_k_ids = list(reversed(self.top_k_ids))
self.top_k_ids_set = set(self.top_k_ids)<|docstring|>Initializes with a text and a list of token weights.
Args:
text: A full-text input to a classifier with tokens separated with ' '.
token_weights: A list of token weights (in the token position order).
top_k_ratio: Rationale size in tokens is defined proportional to the input
length (in tokens). The percentages are given for the ERASER datasets
and are 10% on average.<|endoftext|> |
61c6c324df31421486765501882357b9db316fd0cf148fd8e3347daa9d1c28ff | def get_rationale_text(self, mask_token: Optional[Text]=None) -> str:
'Returns the text covering only the rationale.\n\n Args:\n mask_token: Token to use for all the tokens not in the rationale.\n Returns: A string representing the source text with everything but rationale\n masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result) | Returns the text covering only the rationale.
Args:
mask_token: Token to use for all the tokens not in the rationale.
Returns: A string representing the source text with everything but rationale
masked. | lit_nlp/components/citrus/helpers.py | get_rationale_text | eichinflo/lit | 2,854 | python | def get_rationale_text(self, mask_token: Optional[Text]=None) -> str:
'Returns the text covering only the rationale.\n\n Args:\n mask_token: Token to use for all the tokens not in the rationale.\n Returns: A string representing the source text with everything but rationale\n masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result) | def get_rationale_text(self, mask_token: Optional[Text]=None) -> str:
'Returns the text covering only the rationale.\n\n Args:\n mask_token: Token to use for all the tokens not in the rationale.\n Returns: A string representing the source text with everything but rationale\n masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result)<|docstring|>Returns the text covering only the rationale.
Args:
mask_token: Token to use for all the tokens not in the rationale.
Returns: A string representing the source text with everything but rationale
masked.<|endoftext|> |
6e9eba76808da76fa266151afe7314158546a66de298abe935407ed0fb104170 | def get_text_wo_rationale(self, mask_token: Optional[Text]=None) -> str:
'Returns the text without the rationale.\n\n Args:\n mask_token: Token to use for all the tokens in the rationale.\n Returns: A string representing the source text with the rationale masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i not in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result) | Returns the text without the rationale.
Args:
mask_token: Token to use for all the tokens in the rationale.
Returns: A string representing the source text with the rationale masked. | lit_nlp/components/citrus/helpers.py | get_text_wo_rationale | eichinflo/lit | 2,854 | python | def get_text_wo_rationale(self, mask_token: Optional[Text]=None) -> str:
'Returns the text without the rationale.\n\n Args:\n mask_token: Token to use for all the tokens in the rationale.\n Returns: A string representing the source text with the rationale masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i not in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result) | def get_text_wo_rationale(self, mask_token: Optional[Text]=None) -> str:
'Returns the text without the rationale.\n\n Args:\n mask_token: Token to use for all the tokens in the rationale.\n Returns: A string representing the source text with the rationale masked.\n '
result = []
for (i, token) in enumerate(self.tokens):
if (i not in self.top_k_ids_set):
result.append(token)
elif mask_token:
result.append(mask_token)
return ' '.join(result)<|docstring|>Returns the text without the rationale.
Args:
mask_token: Token to use for all the tokens in the rationale.
Returns: A string representing the source text with the rationale masked.<|endoftext|> |
25d62a8aee0dc38c4ea675e8ed0a2f4947ad8fd18af7f29520d6454625792a18 | @contextmanager
def fake_security_scanner(hostname='fakesecurityscanner', incompatible=False):
'\n Context manager which yields a fake security scanner.\n\n All requests made to the given hostname (default: fakesecurityscanner) will be handled by the\n fake. If `incompatible is True`, returns malformed responses to test if a client can handle\n version skew.\n '
scanner = FakeSecurityScanner(hostname)
if (not incompatible):
with HTTMock(*scanner.endpoints):
(yield scanner)
else:
with HTTMock(*scanner.incompatible_endpoints):
(yield scanner) | Context manager which yields a fake security scanner.
All requests made to the given hostname (default: fakesecurityscanner) will be handled by the
fake. If `incompatible is True`, returns malformed responses to test if a client can handle
version skew. | util/secscan/v4/fake.py | fake_security_scanner | andykrohg/quay | 0 | python | @contextmanager
def fake_security_scanner(hostname='fakesecurityscanner', incompatible=False):
'\n Context manager which yields a fake security scanner.\n\n All requests made to the given hostname (default: fakesecurityscanner) will be handled by the\n fake. If `incompatible is True`, returns malformed responses to test if a client can handle\n version skew.\n '
scanner = FakeSecurityScanner(hostname)
if (not incompatible):
with HTTMock(*scanner.endpoints):
(yield scanner)
else:
with HTTMock(*scanner.incompatible_endpoints):
(yield scanner) | @contextmanager
def fake_security_scanner(hostname='fakesecurityscanner', incompatible=False):
'\n Context manager which yields a fake security scanner.\n\n All requests made to the given hostname (default: fakesecurityscanner) will be handled by the\n fake. If `incompatible is True`, returns malformed responses to test if a client can handle\n version skew.\n '
scanner = FakeSecurityScanner(hostname)
if (not incompatible):
with HTTMock(*scanner.endpoints):
(yield scanner)
else:
with HTTMock(*scanner.incompatible_endpoints):
(yield scanner)<|docstring|>Context manager which yields a fake security scanner.
All requests made to the given hostname (default: fakesecurityscanner) will be handled by the
fake. If `incompatible is True`, returns malformed responses to test if a client can handle
version skew.<|endoftext|> |
af47e937500a2015ebb9be3addf32dece081bd374c23618325b9f87786b4f7dd | @property
def endpoints(self):
'\n The HTTMock endpoint definitions for the fake security scanner.\n '
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_state', method='GET')
def state(url, request):
return {'status_code': 200, 'content': json.dumps({'state': self.indexer_state})}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report', method='POST')
def index(url, request):
body = json.loads(request.body)
if ((not ('hash' in body)) or (not ('layers' in body))):
return {'status_code': 400, 'content': json.dumps({'code': 'bad-request', 'message': 'failed to deserialize manifest'})}
report = {'manifest_hash': body['hash'], 'state': 'IndexFinished', 'packages': {}, 'distributions': {}, 'repository': {}, 'environments': {}, 'success': True, 'err': ''}
self.index_reports[body['hash']] = report
self.vulnerability_reports[body['hash']] = {'manifest_hash': body['hash'], 'packages': {}, 'distributions': {}, 'environments': {}, 'vulnerabilities': {}, 'package_vulnerabilities': {}}
self.manifests[body['hash']] = body
return {'status_code': 201, 'content': json.dumps(report), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report/(.+)', method='GET')
def index_report(url, request):
manifest_hash = url.path[len('/api/v1/index_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.index_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/vulnerability_report/(.+)', method='GET')
def vulnerability_report(url, request):
manifest_hash = url.path[len('/api/v1/vulnerability_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.vulnerability_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@all_requests
def response_content(url, _):
return {'status_code': 404, 'content': '404 page not found'}
return [state, index, index_report, vulnerability_report, response_content] | The HTTMock endpoint definitions for the fake security scanner. | util/secscan/v4/fake.py | endpoints | andykrohg/quay | 0 | python | @property
def endpoints(self):
'\n \n '
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_state', method='GET')
def state(url, request):
return {'status_code': 200, 'content': json.dumps({'state': self.indexer_state})}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report', method='POST')
def index(url, request):
body = json.loads(request.body)
if ((not ('hash' in body)) or (not ('layers' in body))):
return {'status_code': 400, 'content': json.dumps({'code': 'bad-request', 'message': 'failed to deserialize manifest'})}
report = {'manifest_hash': body['hash'], 'state': 'IndexFinished', 'packages': {}, 'distributions': {}, 'repository': {}, 'environments': {}, 'success': True, 'err': }
self.index_reports[body['hash']] = report
self.vulnerability_reports[body['hash']] = {'manifest_hash': body['hash'], 'packages': {}, 'distributions': {}, 'environments': {}, 'vulnerabilities': {}, 'package_vulnerabilities': {}}
self.manifests[body['hash']] = body
return {'status_code': 201, 'content': json.dumps(report), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report/(.+)', method='GET')
def index_report(url, request):
manifest_hash = url.path[len('/api/v1/index_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.index_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/vulnerability_report/(.+)', method='GET')
def vulnerability_report(url, request):
manifest_hash = url.path[len('/api/v1/vulnerability_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.vulnerability_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@all_requests
def response_content(url, _):
return {'status_code': 404, 'content': '404 page not found'}
return [state, index, index_report, vulnerability_report, response_content] | @property
def endpoints(self):
'\n \n '
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_state', method='GET')
def state(url, request):
return {'status_code': 200, 'content': json.dumps({'state': self.indexer_state})}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report', method='POST')
def index(url, request):
body = json.loads(request.body)
if ((not ('hash' in body)) or (not ('layers' in body))):
return {'status_code': 400, 'content': json.dumps({'code': 'bad-request', 'message': 'failed to deserialize manifest'})}
report = {'manifest_hash': body['hash'], 'state': 'IndexFinished', 'packages': {}, 'distributions': {}, 'repository': {}, 'environments': {}, 'success': True, 'err': }
self.index_reports[body['hash']] = report
self.vulnerability_reports[body['hash']] = {'manifest_hash': body['hash'], 'packages': {}, 'distributions': {}, 'environments': {}, 'vulnerabilities': {}, 'package_vulnerabilities': {}}
self.manifests[body['hash']] = body
return {'status_code': 201, 'content': json.dumps(report), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/index_report/(.+)', method='GET')
def index_report(url, request):
manifest_hash = url.path[len('/api/v1/index_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.index_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@urlmatch(netloc=('(.*\\.)?' + self.hostname), path='/api/v1/vulnerability_report/(.+)', method='GET')
def vulnerability_report(url, request):
manifest_hash = url.path[len('/api/v1/vulnerability_report/'):]
if (manifest_hash not in self.index_reports):
return {'status_code': 404, 'content': json.dumps({'code': 'not-found', 'message': (('index report for manifest "' + manifest_hash) + '" not found')})}
return {'status_code': 200, 'content': json.dumps(self.vulnerability_reports[manifest_hash]), 'headers': {'etag': self.indexer_state}}
@all_requests
def response_content(url, _):
return {'status_code': 404, 'content': '404 page not found'}
return [state, index, index_report, vulnerability_report, response_content]<|docstring|>The HTTMock endpoint definitions for the fake security scanner.<|endoftext|> |
d391a127e905aec99ecc708788eaa033598f1039134ab4ac1e5657c49cdbb9df | @property
def incompatible_endpoints(self):
'\n The HTTMock endpoint definitions for the fake security scanner which returns incompatible responses.\n '
@all_requests
def response_content(url, _):
return {'status_code': 200, 'content': json.dumps({'foo': 'bar'})}
return [response_content] | The HTTMock endpoint definitions for the fake security scanner which returns incompatible responses. | util/secscan/v4/fake.py | incompatible_endpoints | andykrohg/quay | 0 | python | @property
def incompatible_endpoints(self):
'\n \n '
@all_requests
def response_content(url, _):
return {'status_code': 200, 'content': json.dumps({'foo': 'bar'})}
return [response_content] | @property
def incompatible_endpoints(self):
'\n \n '
@all_requests
def response_content(url, _):
return {'status_code': 200, 'content': json.dumps({'foo': 'bar'})}
return [response_content]<|docstring|>The HTTMock endpoint definitions for the fake security scanner which returns incompatible responses.<|endoftext|> |
316e317dee8a446dcd11169c7f29a96f36eac507d270df689c74b39dbaba0191 | def get_runtype(self):
"\n Returns runtype. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'energy'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return line.split('(')[0]
else:
return line.split('(')[0] | Returns runtype. For example, for MP2 single points, the line `energy('mp2')` is used.
This method returns the string 'energy'. | autochem/interfaces/psi_results.py | get_runtype | tommason14/monash_automation | 7 | python | def get_runtype(self):
"\n Returns runtype. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'energy'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return line.split('(')[0]
else:
return line.split('(')[0] | def get_runtype(self):
"\n Returns runtype. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'energy'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return line.split('(')[0]
else:
return line.split('(')[0]<|docstring|>Returns runtype. For example, for MP2 single points, the line `energy('mp2')` is used.
This method returns the string 'energy'.<|endoftext|> |
5e0e6d4afe87d82e9036147ae9fa0375a4a05ddfc08437892dcf253ab53283d4 | @property
def method(self):
"\n Returns energy type. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'mp2'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return re.search("[A-z]*\\('([A-z0-9]*)'\\)", line).group(1) | Returns energy type. For example, for MP2 single points, the line `energy('mp2')` is used.
This method returns the string 'mp2'. | autochem/interfaces/psi_results.py | method | tommason14/monash_automation | 7 | python | @property
def method(self):
"\n Returns energy type. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'mp2'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return re.search("[A-z]*\\('([A-z0-9]*)'\\)", line).group(1) | @property
def method(self):
"\n Returns energy type. For example, for MP2 single points, the line `energy('mp2')` is used. \n This method returns the string 'mp2'.\n "
for line in self.read():
if re.search("[A-z]*\\('[A-z0-9]*'(.?\\s*[A-z]*='[A-z]*')*\\)", line):
if re.search("[A-z]*\\('[A-z0-9]*'\\)", line):
return re.search("[A-z]*\\('([A-z0-9]*)'\\)", line).group(1)<|docstring|>Returns energy type. For example, for MP2 single points, the line `energy('mp2')` is used.
This method returns the string 'mp2'.<|endoftext|> |
e070c65dde00d278bfaeaee3953a256e6d0d26213243c5effcc9a46b3dff2964 | def _neutral_homo_lumo(self):
'\n Finds HOMO-LUMO gap for jobs of singlet multiplicity\n '
found_region = False
energies = []
for line in self.read():
if ('Orbital Energies' in line):
found_region = True
if ('Final Occupation' in line):
found_region = False
if (found_region and (line.strip() != '')):
energies.append(line)
for (index, line) in enumerate(energies):
if ('Virtual' in line):
homo_lumo = energies[(index - 1):(index + 2)]
homo = float(homo_lumo[0].split()[(- 1)])
lumo = float(homo_lumo[(- 1)].split()[1])
return (homo, lumo) | Finds HOMO-LUMO gap for jobs of singlet multiplicity | autochem/interfaces/psi_results.py | _neutral_homo_lumo | tommason14/monash_automation | 7 | python | def _neutral_homo_lumo(self):
'\n \n '
found_region = False
energies = []
for line in self.read():
if ('Orbital Energies' in line):
found_region = True
if ('Final Occupation' in line):
found_region = False
if (found_region and (line.strip() != )):
energies.append(line)
for (index, line) in enumerate(energies):
if ('Virtual' in line):
homo_lumo = energies[(index - 1):(index + 2)]
homo = float(homo_lumo[0].split()[(- 1)])
lumo = float(homo_lumo[(- 1)].split()[1])
return (homo, lumo) | def _neutral_homo_lumo(self):
'\n \n '
found_region = False
energies = []
for line in self.read():
if ('Orbital Energies' in line):
found_region = True
if ('Final Occupation' in line):
found_region = False
if (found_region and (line.strip() != )):
energies.append(line)
for (index, line) in enumerate(energies):
if ('Virtual' in line):
homo_lumo = energies[(index - 1):(index + 2)]
homo = float(homo_lumo[0].split()[(- 1)])
lumo = float(homo_lumo[(- 1)].split()[1])
return (homo, lumo)<|docstring|>Finds HOMO-LUMO gap for jobs of singlet multiplicity<|endoftext|> |
e5f1e1ea536a14dbd56d0ab97737e04b63b430a1396bc6caee9a9fbb3cd07c4f | def _reduced_homo_lumo(self):
'\n Finds SOMO-LUMO gap for jobs of doublet multiplicity\n '
found_singly_occupied = False
found_virtual = False
singly = []
virtual = []
for line in self.read():
if ('Singly Occupied' in line):
found_singly_occupied = True
if ('Virtual' in line):
found_singly_occupied = False
found_virtual = True
if ('Final Occupation' in line):
found_virtual = False
if (found_singly_occupied and (line.strip() != '')):
singly.append(line)
if (found_virtual and (line.strip() != '')):
virtual.append(line)
if (len(virtual) > 3):
break
somo = float(singly[(- 1)].split()[(- 1)])
lumo = float(virtual[1].split()[1])
return (somo, lumo) | Finds SOMO-LUMO gap for jobs of doublet multiplicity | autochem/interfaces/psi_results.py | _reduced_homo_lumo | tommason14/monash_automation | 7 | python | def _reduced_homo_lumo(self):
'\n \n '
found_singly_occupied = False
found_virtual = False
singly = []
virtual = []
for line in self.read():
if ('Singly Occupied' in line):
found_singly_occupied = True
if ('Virtual' in line):
found_singly_occupied = False
found_virtual = True
if ('Final Occupation' in line):
found_virtual = False
if (found_singly_occupied and (line.strip() != )):
singly.append(line)
if (found_virtual and (line.strip() != )):
virtual.append(line)
if (len(virtual) > 3):
break
somo = float(singly[(- 1)].split()[(- 1)])
lumo = float(virtual[1].split()[1])
return (somo, lumo) | def _reduced_homo_lumo(self):
'\n \n '
found_singly_occupied = False
found_virtual = False
singly = []
virtual = []
for line in self.read():
if ('Singly Occupied' in line):
found_singly_occupied = True
if ('Virtual' in line):
found_singly_occupied = False
found_virtual = True
if ('Final Occupation' in line):
found_virtual = False
if (found_singly_occupied and (line.strip() != )):
singly.append(line)
if (found_virtual and (line.strip() != )):
virtual.append(line)
if (len(virtual) > 3):
break
somo = float(singly[(- 1)].split()[(- 1)])
lumo = float(virtual[1].split()[1])
return (somo, lumo)<|docstring|>Finds SOMO-LUMO gap for jobs of doublet multiplicity<|endoftext|> |
2ea27e1a525ac936db54765d2fb225d7ff835fe1eb9e7424314b76d292b506d5 | @property
def homo_lumo_info(self):
'\n Prints the HOMO-LUMO gap. Finds SOMO-LUMO if multiplicity is 2.\n Returns `self.multiplicity`, SOMO/HOMO (eV), LUMO (eV) and the gap (eV).\n '
if (self.multiplicity == 1):
transition = 'HOMO-LUMO'
else:
transition = 'SOMO-LUMO'
(homo, lumo, gap) = self._homo_lumo_gap()
return {'File': self.file, 'Path': self.path, 'Multiplicity': self.multiplicity, 'Transition': transition, 'HOMO/SOMO (eV)': homo, 'LUMO (eV)': lumo, 'Gap (eV)': gap} | Prints the HOMO-LUMO gap. Finds SOMO-LUMO if multiplicity is 2.
Returns `self.multiplicity`, SOMO/HOMO (eV), LUMO (eV) and the gap (eV). | autochem/interfaces/psi_results.py | homo_lumo_info | tommason14/monash_automation | 7 | python | @property
def homo_lumo_info(self):
'\n Prints the HOMO-LUMO gap. Finds SOMO-LUMO if multiplicity is 2.\n Returns `self.multiplicity`, SOMO/HOMO (eV), LUMO (eV) and the gap (eV).\n '
if (self.multiplicity == 1):
transition = 'HOMO-LUMO'
else:
transition = 'SOMO-LUMO'
(homo, lumo, gap) = self._homo_lumo_gap()
return {'File': self.file, 'Path': self.path, 'Multiplicity': self.multiplicity, 'Transition': transition, 'HOMO/SOMO (eV)': homo, 'LUMO (eV)': lumo, 'Gap (eV)': gap} | @property
def homo_lumo_info(self):
'\n Prints the HOMO-LUMO gap. Finds SOMO-LUMO if multiplicity is 2.\n Returns `self.multiplicity`, SOMO/HOMO (eV), LUMO (eV) and the gap (eV).\n '
if (self.multiplicity == 1):
transition = 'HOMO-LUMO'
else:
transition = 'SOMO-LUMO'
(homo, lumo, gap) = self._homo_lumo_gap()
return {'File': self.file, 'Path': self.path, 'Multiplicity': self.multiplicity, 'Transition': transition, 'HOMO/SOMO (eV)': homo, 'LUMO (eV)': lumo, 'Gap (eV)': gap}<|docstring|>Prints the HOMO-LUMO gap. Finds SOMO-LUMO if multiplicity is 2.
Returns `self.multiplicity`, SOMO/HOMO (eV), LUMO (eV) and the gap (eV).<|endoftext|> |
36b3609edff168ae93a42b220b5a38952ef65eb80216d3347b2671e8d341f34a | def get_data(self):
'\n Returns job data: filename, filepath, basis set, HF/DFT energy, and MP2 opposite\n and same spin parameters if relevant.\n '
if (self.method == 'scf'):
return self._scf_data()
elif (self.method == 'mp2'):
return self._mp2_data() | Returns job data: filename, filepath, basis set, HF/DFT energy, and MP2 opposite
and same spin parameters if relevant. | autochem/interfaces/psi_results.py | get_data | tommason14/monash_automation | 7 | python | def get_data(self):
'\n Returns job data: filename, filepath, basis set, HF/DFT energy, and MP2 opposite\n and same spin parameters if relevant.\n '
if (self.method == 'scf'):
return self._scf_data()
elif (self.method == 'mp2'):
return self._mp2_data() | def get_data(self):
'\n Returns job data: filename, filepath, basis set, HF/DFT energy, and MP2 opposite\n and same spin parameters if relevant.\n '
if (self.method == 'scf'):
return self._scf_data()
elif (self.method == 'mp2'):
return self._mp2_data()<|docstring|>Returns job data: filename, filepath, basis set, HF/DFT energy, and MP2 opposite
and same spin parameters if relevant.<|endoftext|> |
0e8b39f66da9b93f5b5b9ec8a8be487bb6ce22c79bf2c4078f52c182bccdb6a7 | @property
def basis(self):
'\n Returns basis set.\n '
for line in self.read():
if re.search('basis\\s\\w*(\\-?\\w*){1,2}$', line):
return line.split()[(- 1)] | Returns basis set. | autochem/interfaces/psi_results.py | basis | tommason14/monash_automation | 7 | python | @property
def basis(self):
'\n \n '
for line in self.read():
if re.search('basis\\s\\w*(\\-?\\w*){1,2}$', line):
return line.split()[(- 1)] | @property
def basis(self):
'\n \n '
for line in self.read():
if re.search('basis\\s\\w*(\\-?\\w*){1,2}$', line):
return line.split()[(- 1)]<|docstring|>Returns basis set.<|endoftext|> |
be2cc4689dc7052b1d46012e397768a6a8935fb5de8c51868ce9b50b9ef247e3 | @property
def total_energy(self):
'\n Returns total energy, printed for scf calculations.\n '
total = ''
for line in self.read():
if ('Total Energy =' in line):
total = float(line.split('=')[1].strip())
return total | Returns total energy, printed for scf calculations. | autochem/interfaces/psi_results.py | total_energy | tommason14/monash_automation | 7 | python | @property
def total_energy(self):
'\n \n '
total =
for line in self.read():
if ('Total Energy =' in line):
total = float(line.split('=')[1].strip())
return total | @property
def total_energy(self):
'\n \n '
total =
for line in self.read():
if ('Total Energy =' in line):
total = float(line.split('=')[1].strip())
return total<|docstring|>Returns total energy, printed for scf calculations.<|endoftext|> |
0a89bc78d4950886c1390f999e1e52083ae0f29b01e2654f51ad1eaeb848cc03 | def _scf_data(self):
'\n Return data for scf calculations. \n Note the NAs returned are because of no MP2 data.\n '
return (self.file, self.path, self.method, self.basis, self.total_energy, 'NA', 'NA', 'NA') | Return data for scf calculations.
Note the NAs returned are because of no MP2 data. | autochem/interfaces/psi_results.py | _scf_data | tommason14/monash_automation | 7 | python | def _scf_data(self):
'\n Return data for scf calculations. \n Note the NAs returned are because of no MP2 data.\n '
return (self.file, self.path, self.method, self.basis, self.total_energy, 'NA', 'NA', 'NA') | def _scf_data(self):
'\n Return data for scf calculations. \n Note the NAs returned are because of no MP2 data.\n '
return (self.file, self.path, self.method, self.basis, self.total_energy, 'NA', 'NA', 'NA')<|docstring|>Return data for scf calculations.
Note the NAs returned are because of no MP2 data.<|endoftext|> |
e7f31e208af7ec500b23de8dbb7b62cf4a10ce7fd851f52b5e9308e39926ab9e | @property
def hf_energy_for_mp2(self):
"\n Returns 'reference energy' from MP2 calculations.\n "
HF = ''
for line in self.read():
if ('Reference Energy =' in line):
HF = float(line.split('=')[1].split()[0].strip())
return HF | Returns 'reference energy' from MP2 calculations. | autochem/interfaces/psi_results.py | hf_energy_for_mp2 | tommason14/monash_automation | 7 | python | @property
def hf_energy_for_mp2(self):
"\n \n "
HF =
for line in self.read():
if ('Reference Energy =' in line):
HF = float(line.split('=')[1].split()[0].strip())
return HF | @property
def hf_energy_for_mp2(self):
"\n \n "
HF =
for line in self.read():
if ('Reference Energy =' in line):
HF = float(line.split('=')[1].split()[0].strip())
return HF<|docstring|>Returns 'reference energy' from MP2 calculations.<|endoftext|> |
8e8ae5a6da30fd7f0cfd39bd1f94e2243735e5e07f6d5b1fe74844f4be4843d3 | @property
def mp2_opp(self):
'\n Returns MP2 opposite spin energy.\n '
opp = ''
for line in self.read():
if ('Opposite-Spin Energy =' in line):
opp = float(line.split('=')[1].split()[0].strip())
return opp | Returns MP2 opposite spin energy. | autochem/interfaces/psi_results.py | mp2_opp | tommason14/monash_automation | 7 | python | @property
def mp2_opp(self):
'\n \n '
opp =
for line in self.read():
if ('Opposite-Spin Energy =' in line):
opp = float(line.split('=')[1].split()[0].strip())
return opp | @property
def mp2_opp(self):
'\n \n '
opp =
for line in self.read():
if ('Opposite-Spin Energy =' in line):
opp = float(line.split('=')[1].split()[0].strip())
return opp<|docstring|>Returns MP2 opposite spin energy.<|endoftext|> |
77275cf96c8dee5b2813c9789d5f7da40c499154227acb84b915fe0b42fc1c08 | @property
def mp2_same(self):
'\n Returns MP2 same spin energy.\n '
same = ''
for line in self.read():
if ('Same-Spin Energy =' in line):
same = float(line.split('=')[1].split()[0].strip())
return same | Returns MP2 same spin energy. | autochem/interfaces/psi_results.py | mp2_same | tommason14/monash_automation | 7 | python | @property
def mp2_same(self):
'\n \n '
same =
for line in self.read():
if ('Same-Spin Energy =' in line):
same = float(line.split('=')[1].split()[0].strip())
return same | @property
def mp2_same(self):
'\n \n '
same =
for line in self.read():
if ('Same-Spin Energy =' in line):
same = float(line.split('=')[1].split()[0].strip())
return same<|docstring|>Returns MP2 same spin energy.<|endoftext|> |
ef5c6d2d39118ace939c23e846fc572d8b07399cdf86a2b7a7c1a348846b1789 | def _mp2_data(self):
'\n Returns data for MP2 calculations: filename, filepath, \n basis set, hf energy, opp spin energy, same spin energy.\n No MP2 data is returned, but should be calculated instead from the \n HF and MP2 correlation energies by the user, as coefficients of \n each spin component will vary depending on the basis set.\n '
return (self.file, self.path, self.method, self.basis, self.hf_energy_for_mp2, 'NA', self.mp2_opp, self.mp2_same) | Returns data for MP2 calculations: filename, filepath,
basis set, hf energy, opp spin energy, same spin energy.
No MP2 data is returned, but should be calculated instead from the
HF and MP2 correlation energies by the user, as coefficients of
each spin component will vary depending on the basis set. | autochem/interfaces/psi_results.py | _mp2_data | tommason14/monash_automation | 7 | python | def _mp2_data(self):
'\n Returns data for MP2 calculations: filename, filepath, \n basis set, hf energy, opp spin energy, same spin energy.\n No MP2 data is returned, but should be calculated instead from the \n HF and MP2 correlation energies by the user, as coefficients of \n each spin component will vary depending on the basis set.\n '
return (self.file, self.path, self.method, self.basis, self.hf_energy_for_mp2, 'NA', self.mp2_opp, self.mp2_same) | def _mp2_data(self):
'\n Returns data for MP2 calculations: filename, filepath, \n basis set, hf energy, opp spin energy, same spin energy.\n No MP2 data is returned, but should be calculated instead from the \n HF and MP2 correlation energies by the user, as coefficients of \n each spin component will vary depending on the basis set.\n '
return (self.file, self.path, self.method, self.basis, self.hf_energy_for_mp2, 'NA', self.mp2_opp, self.mp2_same)<|docstring|>Returns data for MP2 calculations: filename, filepath,
basis set, hf energy, opp spin energy, same spin energy.
No MP2 data is returned, but should be calculated instead from the
HF and MP2 correlation energies by the user, as coefficients of
each spin component will vary depending on the basis set.<|endoftext|> |
40ccf9666dc3c71af165776ace437ab2d832019e1191ca408033518a58752953 | def at_cmdset_creation(self):
'\n Populates the cmdset\n '
super().at_cmdset_creation() | Populates the cmdset | CoC/CoC_Default_CmdSets.py | at_cmdset_creation | macorvalan/MyGame | 0 | python | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation() | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation()<|docstring|>Populates the cmdset<|endoftext|> |
40ccf9666dc3c71af165776ace437ab2d832019e1191ca408033518a58752953 | def at_cmdset_creation(self):
'\n Populates the cmdset\n '
super().at_cmdset_creation() | Populates the cmdset | CoC/CoC_Default_CmdSets.py | at_cmdset_creation | macorvalan/MyGame | 0 | python | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation() | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation()<|docstring|>Populates the cmdset<|endoftext|> |
40ccf9666dc3c71af165776ace437ab2d832019e1191ca408033518a58752953 | def at_cmdset_creation(self):
'\n Populates the cmdset\n '
super().at_cmdset_creation() | Populates the cmdset | CoC/CoC_Default_CmdSets.py | at_cmdset_creation | macorvalan/MyGame | 0 | python | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation() | def at_cmdset_creation(self):
'\n \n '
super().at_cmdset_creation()<|docstring|>Populates the cmdset<|endoftext|> |
dc6b17e1f171c6710371c9a1ef7212dec226ab6c6d99f175fbc8591bac7a64b1 | def at_cmdset_creation(self):
'\n This is the only method defined in a cmdset, called during\n its creation. It should populate the set with command instances.\n\n As and example we just add the empty base `Command` object.\n It prints some info.\n '
super().at_cmdset_creation() | This is the only method defined in a cmdset, called during
its creation. It should populate the set with command instances.
As and example we just add the empty base `Command` object.
It prints some info. | CoC/CoC_Default_CmdSets.py | at_cmdset_creation | macorvalan/MyGame | 0 | python | def at_cmdset_creation(self):
'\n This is the only method defined in a cmdset, called during\n its creation. It should populate the set with command instances.\n\n As and example we just add the empty base `Command` object.\n It prints some info.\n '
super().at_cmdset_creation() | def at_cmdset_creation(self):
'\n This is the only method defined in a cmdset, called during\n its creation. It should populate the set with command instances.\n\n As and example we just add the empty base `Command` object.\n It prints some info.\n '
super().at_cmdset_creation()<|docstring|>This is the only method defined in a cmdset, called during
its creation. It should populate the set with command instances.
As and example we just add the empty base `Command` object.
It prints some info.<|endoftext|> |
764a96d4e4b9f28028d596aa1dd5648e431162e273e268b267dcf3f94f0b63ad | def __init__(self, str_in, error_level='M'):
' Init for QRCode\n\n Calls all methods (steps) required to generate a QR code.\n After all steps, the QR code will be stored as a data matrix.\n To generate an output from the matrix,\n call any method prefixed with "out_".\n '
if (error_level.upper() not in list('LMQH')):
raise ValueError('Invalid error level, use L, M (default), Q or H')
self.err_lvl = error_level.upper()
self.generate_data(str_in)
self.static_matrix = []
for i in range(0, self.width):
self.static_matrix.append([])
for _ in range(0, self.width):
self.static_matrix[i].append(None)
self.add_finder_patterns()
self.add_alignment_patterns()
self.add_timer_patterns()
self.static_matrix[(self.width - 8)][8] = 1
self.add_version_information()
self.generate_data_matrix()
self.merge_matrixes()
self.apply_mask_and_finish_format() | Init for QRCode
Calls all methods (steps) required to generate a QR code.
After all steps, the QR code will be stored as a data matrix.
To generate an output from the matrix,
call any method prefixed with "out_". | NoLQR/__init__.py | __init__ | Jelmerro/NoLQR | 2 | python | def __init__(self, str_in, error_level='M'):
' Init for QRCode\n\n Calls all methods (steps) required to generate a QR code.\n After all steps, the QR code will be stored as a data matrix.\n To generate an output from the matrix,\n call any method prefixed with "out_".\n '
if (error_level.upper() not in list('LMQH')):
raise ValueError('Invalid error level, use L, M (default), Q or H')
self.err_lvl = error_level.upper()
self.generate_data(str_in)
self.static_matrix = []
for i in range(0, self.width):
self.static_matrix.append([])
for _ in range(0, self.width):
self.static_matrix[i].append(None)
self.add_finder_patterns()
self.add_alignment_patterns()
self.add_timer_patterns()
self.static_matrix[(self.width - 8)][8] = 1
self.add_version_information()
self.generate_data_matrix()
self.merge_matrixes()
self.apply_mask_and_finish_format() | def __init__(self, str_in, error_level='M'):
' Init for QRCode\n\n Calls all methods (steps) required to generate a QR code.\n After all steps, the QR code will be stored as a data matrix.\n To generate an output from the matrix,\n call any method prefixed with "out_".\n '
if (error_level.upper() not in list('LMQH')):
raise ValueError('Invalid error level, use L, M (default), Q or H')
self.err_lvl = error_level.upper()
self.generate_data(str_in)
self.static_matrix = []
for i in range(0, self.width):
self.static_matrix.append([])
for _ in range(0, self.width):
self.static_matrix[i].append(None)
self.add_finder_patterns()
self.add_alignment_patterns()
self.add_timer_patterns()
self.static_matrix[(self.width - 8)][8] = 1
self.add_version_information()
self.generate_data_matrix()
self.merge_matrixes()
self.apply_mask_and_finish_format()<|docstring|>Init for QRCode
Calls all methods (steps) required to generate a QR code.
After all steps, the QR code will be stored as a data matrix.
To generate an output from the matrix,
call any method prefixed with "out_".<|endoftext|> |
322d6b9dd63c8cff12ac362d208865cd912876474d7799473273cdb420da4a37 | def encode_input(self, str_in):
' Encodes the input string using different modes\n\n Depending on the result of util.best_mode,\n The input string is encoded with either:\n numeric, alphanumeric, binary or kanji.\n Each of these modes has a different way to encode the data,\n and all of them are implemented below.\n The mode indicator and the character count indicator,\n are added before data, to form the data string.\n '
out = ''
data_length = 0
if (self.mode == 'numeric'):
for group in [str_in[i:(i + 3)] for i in range(0, len(str_in), 3)]:
if (len(group) == 3):
out += '{:010b}'.format(int(group))
if (len(group) == 2):
out += '{:07b}'.format(int(group))
if (len(group) == 1):
out += '{:04b}'.format(int(group))
data_length += len(group)
if (self.mode == 'alphanumeric'):
alpha_codes = []
for group in [str_in[i:(i + 2)] for i in range(0, len(str_in), 2)]:
for character in group:
alpha_codes.append(constants.ALPHA_TABLE[character])
for i in range(0, len(alpha_codes), 2):
if ((i + 1) < len(alpha_codes)):
number = ((alpha_codes[i] * 45) + alpha_codes[(i + 1)])
out += '{:011b}'.format(number)
data_length += 2
else:
out += '{:06b}'.format(alpha_codes[i])
data_length += 1
if (self.mode == 'binary'):
for character in str_in.encode(constants.ENCODING):
out += '{:08b}'.format(character)
data_length += 1
if (self.mode == 'kanji'):
characters = []
for item in str_in:
characters.append(item.encode('shift-jis'))
bytes = ''
for character in characters:
if (len(character.hex()) == 4):
bytes += character.hex()
else:
self.mode = 'binary'
return self.encode_input(str_in)
for group in [bytes[i:(i + 4)] for i in range(0, len(bytes), 4)]:
hex_code = int(group, 16)
subtractor = ''
if ((hex_code > int('8140', 16)) and (hex_code < int('9ffc', 16))):
subtractor = '8140'
elif ((hex_code > int('e040', 16)) and (hex_code < int('ebbf', 16))):
subtractor = 'c140'
else:
self.mode = 'binary'
return self.encode_input(str_in)
hex_code = '{:04x}'.format((hex_code - int(subtractor, 16)))
sig_bit = int(hex_code[:2], 16)
ins_bit = int(hex_code[2:], 16)
hex_code = ((sig_bit * int('c0', 16)) + ins_bit)
out += '{:013b}'.format(hex_code)
data_length += 1
self.version = util.version(self.mode, data_length, self.err_lvl)
return '{}{}{}'.format(constants.MODES[self.mode]['mode_indicator'], util.character_count_indicator(self.mode, data_length, self.version), out) | Encodes the input string using different modes
Depending on the result of util.best_mode,
The input string is encoded with either:
numeric, alphanumeric, binary or kanji.
Each of these modes has a different way to encode the data,
and all of them are implemented below.
The mode indicator and the character count indicator,
are added before data, to form the data string. | NoLQR/__init__.py | encode_input | Jelmerro/NoLQR | 2 | python | def encode_input(self, str_in):
' Encodes the input string using different modes\n\n Depending on the result of util.best_mode,\n The input string is encoded with either:\n numeric, alphanumeric, binary or kanji.\n Each of these modes has a different way to encode the data,\n and all of them are implemented below.\n The mode indicator and the character count indicator,\n are added before data, to form the data string.\n '
out =
data_length = 0
if (self.mode == 'numeric'):
for group in [str_in[i:(i + 3)] for i in range(0, len(str_in), 3)]:
if (len(group) == 3):
out += '{:010b}'.format(int(group))
if (len(group) == 2):
out += '{:07b}'.format(int(group))
if (len(group) == 1):
out += '{:04b}'.format(int(group))
data_length += len(group)
if (self.mode == 'alphanumeric'):
alpha_codes = []
for group in [str_in[i:(i + 2)] for i in range(0, len(str_in), 2)]:
for character in group:
alpha_codes.append(constants.ALPHA_TABLE[character])
for i in range(0, len(alpha_codes), 2):
if ((i + 1) < len(alpha_codes)):
number = ((alpha_codes[i] * 45) + alpha_codes[(i + 1)])
out += '{:011b}'.format(number)
data_length += 2
else:
out += '{:06b}'.format(alpha_codes[i])
data_length += 1
if (self.mode == 'binary'):
for character in str_in.encode(constants.ENCODING):
out += '{:08b}'.format(character)
data_length += 1
if (self.mode == 'kanji'):
characters = []
for item in str_in:
characters.append(item.encode('shift-jis'))
bytes =
for character in characters:
if (len(character.hex()) == 4):
bytes += character.hex()
else:
self.mode = 'binary'
return self.encode_input(str_in)
for group in [bytes[i:(i + 4)] for i in range(0, len(bytes), 4)]:
hex_code = int(group, 16)
subtractor =
if ((hex_code > int('8140', 16)) and (hex_code < int('9ffc', 16))):
subtractor = '8140'
elif ((hex_code > int('e040', 16)) and (hex_code < int('ebbf', 16))):
subtractor = 'c140'
else:
self.mode = 'binary'
return self.encode_input(str_in)
hex_code = '{:04x}'.format((hex_code - int(subtractor, 16)))
sig_bit = int(hex_code[:2], 16)
ins_bit = int(hex_code[2:], 16)
hex_code = ((sig_bit * int('c0', 16)) + ins_bit)
out += '{:013b}'.format(hex_code)
data_length += 1
self.version = util.version(self.mode, data_length, self.err_lvl)
return '{}{}{}'.format(constants.MODES[self.mode]['mode_indicator'], util.character_count_indicator(self.mode, data_length, self.version), out) | def encode_input(self, str_in):
' Encodes the input string using different modes\n\n Depending on the result of util.best_mode,\n The input string is encoded with either:\n numeric, alphanumeric, binary or kanji.\n Each of these modes has a different way to encode the data,\n and all of them are implemented below.\n The mode indicator and the character count indicator,\n are added before data, to form the data string.\n '
out =
data_length = 0
if (self.mode == 'numeric'):
for group in [str_in[i:(i + 3)] for i in range(0, len(str_in), 3)]:
if (len(group) == 3):
out += '{:010b}'.format(int(group))
if (len(group) == 2):
out += '{:07b}'.format(int(group))
if (len(group) == 1):
out += '{:04b}'.format(int(group))
data_length += len(group)
if (self.mode == 'alphanumeric'):
alpha_codes = []
for group in [str_in[i:(i + 2)] for i in range(0, len(str_in), 2)]:
for character in group:
alpha_codes.append(constants.ALPHA_TABLE[character])
for i in range(0, len(alpha_codes), 2):
if ((i + 1) < len(alpha_codes)):
number = ((alpha_codes[i] * 45) + alpha_codes[(i + 1)])
out += '{:011b}'.format(number)
data_length += 2
else:
out += '{:06b}'.format(alpha_codes[i])
data_length += 1
if (self.mode == 'binary'):
for character in str_in.encode(constants.ENCODING):
out += '{:08b}'.format(character)
data_length += 1
if (self.mode == 'kanji'):
characters = []
for item in str_in:
characters.append(item.encode('shift-jis'))
bytes =
for character in characters:
if (len(character.hex()) == 4):
bytes += character.hex()
else:
self.mode = 'binary'
return self.encode_input(str_in)
for group in [bytes[i:(i + 4)] for i in range(0, len(bytes), 4)]:
hex_code = int(group, 16)
subtractor =
if ((hex_code > int('8140', 16)) and (hex_code < int('9ffc', 16))):
subtractor = '8140'
elif ((hex_code > int('e040', 16)) and (hex_code < int('ebbf', 16))):
subtractor = 'c140'
else:
self.mode = 'binary'
return self.encode_input(str_in)
hex_code = '{:04x}'.format((hex_code - int(subtractor, 16)))
sig_bit = int(hex_code[:2], 16)
ins_bit = int(hex_code[2:], 16)
hex_code = ((sig_bit * int('c0', 16)) + ins_bit)
out += '{:013b}'.format(hex_code)
data_length += 1
self.version = util.version(self.mode, data_length, self.err_lvl)
return '{}{}{}'.format(constants.MODES[self.mode]['mode_indicator'], util.character_count_indicator(self.mode, data_length, self.version), out)<|docstring|>Encodes the input string using different modes
Depending on the result of util.best_mode,
The input string is encoded with either:
numeric, alphanumeric, binary or kanji.
Each of these modes has a different way to encode the data,
and all of them are implemented below.
The mode indicator and the character count indicator,
are added before data, to form the data string.<|endoftext|> |
af7d256324ecbbe740e95681c12f1e13a8b0e0caa7524c92a8f9087da431d03a | def generate_data(self, str_in):
" Generates the data from the input string\n\n First picks the best mode and calls encode_input.\n After that, zeros are padded as explained in util.pad_zeros.\n Next the data is split in codewords (each containing 8 bits).\n These are used to generate the data blocks and error blocks.\n The result will be interleaved,\n and some remainer bits are added.\n The amount is always between 0 and 8,\n so 8 are added (overflow bits won't be added anyway).\n "
self.mode = util.best_mode(str_in)
data = self.encode_input(str_in)
self.width = util.width(self.version)
max_bytes = constants.VERSIONS[self.version][self.err_lvl]
data = util.pad_zeros(data, max_bytes)
codewords = [data[i:(i + 8)] for i in range(0, len(data), 8)]
info = constants.ERROR_CORRECTION_BLOCKS[self.version][self.err_lvl]
(data_blocks, error_blocks) = util.generate_blocks(codewords, info)
result = util.interleave_codewords(data_blocks, error_blocks)
self.data = (result + ('0' * 8)) | Generates the data from the input string
First picks the best mode and calls encode_input.
After that, zeros are padded as explained in util.pad_zeros.
Next the data is split in codewords (each containing 8 bits).
These are used to generate the data blocks and error blocks.
The result will be interleaved,
and some remainer bits are added.
The amount is always between 0 and 8,
so 8 are added (overflow bits won't be added anyway). | NoLQR/__init__.py | generate_data | Jelmerro/NoLQR | 2 | python | def generate_data(self, str_in):
" Generates the data from the input string\n\n First picks the best mode and calls encode_input.\n After that, zeros are padded as explained in util.pad_zeros.\n Next the data is split in codewords (each containing 8 bits).\n These are used to generate the data blocks and error blocks.\n The result will be interleaved,\n and some remainer bits are added.\n The amount is always between 0 and 8,\n so 8 are added (overflow bits won't be added anyway).\n "
self.mode = util.best_mode(str_in)
data = self.encode_input(str_in)
self.width = util.width(self.version)
max_bytes = constants.VERSIONS[self.version][self.err_lvl]
data = util.pad_zeros(data, max_bytes)
codewords = [data[i:(i + 8)] for i in range(0, len(data), 8)]
info = constants.ERROR_CORRECTION_BLOCKS[self.version][self.err_lvl]
(data_blocks, error_blocks) = util.generate_blocks(codewords, info)
result = util.interleave_codewords(data_blocks, error_blocks)
self.data = (result + ('0' * 8)) | def generate_data(self, str_in):
" Generates the data from the input string\n\n First picks the best mode and calls encode_input.\n After that, zeros are padded as explained in util.pad_zeros.\n Next the data is split in codewords (each containing 8 bits).\n These are used to generate the data blocks and error blocks.\n The result will be interleaved,\n and some remainer bits are added.\n The amount is always between 0 and 8,\n so 8 are added (overflow bits won't be added anyway).\n "
self.mode = util.best_mode(str_in)
data = self.encode_input(str_in)
self.width = util.width(self.version)
max_bytes = constants.VERSIONS[self.version][self.err_lvl]
data = util.pad_zeros(data, max_bytes)
codewords = [data[i:(i + 8)] for i in range(0, len(data), 8)]
info = constants.ERROR_CORRECTION_BLOCKS[self.version][self.err_lvl]
(data_blocks, error_blocks) = util.generate_blocks(codewords, info)
result = util.interleave_codewords(data_blocks, error_blocks)
self.data = (result + ('0' * 8))<|docstring|>Generates the data from the input string
First picks the best mode and calls encode_input.
After that, zeros are padded as explained in util.pad_zeros.
Next the data is split in codewords (each containing 8 bits).
These are used to generate the data blocks and error blocks.
The result will be interleaved,
and some remainer bits are added.
The amount is always between 0 and 8,
so 8 are added (overflow bits won't be added anyway).<|endoftext|> |
01f9eb7561c51aeb5c8eee594170d73cb01cb2cfbc8f2c52240feda82c58b40a | def add_finder_patterns(self):
' Adds the finder patterns to the matrix\n\n In the top-left, top-right and bottom-left corner,\n a finder pattern is needed.\n This consists of a black 3x3 square,\n with a white border around that,\n with another black border around that.\n This 7x7 pattern has a white line between the data.\n The ranges in the loops below are even bigger,\n because they also reserve space for the format string.\n '
for y in range(0, 9):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range((self.width - 8), self.width):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range(0, 9):
for x in range((self.width - 8), self.width):
self.static_matrix[y][x] = 0
for (base_x, base_y) in [[0, 0], [(self.width - 7), 0], [0, (self.width - 7)]]:
for x in range(base_x, (base_x + 7)):
self.static_matrix[base_y][x] = 1
self.static_matrix[(base_y + 6)][x] = 1
for y in range(base_y, (base_y + 7)):
self.static_matrix[y][base_x] = 1
self.static_matrix[y][(base_x + 6)] = 1
for y in range((base_y + 2), (base_y + 5)):
for x in range((base_x + 2), (base_x + 5)):
self.static_matrix[y][x] = 1 | Adds the finder patterns to the matrix
In the top-left, top-right and bottom-left corner,
a finder pattern is needed.
This consists of a black 3x3 square,
with a white border around that,
with another black border around that.
This 7x7 pattern has a white line between the data.
The ranges in the loops below are even bigger,
because they also reserve space for the format string. | NoLQR/__init__.py | add_finder_patterns | Jelmerro/NoLQR | 2 | python | def add_finder_patterns(self):
' Adds the finder patterns to the matrix\n\n In the top-left, top-right and bottom-left corner,\n a finder pattern is needed.\n This consists of a black 3x3 square,\n with a white border around that,\n with another black border around that.\n This 7x7 pattern has a white line between the data.\n The ranges in the loops below are even bigger,\n because they also reserve space for the format string.\n '
for y in range(0, 9):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range((self.width - 8), self.width):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range(0, 9):
for x in range((self.width - 8), self.width):
self.static_matrix[y][x] = 0
for (base_x, base_y) in [[0, 0], [(self.width - 7), 0], [0, (self.width - 7)]]:
for x in range(base_x, (base_x + 7)):
self.static_matrix[base_y][x] = 1
self.static_matrix[(base_y + 6)][x] = 1
for y in range(base_y, (base_y + 7)):
self.static_matrix[y][base_x] = 1
self.static_matrix[y][(base_x + 6)] = 1
for y in range((base_y + 2), (base_y + 5)):
for x in range((base_x + 2), (base_x + 5)):
self.static_matrix[y][x] = 1 | def add_finder_patterns(self):
' Adds the finder patterns to the matrix\n\n In the top-left, top-right and bottom-left corner,\n a finder pattern is needed.\n This consists of a black 3x3 square,\n with a white border around that,\n with another black border around that.\n This 7x7 pattern has a white line between the data.\n The ranges in the loops below are even bigger,\n because they also reserve space for the format string.\n '
for y in range(0, 9):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range((self.width - 8), self.width):
for x in range(0, 9):
self.static_matrix[y][x] = 0
for y in range(0, 9):
for x in range((self.width - 8), self.width):
self.static_matrix[y][x] = 0
for (base_x, base_y) in [[0, 0], [(self.width - 7), 0], [0, (self.width - 7)]]:
for x in range(base_x, (base_x + 7)):
self.static_matrix[base_y][x] = 1
self.static_matrix[(base_y + 6)][x] = 1
for y in range(base_y, (base_y + 7)):
self.static_matrix[y][base_x] = 1
self.static_matrix[y][(base_x + 6)] = 1
for y in range((base_y + 2), (base_y + 5)):
for x in range((base_x + 2), (base_x + 5)):
self.static_matrix[y][x] = 1<|docstring|>Adds the finder patterns to the matrix
In the top-left, top-right and bottom-left corner,
a finder pattern is needed.
This consists of a black 3x3 square,
with a white border around that,
with another black border around that.
This 7x7 pattern has a white line between the data.
The ranges in the loops below are even bigger,
because they also reserve space for the format string.<|endoftext|> |
f7c33663db4ff1f5dadb02df5eb7f30254f5f0af93143eeb63ca043f0136d086 | def add_alignment_patterns(self):
" Adds the alignment patterns to the matrix\n\n The alignment patterns are added in different locations,\n depending on the version of the qr code.'\n It consists of a black pixel,\n with a white border around that,\n with another black border around that.\n The result is a 5x5 square pattern.\n In constants, a list of numbers is stored.\n This is a list of x/y positions,\n as each number can be either x or y,\n and all combination will receive an alignment pattern.\n The patterns are not added however,\n in any place which would overlap a reserved area.\n "
patterns = constants.VERSIONS[self.version]['alignment']
for base_x in patterns:
for base_y in patterns:
if (not self.static_matrix[base_y][base_x]):
for y in range((base_y - 2), (base_y + 3)):
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[y][x] = 0
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x - 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y - 2)][x] = 1
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x + 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y + 2)][x] = 1
self.static_matrix[base_y][base_x] = 1 | Adds the alignment patterns to the matrix
The alignment patterns are added in different locations,
depending on the version of the qr code.'
It consists of a black pixel,
with a white border around that,
with another black border around that.
The result is a 5x5 square pattern.
In constants, a list of numbers is stored.
This is a list of x/y positions,
as each number can be either x or y,
and all combination will receive an alignment pattern.
The patterns are not added however,
in any place which would overlap a reserved area. | NoLQR/__init__.py | add_alignment_patterns | Jelmerro/NoLQR | 2 | python | def add_alignment_patterns(self):
" Adds the alignment patterns to the matrix\n\n The alignment patterns are added in different locations,\n depending on the version of the qr code.'\n It consists of a black pixel,\n with a white border around that,\n with another black border around that.\n The result is a 5x5 square pattern.\n In constants, a list of numbers is stored.\n This is a list of x/y positions,\n as each number can be either x or y,\n and all combination will receive an alignment pattern.\n The patterns are not added however,\n in any place which would overlap a reserved area.\n "
patterns = constants.VERSIONS[self.version]['alignment']
for base_x in patterns:
for base_y in patterns:
if (not self.static_matrix[base_y][base_x]):
for y in range((base_y - 2), (base_y + 3)):
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[y][x] = 0
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x - 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y - 2)][x] = 1
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x + 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y + 2)][x] = 1
self.static_matrix[base_y][base_x] = 1 | def add_alignment_patterns(self):
" Adds the alignment patterns to the matrix\n\n The alignment patterns are added in different locations,\n depending on the version of the qr code.'\n It consists of a black pixel,\n with a white border around that,\n with another black border around that.\n The result is a 5x5 square pattern.\n In constants, a list of numbers is stored.\n This is a list of x/y positions,\n as each number can be either x or y,\n and all combination will receive an alignment pattern.\n The patterns are not added however,\n in any place which would overlap a reserved area.\n "
patterns = constants.VERSIONS[self.version]['alignment']
for base_x in patterns:
for base_y in patterns:
if (not self.static_matrix[base_y][base_x]):
for y in range((base_y - 2), (base_y + 3)):
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[y][x] = 0
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x - 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y - 2)][x] = 1
for y in range((base_y - 2), (base_y + 3)):
self.static_matrix[y][(base_x + 2)] = 1
for x in range((base_x - 2), (base_x + 3)):
self.static_matrix[(base_y + 2)][x] = 1
self.static_matrix[base_y][base_x] = 1<|docstring|>Adds the alignment patterns to the matrix
The alignment patterns are added in different locations,
depending on the version of the qr code.'
It consists of a black pixel,
with a white border around that,
with another black border around that.
The result is a 5x5 square pattern.
In constants, a list of numbers is stored.
This is a list of x/y positions,
as each number can be either x or y,
and all combination will receive an alignment pattern.
The patterns are not added however,
in any place which would overlap a reserved area.<|endoftext|> |
f23f8f677f56fa73304f8e524051eedefcd4d21ad765efeba2a27b3adc0d3d85 | def add_timer_patterns(self):
' Adds the timer pattern to the matrix\n\n The timer pattern is a dotted line,\n which is added between the finder patterns.\n No conflict calculation with the alignment patterns is done,\n because this dotted line is part of the pattern.\n '
for x in range(6, (self.width - 8), 2):
self.static_matrix[6][x] = 1
self.static_matrix[6][(x + 1)] = 0
for y in range(6, (self.width - 8), 2):
self.static_matrix[y][6] = 1
self.static_matrix[(y + 1)][6] = 0 | Adds the timer pattern to the matrix
The timer pattern is a dotted line,
which is added between the finder patterns.
No conflict calculation with the alignment patterns is done,
because this dotted line is part of the pattern. | NoLQR/__init__.py | add_timer_patterns | Jelmerro/NoLQR | 2 | python | def add_timer_patterns(self):
' Adds the timer pattern to the matrix\n\n The timer pattern is a dotted line,\n which is added between the finder patterns.\n No conflict calculation with the alignment patterns is done,\n because this dotted line is part of the pattern.\n '
for x in range(6, (self.width - 8), 2):
self.static_matrix[6][x] = 1
self.static_matrix[6][(x + 1)] = 0
for y in range(6, (self.width - 8), 2):
self.static_matrix[y][6] = 1
self.static_matrix[(y + 1)][6] = 0 | def add_timer_patterns(self):
' Adds the timer pattern to the matrix\n\n The timer pattern is a dotted line,\n which is added between the finder patterns.\n No conflict calculation with the alignment patterns is done,\n because this dotted line is part of the pattern.\n '
for x in range(6, (self.width - 8), 2):
self.static_matrix[6][x] = 1
self.static_matrix[6][(x + 1)] = 0
for y in range(6, (self.width - 8), 2):
self.static_matrix[y][6] = 1
self.static_matrix[(y + 1)][6] = 0<|docstring|>Adds the timer pattern to the matrix
The timer pattern is a dotted line,
which is added between the finder patterns.
No conflict calculation with the alignment patterns is done,
because this dotted line is part of the pattern.<|endoftext|> |
de6d22025d802a50efe505c4e0c25a7a00365f3082f6c1eb49b6ed51ca4c5313 | def add_version_information(self):
' Adds the version information to the matrix\n\n This is only needed for version 7 and up,\n and consists of a 3x6 area near the finder patterns.\n The bits are added from most significant to least,\n so the index starts at 17 and goes down from there.\n '
if (self.version > 6):
pattern = constants.VERSIONS[self.version]['pattern']
index = 17
for y in range(0, 6):
for x in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1
index = 17
for x in range(0, 6):
for y in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1 | Adds the version information to the matrix
This is only needed for version 7 and up,
and consists of a 3x6 area near the finder patterns.
The bits are added from most significant to least,
so the index starts at 17 and goes down from there. | NoLQR/__init__.py | add_version_information | Jelmerro/NoLQR | 2 | python | def add_version_information(self):
' Adds the version information to the matrix\n\n This is only needed for version 7 and up,\n and consists of a 3x6 area near the finder patterns.\n The bits are added from most significant to least,\n so the index starts at 17 and goes down from there.\n '
if (self.version > 6):
pattern = constants.VERSIONS[self.version]['pattern']
index = 17
for y in range(0, 6):
for x in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1
index = 17
for x in range(0, 6):
for y in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1 | def add_version_information(self):
' Adds the version information to the matrix\n\n This is only needed for version 7 and up,\n and consists of a 3x6 area near the finder patterns.\n The bits are added from most significant to least,\n so the index starts at 17 and goes down from there.\n '
if (self.version > 6):
pattern = constants.VERSIONS[self.version]['pattern']
index = 17
for y in range(0, 6):
for x in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1
index = 17
for x in range(0, 6):
for y in range((self.width - 11), (self.width - 8)):
self.static_matrix[y][x] = int(pattern[index])
index -= 1<|docstring|>Adds the version information to the matrix
This is only needed for version 7 and up,
and consists of a 3x6 area near the finder patterns.
The bits are added from most significant to least,
so the index starts at 17 and goes down from there.<|endoftext|> |
ea8efe92c7c605ac08782dae19ebe0d29794ae4c7d1150130d7d720066de2dd1 | def generate_data_matrix(self):
' Generates the data matrix\n\n The data is added in a zig-zag pattern,\n starting in the bottom right corner.\n Each zig-zag is two bits/pixels wide.\n Once the top is reached, move two to the left,\n and add the data in a zig-zag going down.\n If a reserved bit is found,\n skip it, and add the data bit in the next suitable location.\n This is done for all the data and the entire matrix,\n with one exception for the vertical timing pattern.\n This column is skipped altogether,\n and the zig-zag pattern will continue one bit to the left.\n '
self.data_matrix = []
for i in range(0, self.width):
self.data_matrix.append([])
for _ in range(0, self.width):
self.data_matrix[i].append(None)
for base_x in range((self.width - 1), 0, (- 2)):
for base_y in range((self.width - 1), (- 1), (- 1)):
if (base_x < 8):
x = (base_x - 1)
else:
x = base_x
if ((base_x % 4) == 2):
y = ((self.width - base_y) - 1)
else:
y = base_y
if (self.data and (self.static_matrix[y][x] is None)):
self.data_matrix[y][x] = int(self.data[:1])
self.data = self.data[1:]
if ((x > 0) and self.data and (self.static_matrix[y][(x - 1)] is None)):
self.data_matrix[y][(x - 1)] = int(self.data[:1])
self.data = self.data[1:] | Generates the data matrix
The data is added in a zig-zag pattern,
starting in the bottom right corner.
Each zig-zag is two bits/pixels wide.
Once the top is reached, move two to the left,
and add the data in a zig-zag going down.
If a reserved bit is found,
skip it, and add the data bit in the next suitable location.
This is done for all the data and the entire matrix,
with one exception for the vertical timing pattern.
This column is skipped altogether,
and the zig-zag pattern will continue one bit to the left. | NoLQR/__init__.py | generate_data_matrix | Jelmerro/NoLQR | 2 | python | def generate_data_matrix(self):
' Generates the data matrix\n\n The data is added in a zig-zag pattern,\n starting in the bottom right corner.\n Each zig-zag is two bits/pixels wide.\n Once the top is reached, move two to the left,\n and add the data in a zig-zag going down.\n If a reserved bit is found,\n skip it, and add the data bit in the next suitable location.\n This is done for all the data and the entire matrix,\n with one exception for the vertical timing pattern.\n This column is skipped altogether,\n and the zig-zag pattern will continue one bit to the left.\n '
self.data_matrix = []
for i in range(0, self.width):
self.data_matrix.append([])
for _ in range(0, self.width):
self.data_matrix[i].append(None)
for base_x in range((self.width - 1), 0, (- 2)):
for base_y in range((self.width - 1), (- 1), (- 1)):
if (base_x < 8):
x = (base_x - 1)
else:
x = base_x
if ((base_x % 4) == 2):
y = ((self.width - base_y) - 1)
else:
y = base_y
if (self.data and (self.static_matrix[y][x] is None)):
self.data_matrix[y][x] = int(self.data[:1])
self.data = self.data[1:]
if ((x > 0) and self.data and (self.static_matrix[y][(x - 1)] is None)):
self.data_matrix[y][(x - 1)] = int(self.data[:1])
self.data = self.data[1:] | def generate_data_matrix(self):
' Generates the data matrix\n\n The data is added in a zig-zag pattern,\n starting in the bottom right corner.\n Each zig-zag is two bits/pixels wide.\n Once the top is reached, move two to the left,\n and add the data in a zig-zag going down.\n If a reserved bit is found,\n skip it, and add the data bit in the next suitable location.\n This is done for all the data and the entire matrix,\n with one exception for the vertical timing pattern.\n This column is skipped altogether,\n and the zig-zag pattern will continue one bit to the left.\n '
self.data_matrix = []
for i in range(0, self.width):
self.data_matrix.append([])
for _ in range(0, self.width):
self.data_matrix[i].append(None)
for base_x in range((self.width - 1), 0, (- 2)):
for base_y in range((self.width - 1), (- 1), (- 1)):
if (base_x < 8):
x = (base_x - 1)
else:
x = base_x
if ((base_x % 4) == 2):
y = ((self.width - base_y) - 1)
else:
y = base_y
if (self.data and (self.static_matrix[y][x] is None)):
self.data_matrix[y][x] = int(self.data[:1])
self.data = self.data[1:]
if ((x > 0) and self.data and (self.static_matrix[y][(x - 1)] is None)):
self.data_matrix[y][(x - 1)] = int(self.data[:1])
self.data = self.data[1:]<|docstring|>Generates the data matrix
The data is added in a zig-zag pattern,
starting in the bottom right corner.
Each zig-zag is two bits/pixels wide.
Once the top is reached, move two to the left,
and add the data in a zig-zag going down.
If a reserved bit is found,
skip it, and add the data bit in the next suitable location.
This is done for all the data and the entire matrix,
with one exception for the vertical timing pattern.
This column is skipped altogether,
and the zig-zag pattern will continue one bit to the left.<|endoftext|> |
ee7d7fd588592bd2050ef9de5c2ca6bd58697e978694ee6e789de985b72c9d33 | def merge_matrixes(self):
' Merge the data and the static matrix\n\n When this method is called,\n all patterns are in the static matrix,\n and all data is in the data matrix.\n This method simply merges the two matrixes,\n into a single matrix.\n '
self.matrix = []
for i in range(0, self.width):
self.matrix.append([])
for j in range(0, self.width):
self.matrix[i].append(self.static_matrix[i][j])
for x in range(0, self.width):
for y in range(0, self.width):
if (self.matrix[y][x] is None):
self.matrix[y][x] = self.data_matrix[y][x] | Merge the data and the static matrix
When this method is called,
all patterns are in the static matrix,
and all data is in the data matrix.
This method simply merges the two matrixes,
into a single matrix. | NoLQR/__init__.py | merge_matrixes | Jelmerro/NoLQR | 2 | python | def merge_matrixes(self):
' Merge the data and the static matrix\n\n When this method is called,\n all patterns are in the static matrix,\n and all data is in the data matrix.\n This method simply merges the two matrixes,\n into a single matrix.\n '
self.matrix = []
for i in range(0, self.width):
self.matrix.append([])
for j in range(0, self.width):
self.matrix[i].append(self.static_matrix[i][j])
for x in range(0, self.width):
for y in range(0, self.width):
if (self.matrix[y][x] is None):
self.matrix[y][x] = self.data_matrix[y][x] | def merge_matrixes(self):
' Merge the data and the static matrix\n\n When this method is called,\n all patterns are in the static matrix,\n and all data is in the data matrix.\n This method simply merges the two matrixes,\n into a single matrix.\n '
self.matrix = []
for i in range(0, self.width):
self.matrix.append([])
for j in range(0, self.width):
self.matrix[i].append(self.static_matrix[i][j])
for x in range(0, self.width):
for y in range(0, self.width):
if (self.matrix[y][x] is None):
self.matrix[y][x] = self.data_matrix[y][x]<|docstring|>Merge the data and the static matrix
When this method is called,
all patterns are in the static matrix,
and all data is in the data matrix.
This method simply merges the two matrixes,
into a single matrix.<|endoftext|> |
6d1483b3487ead8e21e6fda760ee76848693a6f3ae314d8293d11df6ad849c99 | def apply_mask_and_finish_format(self):
' Apply mask and finish overall formatting\n\n Each masking pattern is applied separately,\n and the best one is picked.\n This is done by calculating a score,\n for each of the different mask patterns.\n There are four penalty rules for that:\n - Single line with same colored bits (column or row)\n This gives a penalty for each group of 5 or more.\n The penalty is 3 for a group of 5,\n and 1 more for every next same colored bit.\n This is tested for horizontal and vertical lines.\n - 2x2 area of same colored bits\n This gives a penalty for ALL 2x2 groups,\n even if they are part of another group.\n Every 2x2 square has a penalty of 3.\n - Similar bits to a finder pattern (column or row)\n This gives a penalty for all 10111010000 or 00001011101.\n Each time these bits are found, add 40 to the penalty.\n This is tested for horizontal and vertical lines.\n - A large amount of dark or light bits\n If the percentage of dark modules is not near 50,\n add a penalty of 10 for every 5 percent (rounded down).\n This means, 4.9 percent results in 0, but 5.0 in 10.\n\n After calculating the score for all different mask patterns,\n the mask pattern with the lowest score is used.\n The format string was already added in the process,\n because the penalty rules also apply to the format bits.\n '
matrixes = []
scores = []
for m in range(0, 8):
matrixes.append([])
scores.append(0)
for i in range(0, self.width):
matrixes[m].append([])
for j in range(0, self.width):
matrixes[m][i].append(self.matrix[i][j])
masks = [(lambda x, y: (((x + y) % 2) == 0)), (lambda x, y: ((y % 2) == 0)), (lambda x, y: ((x % 3) == 0)), (lambda x, y: (((x + y) % 3) == 0)), (lambda x, y: (((int((y / 2)) + int((x / 3))) % 2) == 0)), (lambda x, y: ((((x * y) % 2) + ((x * y) % 3)) == 0)), (lambda x, y: (((((x * y) % 3) + (x * y)) % 2) == 0)), (lambda x, y: ((((((x * y) % 3) + x) + y) % 2) == 0))]
for m in range(0, 8):
for x in range(0, self.width):
for y in range(0, self.width):
if ((self.data_matrix[y][x] is not None) and masks[m](x, y)):
matrixes[m][y][x] = ((self.data_matrix[y][x] + 1) % 2)
matrixes[m] = util.add_format_info(matrixes[m], self.width, constants.FORMAT_STRING[self.err_lvl][m])
for direction in [0, 1]:
total_black = 0
counter_white = 0
counter_black = 0
ss1 = ''
ss2 = ''
for x_or_y1 in range(0, self.width):
for x_or_y2 in range(0, self.width):
if direction:
current_position = matrixes[m][x_or_y1][x_or_y2]
else:
current_position = matrixes[m][x_or_y2][x_or_y1]
if (current_position == 1):
counter_white = 0
counter_black += 1
total_black += 1
else:
counter_white += 1
counter_black = 0
if ((counter_white == 5) or (counter_black == 5)):
scores[m] += 3
elif ((counter_white > 5) or (counter_black > 5)):
scores[m] += 1
if (current_position == int('10111010000'[len(ss1)])):
ss1 += str(current_position)
if (len(ss1) == 11):
scores[m] += 40
ss1 = ''
else:
ss1 = ''
if (current_position == int('00001011101'[len(ss2)])):
ss2 += str(current_position)
if (len(ss2) == 11):
scores[m] += 40
ss2 = ''
else:
ss2 = ''
for x in range(0, (self.width - 1)):
for y in range(0, (self.width - 1)):
if ((matrixes[m][(y + 1)][x] == 1) and (matrixes[m][(y + 1)][(x + 1)] == 1)):
if ((matrixes[m][y][x] == 1) and (matrixes[m][y][(x + 1)] == 1)):
scores[m] += 3
if ((matrixes[m][(y + 1)][x] == 0) and (matrixes[m][(y + 1)][(x + 1)] == 0)):
if ((matrixes[m][y][x] == 0) and (matrixes[m][y][(x + 1)] == 0)):
scores[m] += 3
percentage = ((total_black / (self.width * self.width)) * 100)
if (percentage > 50):
scores[m] += (int(((percentage - 50) / 5)) * 10)
elif (percentage < 50):
scores[m] += (int(((50 - percentage) / 5)) * 10)
self.matrix = matrixes[scores.index(min(scores))] | Apply mask and finish overall formatting
Each masking pattern is applied separately,
and the best one is picked.
This is done by calculating a score,
for each of the different mask patterns.
There are four penalty rules for that:
- Single line with same colored bits (column or row)
This gives a penalty for each group of 5 or more.
The penalty is 3 for a group of 5,
and 1 more for every next same colored bit.
This is tested for horizontal and vertical lines.
- 2x2 area of same colored bits
This gives a penalty for ALL 2x2 groups,
even if they are part of another group.
Every 2x2 square has a penalty of 3.
- Similar bits to a finder pattern (column or row)
This gives a penalty for all 10111010000 or 00001011101.
Each time these bits are found, add 40 to the penalty.
This is tested for horizontal and vertical lines.
- A large amount of dark or light bits
If the percentage of dark modules is not near 50,
add a penalty of 10 for every 5 percent (rounded down).
This means, 4.9 percent results in 0, but 5.0 in 10.
After calculating the score for all different mask patterns,
the mask pattern with the lowest score is used.
The format string was already added in the process,
because the penalty rules also apply to the format bits. | NoLQR/__init__.py | apply_mask_and_finish_format | Jelmerro/NoLQR | 2 | python | def apply_mask_and_finish_format(self):
' Apply mask and finish overall formatting\n\n Each masking pattern is applied separately,\n and the best one is picked.\n This is done by calculating a score,\n for each of the different mask patterns.\n There are four penalty rules for that:\n - Single line with same colored bits (column or row)\n This gives a penalty for each group of 5 or more.\n The penalty is 3 for a group of 5,\n and 1 more for every next same colored bit.\n This is tested for horizontal and vertical lines.\n - 2x2 area of same colored bits\n This gives a penalty for ALL 2x2 groups,\n even if they are part of another group.\n Every 2x2 square has a penalty of 3.\n - Similar bits to a finder pattern (column or row)\n This gives a penalty for all 10111010000 or 00001011101.\n Each time these bits are found, add 40 to the penalty.\n This is tested for horizontal and vertical lines.\n - A large amount of dark or light bits\n If the percentage of dark modules is not near 50,\n add a penalty of 10 for every 5 percent (rounded down).\n This means, 4.9 percent results in 0, but 5.0 in 10.\n\n After calculating the score for all different mask patterns,\n the mask pattern with the lowest score is used.\n The format string was already added in the process,\n because the penalty rules also apply to the format bits.\n '
matrixes = []
scores = []
for m in range(0, 8):
matrixes.append([])
scores.append(0)
for i in range(0, self.width):
matrixes[m].append([])
for j in range(0, self.width):
matrixes[m][i].append(self.matrix[i][j])
masks = [(lambda x, y: (((x + y) % 2) == 0)), (lambda x, y: ((y % 2) == 0)), (lambda x, y: ((x % 3) == 0)), (lambda x, y: (((x + y) % 3) == 0)), (lambda x, y: (((int((y / 2)) + int((x / 3))) % 2) == 0)), (lambda x, y: ((((x * y) % 2) + ((x * y) % 3)) == 0)), (lambda x, y: (((((x * y) % 3) + (x * y)) % 2) == 0)), (lambda x, y: ((((((x * y) % 3) + x) + y) % 2) == 0))]
for m in range(0, 8):
for x in range(0, self.width):
for y in range(0, self.width):
if ((self.data_matrix[y][x] is not None) and masks[m](x, y)):
matrixes[m][y][x] = ((self.data_matrix[y][x] + 1) % 2)
matrixes[m] = util.add_format_info(matrixes[m], self.width, constants.FORMAT_STRING[self.err_lvl][m])
for direction in [0, 1]:
total_black = 0
counter_white = 0
counter_black = 0
ss1 =
ss2 =
for x_or_y1 in range(0, self.width):
for x_or_y2 in range(0, self.width):
if direction:
current_position = matrixes[m][x_or_y1][x_or_y2]
else:
current_position = matrixes[m][x_or_y2][x_or_y1]
if (current_position == 1):
counter_white = 0
counter_black += 1
total_black += 1
else:
counter_white += 1
counter_black = 0
if ((counter_white == 5) or (counter_black == 5)):
scores[m] += 3
elif ((counter_white > 5) or (counter_black > 5)):
scores[m] += 1
if (current_position == int('10111010000'[len(ss1)])):
ss1 += str(current_position)
if (len(ss1) == 11):
scores[m] += 40
ss1 =
else:
ss1 =
if (current_position == int('00001011101'[len(ss2)])):
ss2 += str(current_position)
if (len(ss2) == 11):
scores[m] += 40
ss2 =
else:
ss2 =
for x in range(0, (self.width - 1)):
for y in range(0, (self.width - 1)):
if ((matrixes[m][(y + 1)][x] == 1) and (matrixes[m][(y + 1)][(x + 1)] == 1)):
if ((matrixes[m][y][x] == 1) and (matrixes[m][y][(x + 1)] == 1)):
scores[m] += 3
if ((matrixes[m][(y + 1)][x] == 0) and (matrixes[m][(y + 1)][(x + 1)] == 0)):
if ((matrixes[m][y][x] == 0) and (matrixes[m][y][(x + 1)] == 0)):
scores[m] += 3
percentage = ((total_black / (self.width * self.width)) * 100)
if (percentage > 50):
scores[m] += (int(((percentage - 50) / 5)) * 10)
elif (percentage < 50):
scores[m] += (int(((50 - percentage) / 5)) * 10)
self.matrix = matrixes[scores.index(min(scores))] | def apply_mask_and_finish_format(self):
' Apply mask and finish overall formatting\n\n Each masking pattern is applied separately,\n and the best one is picked.\n This is done by calculating a score,\n for each of the different mask patterns.\n There are four penalty rules for that:\n - Single line with same colored bits (column or row)\n This gives a penalty for each group of 5 or more.\n The penalty is 3 for a group of 5,\n and 1 more for every next same colored bit.\n This is tested for horizontal and vertical lines.\n - 2x2 area of same colored bits\n This gives a penalty for ALL 2x2 groups,\n even if they are part of another group.\n Every 2x2 square has a penalty of 3.\n - Similar bits to a finder pattern (column or row)\n This gives a penalty for all 10111010000 or 00001011101.\n Each time these bits are found, add 40 to the penalty.\n This is tested for horizontal and vertical lines.\n - A large amount of dark or light bits\n If the percentage of dark modules is not near 50,\n add a penalty of 10 for every 5 percent (rounded down).\n This means, 4.9 percent results in 0, but 5.0 in 10.\n\n After calculating the score for all different mask patterns,\n the mask pattern with the lowest score is used.\n The format string was already added in the process,\n because the penalty rules also apply to the format bits.\n '
matrixes = []
scores = []
for m in range(0, 8):
matrixes.append([])
scores.append(0)
for i in range(0, self.width):
matrixes[m].append([])
for j in range(0, self.width):
matrixes[m][i].append(self.matrix[i][j])
masks = [(lambda x, y: (((x + y) % 2) == 0)), (lambda x, y: ((y % 2) == 0)), (lambda x, y: ((x % 3) == 0)), (lambda x, y: (((x + y) % 3) == 0)), (lambda x, y: (((int((y / 2)) + int((x / 3))) % 2) == 0)), (lambda x, y: ((((x * y) % 2) + ((x * y) % 3)) == 0)), (lambda x, y: (((((x * y) % 3) + (x * y)) % 2) == 0)), (lambda x, y: ((((((x * y) % 3) + x) + y) % 2) == 0))]
for m in range(0, 8):
for x in range(0, self.width):
for y in range(0, self.width):
if ((self.data_matrix[y][x] is not None) and masks[m](x, y)):
matrixes[m][y][x] = ((self.data_matrix[y][x] + 1) % 2)
matrixes[m] = util.add_format_info(matrixes[m], self.width, constants.FORMAT_STRING[self.err_lvl][m])
for direction in [0, 1]:
total_black = 0
counter_white = 0
counter_black = 0
ss1 =
ss2 =
for x_or_y1 in range(0, self.width):
for x_or_y2 in range(0, self.width):
if direction:
current_position = matrixes[m][x_or_y1][x_or_y2]
else:
current_position = matrixes[m][x_or_y2][x_or_y1]
if (current_position == 1):
counter_white = 0
counter_black += 1
total_black += 1
else:
counter_white += 1
counter_black = 0
if ((counter_white == 5) or (counter_black == 5)):
scores[m] += 3
elif ((counter_white > 5) or (counter_black > 5)):
scores[m] += 1
if (current_position == int('10111010000'[len(ss1)])):
ss1 += str(current_position)
if (len(ss1) == 11):
scores[m] += 40
ss1 =
else:
ss1 =
if (current_position == int('00001011101'[len(ss2)])):
ss2 += str(current_position)
if (len(ss2) == 11):
scores[m] += 40
ss2 =
else:
ss2 =
for x in range(0, (self.width - 1)):
for y in range(0, (self.width - 1)):
if ((matrixes[m][(y + 1)][x] == 1) and (matrixes[m][(y + 1)][(x + 1)] == 1)):
if ((matrixes[m][y][x] == 1) and (matrixes[m][y][(x + 1)] == 1)):
scores[m] += 3
if ((matrixes[m][(y + 1)][x] == 0) and (matrixes[m][(y + 1)][(x + 1)] == 0)):
if ((matrixes[m][y][x] == 0) and (matrixes[m][y][(x + 1)] == 0)):
scores[m] += 3
percentage = ((total_black / (self.width * self.width)) * 100)
if (percentage > 50):
scores[m] += (int(((percentage - 50) / 5)) * 10)
elif (percentage < 50):
scores[m] += (int(((50 - percentage) / 5)) * 10)
self.matrix = matrixes[scores.index(min(scores))]<|docstring|>Apply mask and finish overall formatting
Each masking pattern is applied separately,
and the best one is picked.
This is done by calculating a score,
for each of the different mask patterns.
There are four penalty rules for that:
- Single line with same colored bits (column or row)
This gives a penalty for each group of 5 or more.
The penalty is 3 for a group of 5,
and 1 more for every next same colored bit.
This is tested for horizontal and vertical lines.
- 2x2 area of same colored bits
This gives a penalty for ALL 2x2 groups,
even if they are part of another group.
Every 2x2 square has a penalty of 3.
- Similar bits to a finder pattern (column or row)
This gives a penalty for all 10111010000 or 00001011101.
Each time these bits are found, add 40 to the penalty.
This is tested for horizontal and vertical lines.
- A large amount of dark or light bits
If the percentage of dark modules is not near 50,
add a penalty of 10 for every 5 percent (rounded down).
This means, 4.9 percent results in 0, but 5.0 in 10.
After calculating the score for all different mask patterns,
the mask pattern with the lowest score is used.
The format string was already added in the process,
because the penalty rules also apply to the format bits.<|endoftext|> |
869e40bfbbb7626b071246ad7bc0229f49ecb6a87b0aced8e3f7dbe46a7f0a7b | def out_terminal(self, inverted=True):
' Output to terminal\n\n Output the QR Code to the terminal.\n Simply loops over the matrix two lines at the time,\n and prints the suitable character (█, ▄, ▀ or a space).\n '
if inverted:
EMPTY = '█'
TOP = '▄'
BOTTOM = '▀'
FULL = ' '
else:
EMPTY = ' '
TOP = '▀'
BOTTOM = '▄'
FULL = '█'
print((EMPTY * (self.width + 4)))
for row in range(0, self.width, 2):
out = (EMPTY * 2)
for p in range(0, self.width):
if ((row + 1) == self.width):
if self.matrix[row][p]:
out += TOP
else:
out += EMPTY
elif (self.matrix[row][p] and self.matrix[(row + 1)][p]):
out += FULL
elif self.matrix[row][p]:
out += TOP
elif self.matrix[(row + 1)][p]:
out += BOTTOM
else:
out += EMPTY
out += (EMPTY * 2)
print(out)
print((EMPTY * (len(self.matrix) + 4))) | Output to terminal
Output the QR Code to the terminal.
Simply loops over the matrix two lines at the time,
and prints the suitable character (█, ▄, ▀ or a space). | NoLQR/__init__.py | out_terminal | Jelmerro/NoLQR | 2 | python | def out_terminal(self, inverted=True):
' Output to terminal\n\n Output the QR Code to the terminal.\n Simply loops over the matrix two lines at the time,\n and prints the suitable character (█, ▄, ▀ or a space).\n '
if inverted:
EMPTY = '█'
TOP = '▄'
BOTTOM = '▀'
FULL = ' '
else:
EMPTY = ' '
TOP = '▀'
BOTTOM = '▄'
FULL = '█'
print((EMPTY * (self.width + 4)))
for row in range(0, self.width, 2):
out = (EMPTY * 2)
for p in range(0, self.width):
if ((row + 1) == self.width):
if self.matrix[row][p]:
out += TOP
else:
out += EMPTY
elif (self.matrix[row][p] and self.matrix[(row + 1)][p]):
out += FULL
elif self.matrix[row][p]:
out += TOP
elif self.matrix[(row + 1)][p]:
out += BOTTOM
else:
out += EMPTY
out += (EMPTY * 2)
print(out)
print((EMPTY * (len(self.matrix) + 4))) | def out_terminal(self, inverted=True):
' Output to terminal\n\n Output the QR Code to the terminal.\n Simply loops over the matrix two lines at the time,\n and prints the suitable character (█, ▄, ▀ or a space).\n '
if inverted:
EMPTY = '█'
TOP = '▄'
BOTTOM = '▀'
FULL = ' '
else:
EMPTY = ' '
TOP = '▀'
BOTTOM = '▄'
FULL = '█'
print((EMPTY * (self.width + 4)))
for row in range(0, self.width, 2):
out = (EMPTY * 2)
for p in range(0, self.width):
if ((row + 1) == self.width):
if self.matrix[row][p]:
out += TOP
else:
out += EMPTY
elif (self.matrix[row][p] and self.matrix[(row + 1)][p]):
out += FULL
elif self.matrix[row][p]:
out += TOP
elif self.matrix[(row + 1)][p]:
out += BOTTOM
else:
out += EMPTY
out += (EMPTY * 2)
print(out)
print((EMPTY * (len(self.matrix) + 4)))<|docstring|>Output to terminal
Output the QR Code to the terminal.
Simply loops over the matrix two lines at the time,
and prints the suitable character (█, ▄, ▀ or a space).<|endoftext|> |
bcc80184e6bd7098a03404eab3e55d7cfcb7f49168f3db320b20cff225ca354a | def out_svg(self, filename, dark='black', light='white', background='white'):
' Output as an svg\n\n Output the QR Code to an svg file.\n Loops over the matrix, and makes a rect for each square.\n Also makes a colored background.\n Custom colors and sizes can be provided as arguments.\n '
filename = filename.rstrip()
if (not filename.endswith('.svg')):
filename = '{}.svg'.format(filename)
rect = ' <rect x="{}" y="{}" height="{}" width="{}" fill="{}" />\n'
out = '<?xml version="1.0" encoding="UTF-8" ?>\n'
out += '<!-- Generated with NoLQR, QR code generation lighter than an unladen swallow -->\n'
out += '<!-- Visit https://github.com/Jelmerro/NoLQR for updates and details -->\n'
out += '<svg height="{}" width="{}" xmlns="http://www.w3.org/2000/svg" version="1.1">\n'.format((self.width + 4), (self.width + 4))
out += rect.format(0, 0, (self.width + 4), (self.width + 4), background)
for row in range(0, self.width):
for col in range(0, self.width):
out += rect.format((2 + row), (2 + col), 1, 1, (dark if self.matrix[col][row] else light))
with open(filename, 'w') as f:
f.write((out + '</svg>')) | Output as an svg
Output the QR Code to an svg file.
Loops over the matrix, and makes a rect for each square.
Also makes a colored background.
Custom colors and sizes can be provided as arguments. | NoLQR/__init__.py | out_svg | Jelmerro/NoLQR | 2 | python | def out_svg(self, filename, dark='black', light='white', background='white'):
' Output as an svg\n\n Output the QR Code to an svg file.\n Loops over the matrix, and makes a rect for each square.\n Also makes a colored background.\n Custom colors and sizes can be provided as arguments.\n '
filename = filename.rstrip()
if (not filename.endswith('.svg')):
filename = '{}.svg'.format(filename)
rect = ' <rect x="{}" y="{}" height="{}" width="{}" fill="{}" />\n'
out = '<?xml version="1.0" encoding="UTF-8" ?>\n'
out += '<!-- Generated with NoLQR, QR code generation lighter than an unladen swallow -->\n'
out += '<!-- Visit https://github.com/Jelmerro/NoLQR for updates and details -->\n'
out += '<svg height="{}" width="{}" xmlns="http://www.w3.org/2000/svg" version="1.1">\n'.format((self.width + 4), (self.width + 4))
out += rect.format(0, 0, (self.width + 4), (self.width + 4), background)
for row in range(0, self.width):
for col in range(0, self.width):
out += rect.format((2 + row), (2 + col), 1, 1, (dark if self.matrix[col][row] else light))
with open(filename, 'w') as f:
f.write((out + '</svg>')) | def out_svg(self, filename, dark='black', light='white', background='white'):
' Output as an svg\n\n Output the QR Code to an svg file.\n Loops over the matrix, and makes a rect for each square.\n Also makes a colored background.\n Custom colors and sizes can be provided as arguments.\n '
filename = filename.rstrip()
if (not filename.endswith('.svg')):
filename = '{}.svg'.format(filename)
rect = ' <rect x="{}" y="{}" height="{}" width="{}" fill="{}" />\n'
out = '<?xml version="1.0" encoding="UTF-8" ?>\n'
out += '<!-- Generated with NoLQR, QR code generation lighter than an unladen swallow -->\n'
out += '<!-- Visit https://github.com/Jelmerro/NoLQR for updates and details -->\n'
out += '<svg height="{}" width="{}" xmlns="http://www.w3.org/2000/svg" version="1.1">\n'.format((self.width + 4), (self.width + 4))
out += rect.format(0, 0, (self.width + 4), (self.width + 4), background)
for row in range(0, self.width):
for col in range(0, self.width):
out += rect.format((2 + row), (2 + col), 1, 1, (dark if self.matrix[col][row] else light))
with open(filename, 'w') as f:
f.write((out + '</svg>'))<|docstring|>Output as an svg
Output the QR Code to an svg file.
Loops over the matrix, and makes a rect for each square.
Also makes a colored background.
Custom colors and sizes can be provided as arguments.<|endoftext|> |
2b184b5ff2a9b8c33b3d0528b8c99751e206312a6e78ed28b2c1489c0de79e6e | def merge(file1, file2, res='result.csv', k=1):
'\n file1 准确率高 第一个位置的准确个数多\n file2 召回率高 所有位置的准确的个数多\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines) | file1 准确率高 第一个位置的准确个数多
file2 召回率高 所有位置的准确的个数多 | scripts/mer_csv.py | merge | ZhouLigao/PyTorchText | 1,136 | python | def merge(file1, file2, res='result.csv', k=1):
'\n file1 准确率高 第一个位置的准确个数多\n file2 召回率高 所有位置的准确的个数多\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines) | def merge(file1, file2, res='result.csv', k=1):
'\n file1 准确率高 第一个位置的准确个数多\n file2 召回率高 所有位置的准确的个数多\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines)<|docstring|>file1 准确率高 第一个位置的准确个数多
file2 召回率高 所有位置的准确的个数多<|endoftext|> |
7054e4f9601b5595613dea7e3b79957e37925e551432c83995fe2720c0adbef0 | def merge2(file1, file2, res='result.csv', k=1):
'\n file1 准确率高\n file2 召回率高\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
_c1 = d1[key]
_c2 = d2[key]
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines) | file1 准确率高
file2 召回率高 | scripts/mer_csv.py | merge2 | ZhouLigao/PyTorchText | 1,136 | python | def merge2(file1, file2, res='result.csv', k=1):
'\n file1 准确率高\n file2 召回率高\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
_c1 = d1[key]
_c2 = d2[key]
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines) | def merge2(file1, file2, res='result.csv', k=1):
'\n file1 准确率高\n file2 召回率高\n '
with open(file1) as f:
lines1 = f.readlines()
with open(file2) as f:
lines2 = f.readlines()
d1 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines1}
d2 = {_.split(',')[0]: _.strip().split(',')[1:] for _ in lines2}
d = {}
for key in d1:
_c1 = d1[key]
_c2 = d2[key]
i1 = d1[key][:k]
i2 = [_ for _ in d2[key] if (_ not in i1)][:(5 - k)]
d[key] = (i1 + i2)
lines = [([_] + _2) for (_, _2) in d.iteritems()]
write_csv(res, lines)<|docstring|>file1 准确率高
file2 召回率高<|endoftext|> |
be90cec0c3fd52b401543b618b761b4d8b42cb70f3d99384e632fa73e122e876 | def assignText(self, accessible, text):
"\n set the accessible's text\n "
procedurelogger.action(('set %s text to "%s"' % (accessible, text)))
try:
accessible.text = text
except NotImplementedError:
pass | set the accessible's text | test/testers/winforms/trackbar/trackbarframe.py | assignText | terrajobst/uia2atk | 1 | python | def assignText(self, accessible, text):
"\n \n "
procedurelogger.action(('set %s text to "%s"' % (accessible, text)))
try:
accessible.text = text
except NotImplementedError:
pass | def assignText(self, accessible, text):
"\n \n "
procedurelogger.action(('set %s text to "%s"' % (accessible, text)))
try:
accessible.text = text
except NotImplementedError:
pass<|docstring|>set the accessible's text<|endoftext|> |
13c95a14be5d2429a7297d6c10aa4799dbb699189bdb1d80d0344173e3b00864 | def assignValue(self, accessible, value):
"\n set the accessible's value\n "
procedurelogger.action(('set %s\'s value to "%s"' % (accessible, value)))
accessible.value = value | set the accessible's value | test/testers/winforms/trackbar/trackbarframe.py | assignValue | terrajobst/uia2atk | 1 | python | def assignValue(self, accessible, value):
"\n \n "
procedurelogger.action(('set %s\'s value to "%s"' % (accessible, value)))
accessible.value = value | def assignValue(self, accessible, value):
"\n \n "
procedurelogger.action(('set %s\'s value to "%s"' % (accessible, value)))
accessible.value = value<|docstring|>set the accessible's value<|endoftext|> |
89ce2c4f2e12690760d1ddb9bc640eae46ab361468e7337c8741d32e32bd753e | def assertValue(self, accessible, expected_value):
'assert that the actual value '
procedurelogger.action(('Assert that the value of %s is what we expect' % accessible))
actual_value = accessible.value
procedurelogger.expectedResult(('%s value is %s' % (accessible, expected_value)))
assert (actual_value == expected_value), ('Value was %s, expected %s' % (actual_value, expected_value)) | assert that the actual value | test/testers/winforms/trackbar/trackbarframe.py | assertValue | terrajobst/uia2atk | 1 | python | def assertValue(self, accessible, expected_value):
' '
procedurelogger.action(('Assert that the value of %s is what we expect' % accessible))
actual_value = accessible.value
procedurelogger.expectedResult(('%s value is %s' % (accessible, expected_value)))
assert (actual_value == expected_value), ('Value was %s, expected %s' % (actual_value, expected_value)) | def assertValue(self, accessible, expected_value):
' '
procedurelogger.action(('Assert that the value of %s is what we expect' % accessible))
actual_value = accessible.value
procedurelogger.expectedResult(('%s value is %s' % (accessible, expected_value)))
assert (actual_value == expected_value), ('Value was %s, expected %s' % (actual_value, expected_value))<|docstring|>assert that the actual value<|endoftext|> |
a9d625b1c9a311c497f77244508a850a923da5f8d399e5fdc9b5fb21c4aa6412 | def assertText(self, accessible, expected_text):
'assert that the actual text '
procedurelogger.action(('Assert that the text of %s is what we expect' % accessible))
actual_text = accessible.text
procedurelogger.expectedResult(('%s text is "%s"' % (accessible, expected_text)))
assert (actual_text == expected_text), ('Text was "%s", expected "%s"' % (actual_text, expected_text)) | assert that the actual text | test/testers/winforms/trackbar/trackbarframe.py | assertText | terrajobst/uia2atk | 1 | python | def assertText(self, accessible, expected_text):
' '
procedurelogger.action(('Assert that the text of %s is what we expect' % accessible))
actual_text = accessible.text
procedurelogger.expectedResult(('%s text is "%s"' % (accessible, expected_text)))
assert (actual_text == expected_text), ('Text was "%s", expected "%s"' % (actual_text, expected_text)) | def assertText(self, accessible, expected_text):
' '
procedurelogger.action(('Assert that the text of %s is what we expect' % accessible))
actual_text = accessible.text
procedurelogger.expectedResult(('%s text is "%s"' % (accessible, expected_text)))
assert (actual_text == expected_text), ('Text was "%s", expected "%s"' % (actual_text, expected_text))<|docstring|>assert that the actual text<|endoftext|> |
5ba5a08fbe2ab01ac0a3260a645eb2861076ed752cc3e3c8652c901be31f2636 | @views.route('/static/user.css')
@cache.cached(timeout=300)
def custom_css():
'\n Custom CSS Handler route\n :return:\n '
return Response(get_config('css'), mimetype='text/css') | Custom CSS Handler route
:return: | CTFd/views.py | custom_css | mayoneko/CTFd | 2 | python | @views.route('/static/user.css')
@cache.cached(timeout=300)
def custom_css():
'\n Custom CSS Handler route\n :return:\n '
return Response(get_config('css'), mimetype='text/css') | @views.route('/static/user.css')
@cache.cached(timeout=300)
def custom_css():
'\n Custom CSS Handler route\n :return:\n '
return Response(get_config('css'), mimetype='text/css')<|docstring|>Custom CSS Handler route
:return:<|endoftext|> |
7811d8895cb7587dfbf8c8aa79b3f44a69bb7333bba0c94406577d28ad3f5bbb | @views.route('/', defaults={'route': 'index'})
@views.route('/<path:route>')
def static_html(route):
'\n Route in charge of routing users to Pages.\n :param route:\n :return:\n '
page = get_page(route)
if (page is None):
abort(404)
else:
if (page.auth_required and (authed() is False)):
return redirect(url_for('auth.login', next=request.path))
return render_template('page.html', content=markdown(page.content)) | Route in charge of routing users to Pages.
:param route:
:return: | CTFd/views.py | static_html | mayoneko/CTFd | 2 | python | @views.route('/', defaults={'route': 'index'})
@views.route('/<path:route>')
def static_html(route):
'\n Route in charge of routing users to Pages.\n :param route:\n :return:\n '
page = get_page(route)
if (page is None):
abort(404)
else:
if (page.auth_required and (authed() is False)):
return redirect(url_for('auth.login', next=request.path))
return render_template('page.html', content=markdown(page.content)) | @views.route('/', defaults={'route': 'index'})
@views.route('/<path:route>')
def static_html(route):
'\n Route in charge of routing users to Pages.\n :param route:\n :return:\n '
page = get_page(route)
if (page is None):
abort(404)
else:
if (page.auth_required and (authed() is False)):
return redirect(url_for('auth.login', next=request.path))
return render_template('page.html', content=markdown(page.content))<|docstring|>Route in charge of routing users to Pages.
:param route:
:return:<|endoftext|> |
53636adc9069d9b91d9c7563a00831bca367424bdbe6a62b21c6197a8438e7f8 | @views.route('/files', defaults={'path': ''})
@views.route('/files/<path:path>')
def files(path):
'\n Route in charge of dealing with making sure that CTF challenges are only accessible during the competition.\n :param path:\n :return:\n '
f = Files.query.filter_by(location=path).first_or_404()
if (f.type == 'challenge'):
if current_user.authed():
if (current_user.is_admin() is False):
if (not ctftime()):
abort(403)
else:
abort(403)
uploader = get_uploader()
try:
return uploader.download(f.location)
except IOError:
abort(404) | Route in charge of dealing with making sure that CTF challenges are only accessible during the competition.
:param path:
:return: | CTFd/views.py | files | mayoneko/CTFd | 2 | python | @views.route('/files', defaults={'path': })
@views.route('/files/<path:path>')
def files(path):
'\n Route in charge of dealing with making sure that CTF challenges are only accessible during the competition.\n :param path:\n :return:\n '
f = Files.query.filter_by(location=path).first_or_404()
if (f.type == 'challenge'):
if current_user.authed():
if (current_user.is_admin() is False):
if (not ctftime()):
abort(403)
else:
abort(403)
uploader = get_uploader()
try:
return uploader.download(f.location)
except IOError:
abort(404) | @views.route('/files', defaults={'path': })
@views.route('/files/<path:path>')
def files(path):
'\n Route in charge of dealing with making sure that CTF challenges are only accessible during the competition.\n :param path:\n :return:\n '
f = Files.query.filter_by(location=path).first_or_404()
if (f.type == 'challenge'):
if current_user.authed():
if (current_user.is_admin() is False):
if (not ctftime()):
abort(403)
else:
abort(403)
uploader = get_uploader()
try:
return uploader.download(f.location)
except IOError:
abort(404)<|docstring|>Route in charge of dealing with making sure that CTF challenges are only accessible during the competition.
:param path:
:return:<|endoftext|> |
cbe19811d3186f2d30a2bd9cacbddc67e6b748d35c457b95bee3c4b9518c8c4e | @views.route('/themes/<theme>/static/<path:path>')
def themes(theme, path):
'\n General static file handler\n :param theme:\n :param path:\n :return:\n '
filename = safe_join(app.root_path, 'themes', theme, 'static', path)
if os.path.isfile(filename):
return send_file(filename)
else:
abort(404) | General static file handler
:param theme:
:param path:
:return: | CTFd/views.py | themes | mayoneko/CTFd | 2 | python | @views.route('/themes/<theme>/static/<path:path>')
def themes(theme, path):
'\n General static file handler\n :param theme:\n :param path:\n :return:\n '
filename = safe_join(app.root_path, 'themes', theme, 'static', path)
if os.path.isfile(filename):
return send_file(filename)
else:
abort(404) | @views.route('/themes/<theme>/static/<path:path>')
def themes(theme, path):
'\n General static file handler\n :param theme:\n :param path:\n :return:\n '
filename = safe_join(app.root_path, 'themes', theme, 'static', path)
if os.path.isfile(filename):
return send_file(filename)
else:
abort(404)<|docstring|>General static file handler
:param theme:
:param path:
:return:<|endoftext|> |
df042cbe8934fba84149e33c040e62b840b2b008a061e47eac006f1f8e53eeec | def psql_insert_copy(table, conn, keys, data_iter):
'Uses postgres insert method to convert a dataframe to a csv and\n copy directly into a sql table. Refs:\n https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method\n https://www.postgresql.org/docs/current/static/sql-copy.html\n '
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join(('"{}"'.format(k) for k in keys))
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
cur.copy_expert(sql=sql, file=s_buf) | Uses postgres insert method to convert a dataframe to a csv and
copy directly into a sql table. Refs:
https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
https://www.postgresql.org/docs/current/static/sql-copy.html | 341_build_week_rapid_bq_to_pg.py | psql_insert_copy | Nburkhal/DS-work | 0 | python | def psql_insert_copy(table, conn, keys, data_iter):
'Uses postgres insert method to convert a dataframe to a csv and\n copy directly into a sql table. Refs:\n https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method\n https://www.postgresql.org/docs/current/static/sql-copy.html\n '
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join(('"{}"'.format(k) for k in keys))
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
cur.copy_expert(sql=sql, file=s_buf) | def psql_insert_copy(table, conn, keys, data_iter):
'Uses postgres insert method to convert a dataframe to a csv and\n copy directly into a sql table. Refs:\n https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method\n https://www.postgresql.org/docs/current/static/sql-copy.html\n '
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join(('"{}"'.format(k) for k in keys))
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)<|docstring|>Uses postgres insert method to convert a dataframe to a csv and
copy directly into a sql table. Refs:
https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
https://www.postgresql.org/docs/current/static/sql-copy.html<|endoftext|> |
b53c6aa1b0eba8e153f982bda3263c5243578c8cb3076c5bf69bfa098abcfe04 | def __call__(self, xi, order=0):
'Evaluate the path at given position.'
ret = [poly.derivative(order)(xi) for poly in self._polys]
return np.array(ret).T | Evaluate the path at given position. | toppra/simplepath.py | __call__ | johnwason/toppra | 342 | python | def __call__(self, xi, order=0):
ret = [poly.derivative(order)(xi) for poly in self._polys]
return np.array(ret).T | def __call__(self, xi, order=0):
ret = [poly.derivative(order)(xi) for poly in self._polys]
return np.array(ret).T<|docstring|>Evaluate the path at given position.<|endoftext|> |
31245b8657574939986e18bcb3abb90ec810ab078d5140f44708a47c6681b5e2 | def test_EncodeInteractionEffectsTransformer_unexpected_values(self):
"\n this test makes sure that any unexpected values raises an assertion error\n (that's what `possible_values` is supposed to solve, so the user should never see new values\n "
titanic_data = TestHelper.get_titanic_data()
transformer = EncodeInteractionEffectsTransformer(columns=['Pclass', 'Sex'])
transformer.fit_transform(data_x=titanic_data)
titanic_data.loc[(0, 'Pclass')] = 4
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=titanic_data))) | this test makes sure that any unexpected values raises an assertion error
(that's what `possible_values` is supposed to solve, so the user should never see new values | tests/test_Transformers.py | test_EncodeInteractionEffectsTransformer_unexpected_values | shane-kercheval/oo-learning | 1 | python | def test_EncodeInteractionEffectsTransformer_unexpected_values(self):
"\n this test makes sure that any unexpected values raises an assertion error\n (that's what `possible_values` is supposed to solve, so the user should never see new values\n "
titanic_data = TestHelper.get_titanic_data()
transformer = EncodeInteractionEffectsTransformer(columns=['Pclass', 'Sex'])
transformer.fit_transform(data_x=titanic_data)
titanic_data.loc[(0, 'Pclass')] = 4
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=titanic_data))) | def test_EncodeInteractionEffectsTransformer_unexpected_values(self):
"\n this test makes sure that any unexpected values raises an assertion error\n (that's what `possible_values` is supposed to solve, so the user should never see new values\n "
titanic_data = TestHelper.get_titanic_data()
transformer = EncodeInteractionEffectsTransformer(columns=['Pclass', 'Sex'])
transformer.fit_transform(data_x=titanic_data)
titanic_data.loc[(0, 'Pclass')] = 4
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=titanic_data)))<|docstring|>this test makes sure that any unexpected values raises an assertion error
(that's what `possible_values` is supposed to solve, so the user should never see new values<|endoftext|> |
301eda1c995273450711f513baa840246c8fb5e503bacf05badd12bca5079262 | def test_transformations_TitanicDataset_test_various_conditions(self):
'\n Test:\n - At times there will be numeric columns that are actually categorical (e.g. 0/1)\n that we will need to specify\n - Categoric imputation\n - Test imputing only categoric, or only numeric\n - test full pipeline\n '
data = TestHelper.get_titanic_data()
test_splitter = ClassificationStratifiedDataSplitter(holdout_ratio=0.05)
(training_indexes, test_indexes) = test_splitter.split(target_values=data.Survived)
train_data = data.iloc[training_indexes]
test_data = data.iloc[test_indexes]
indexes_of_null_train = {column: train_data[column].isnull().values for column in data.columns.values}
indexes_of_null_test = {column: test_data[column].isnull().values for column in data.columns.values}
pipeline = TransformerPipeline(transformations=[RemoveColumnsTransformer(['PassengerId', 'Name', 'Ticket', 'Cabin']), CategoricConverterTransformer(['Pclass', 'SibSp', 'Parch']), ImputationTransformer(), DummyEncodeTransformer(CategoricalEncoding.ONE_HOT)])
transformed_training = pipeline.fit_transform(data_x=train_data)
assert (transformed_training.columns.values.tolist() == ['Survived', 'Age', 'Fare', 'Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex_female', 'Sex_male', 'SibSp_0', 'SibSp_1', 'SibSp_2', 'SibSp_3', 'SibSp_4', 'SibSp_5', 'SibSp_8', 'Parch_0', 'Parch_1', 'Parch_2', 'Parch_3', 'Parch_4', 'Parch_5', 'Parch_6', 'Embarked_C', 'Embarked_Q', 'Embarked_S'])
assert (train_data.isnull().sum().sum() > 0)
assert (transformed_training.isnull().sum().sum() == 0)
expected_imputed_age = train_data.Age.median()
assert all((transformed_training[indexes_of_null_train['Age']]['Age'] == expected_imputed_age))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_S'] == 1))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_C'] == 0))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_Q'] == 0))
transformed_test = pipeline.transform(data_x=test_data)
assert (transformed_test.columns.values.tolist() == transformed_training.columns.values.tolist())
assert (test_data.isnull().sum().sum() > 0)
assert (transformed_test.isnull().sum().sum() == 0)
assert all((transformed_test[indexes_of_null_test['Age']]['Age'] == expected_imputed_age)) | Test:
- At times there will be numeric columns that are actually categorical (e.g. 0/1)
that we will need to specify
- Categoric imputation
- Test imputing only categoric, or only numeric
- test full pipeline | tests/test_Transformers.py | test_transformations_TitanicDataset_test_various_conditions | shane-kercheval/oo-learning | 1 | python | def test_transformations_TitanicDataset_test_various_conditions(self):
'\n Test:\n - At times there will be numeric columns that are actually categorical (e.g. 0/1)\n that we will need to specify\n - Categoric imputation\n - Test imputing only categoric, or only numeric\n - test full pipeline\n '
data = TestHelper.get_titanic_data()
test_splitter = ClassificationStratifiedDataSplitter(holdout_ratio=0.05)
(training_indexes, test_indexes) = test_splitter.split(target_values=data.Survived)
train_data = data.iloc[training_indexes]
test_data = data.iloc[test_indexes]
indexes_of_null_train = {column: train_data[column].isnull().values for column in data.columns.values}
indexes_of_null_test = {column: test_data[column].isnull().values for column in data.columns.values}
pipeline = TransformerPipeline(transformations=[RemoveColumnsTransformer(['PassengerId', 'Name', 'Ticket', 'Cabin']), CategoricConverterTransformer(['Pclass', 'SibSp', 'Parch']), ImputationTransformer(), DummyEncodeTransformer(CategoricalEncoding.ONE_HOT)])
transformed_training = pipeline.fit_transform(data_x=train_data)
assert (transformed_training.columns.values.tolist() == ['Survived', 'Age', 'Fare', 'Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex_female', 'Sex_male', 'SibSp_0', 'SibSp_1', 'SibSp_2', 'SibSp_3', 'SibSp_4', 'SibSp_5', 'SibSp_8', 'Parch_0', 'Parch_1', 'Parch_2', 'Parch_3', 'Parch_4', 'Parch_5', 'Parch_6', 'Embarked_C', 'Embarked_Q', 'Embarked_S'])
assert (train_data.isnull().sum().sum() > 0)
assert (transformed_training.isnull().sum().sum() == 0)
expected_imputed_age = train_data.Age.median()
assert all((transformed_training[indexes_of_null_train['Age']]['Age'] == expected_imputed_age))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_S'] == 1))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_C'] == 0))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_Q'] == 0))
transformed_test = pipeline.transform(data_x=test_data)
assert (transformed_test.columns.values.tolist() == transformed_training.columns.values.tolist())
assert (test_data.isnull().sum().sum() > 0)
assert (transformed_test.isnull().sum().sum() == 0)
assert all((transformed_test[indexes_of_null_test['Age']]['Age'] == expected_imputed_age)) | def test_transformations_TitanicDataset_test_various_conditions(self):
'\n Test:\n - At times there will be numeric columns that are actually categorical (e.g. 0/1)\n that we will need to specify\n - Categoric imputation\n - Test imputing only categoric, or only numeric\n - test full pipeline\n '
data = TestHelper.get_titanic_data()
test_splitter = ClassificationStratifiedDataSplitter(holdout_ratio=0.05)
(training_indexes, test_indexes) = test_splitter.split(target_values=data.Survived)
train_data = data.iloc[training_indexes]
test_data = data.iloc[test_indexes]
indexes_of_null_train = {column: train_data[column].isnull().values for column in data.columns.values}
indexes_of_null_test = {column: test_data[column].isnull().values for column in data.columns.values}
pipeline = TransformerPipeline(transformations=[RemoveColumnsTransformer(['PassengerId', 'Name', 'Ticket', 'Cabin']), CategoricConverterTransformer(['Pclass', 'SibSp', 'Parch']), ImputationTransformer(), DummyEncodeTransformer(CategoricalEncoding.ONE_HOT)])
transformed_training = pipeline.fit_transform(data_x=train_data)
assert (transformed_training.columns.values.tolist() == ['Survived', 'Age', 'Fare', 'Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex_female', 'Sex_male', 'SibSp_0', 'SibSp_1', 'SibSp_2', 'SibSp_3', 'SibSp_4', 'SibSp_5', 'SibSp_8', 'Parch_0', 'Parch_1', 'Parch_2', 'Parch_3', 'Parch_4', 'Parch_5', 'Parch_6', 'Embarked_C', 'Embarked_Q', 'Embarked_S'])
assert (train_data.isnull().sum().sum() > 0)
assert (transformed_training.isnull().sum().sum() == 0)
expected_imputed_age = train_data.Age.median()
assert all((transformed_training[indexes_of_null_train['Age']]['Age'] == expected_imputed_age))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_S'] == 1))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_C'] == 0))
assert all((transformed_training[indexes_of_null_train['Embarked']]['Embarked_Q'] == 0))
transformed_test = pipeline.transform(data_x=test_data)
assert (transformed_test.columns.values.tolist() == transformed_training.columns.values.tolist())
assert (test_data.isnull().sum().sum() > 0)
assert (transformed_test.isnull().sum().sum() == 0)
assert all((transformed_test[indexes_of_null_test['Age']]['Age'] == expected_imputed_age))<|docstring|>Test:
- At times there will be numeric columns that are actually categorical (e.g. 0/1)
that we will need to specify
- Categoric imputation
- Test imputing only categoric, or only numeric
- test full pipeline<|endoftext|> |
95519e6eabb240c82a49604725f141bae8733041b9c6164c2bb5a93be2c69b4e | def test_StatelessTransformer(self):
'\n Create a StatelessTransformer that does the same thing as RemoveColumnsTransformer so that we can\n duplicate the test and ensure we get the same values. i.e. we should be indifferent towards methods\n '
data = TestHelper.get_insurance_data()
def test_remove_columns(columns_to_remove):
def remove_columns_helper(data_to_transform: pd.DataFrame):
return data_to_transform.drop(columns=columns_to_remove)
remove_column_transformer = StatelessTransformer(custom_function=remove_columns_helper)
new_data = remove_column_transformer.fit_transform(data_x=data)
assert all((new_data.columns.values == [column for column in data.columns.values if (column not in columns_to_remove)]))
self.assertRaises(BaseException, (lambda : test_remove_columns(columns_to_remove=['expensess'])))
for x in data.columns.values:
test_remove_columns(columns_to_remove=[x])
for index in range(1, len(data.columns.values)):
test_remove_columns(columns_to_remove=list(data.columns.values[0:(index + 1)])) | Create a StatelessTransformer that does the same thing as RemoveColumnsTransformer so that we can
duplicate the test and ensure we get the same values. i.e. we should be indifferent towards methods | tests/test_Transformers.py | test_StatelessTransformer | shane-kercheval/oo-learning | 1 | python | def test_StatelessTransformer(self):
'\n Create a StatelessTransformer that does the same thing as RemoveColumnsTransformer so that we can\n duplicate the test and ensure we get the same values. i.e. we should be indifferent towards methods\n '
data = TestHelper.get_insurance_data()
def test_remove_columns(columns_to_remove):
def remove_columns_helper(data_to_transform: pd.DataFrame):
return data_to_transform.drop(columns=columns_to_remove)
remove_column_transformer = StatelessTransformer(custom_function=remove_columns_helper)
new_data = remove_column_transformer.fit_transform(data_x=data)
assert all((new_data.columns.values == [column for column in data.columns.values if (column not in columns_to_remove)]))
self.assertRaises(BaseException, (lambda : test_remove_columns(columns_to_remove=['expensess'])))
for x in data.columns.values:
test_remove_columns(columns_to_remove=[x])
for index in range(1, len(data.columns.values)):
test_remove_columns(columns_to_remove=list(data.columns.values[0:(index + 1)])) | def test_StatelessTransformer(self):
'\n Create a StatelessTransformer that does the same thing as RemoveColumnsTransformer so that we can\n duplicate the test and ensure we get the same values. i.e. we should be indifferent towards methods\n '
data = TestHelper.get_insurance_data()
def test_remove_columns(columns_to_remove):
def remove_columns_helper(data_to_transform: pd.DataFrame):
return data_to_transform.drop(columns=columns_to_remove)
remove_column_transformer = StatelessTransformer(custom_function=remove_columns_helper)
new_data = remove_column_transformer.fit_transform(data_x=data)
assert all((new_data.columns.values == [column for column in data.columns.values if (column not in columns_to_remove)]))
self.assertRaises(BaseException, (lambda : test_remove_columns(columns_to_remove=['expensess'])))
for x in data.columns.values:
test_remove_columns(columns_to_remove=[x])
for index in range(1, len(data.columns.values)):
test_remove_columns(columns_to_remove=list(data.columns.values[0:(index + 1)]))<|docstring|>Create a StatelessTransformer that does the same thing as RemoveColumnsTransformer so that we can
duplicate the test and ensure we get the same values. i.e. we should be indifferent towards methods<|endoftext|> |
564c45b1df4297551229d883a97c9999dff39f27305bfc734796adb0d189d218 | def test_CenterScaleTransformer_column_all_same_values(self):
'\n the standard deviation of a column containing all of the same number is 0, which creates a problem\n because we divide by the standard deviation (i.e. 0) which gives NaN values.\n in this case, if there is no standard deviation, all of the valuse should simply be 0 for\n Center/Scaling around a mean of 0\n '
data = TestHelper.get_housing_data()
data['longitude'] = ([1] * len(data))
assert all((data.longitude.values == 1))
assert (data.drop(columns='total_bedrooms').isna().sum().sum() == 0)
target_variable = 'median_house_value'
(training_set, _, test_set, _) = TestHelper.split_train_holdout_regression(data, target_variable)
transformer = CenterScaleTransformer()
transformed_training = transformer.fit_transform(data_x=training_set.copy())
assert (transformed_training.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_training.longitude == 0))
transformed_test = transformer.transform(data_x=test_set.copy())
assert (transformed_test.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_test.longitude == 0))
test_set.loc[(3396, 'longitude')] = 2
assert (not all((test_set.longitude == 1)))
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=test_set.copy()))) | the standard deviation of a column containing all of the same number is 0, which creates a problem
because we divide by the standard deviation (i.e. 0) which gives NaN values.
in this case, if there is no standard deviation, all of the valuse should simply be 0 for
Center/Scaling around a mean of 0 | tests/test_Transformers.py | test_CenterScaleTransformer_column_all_same_values | shane-kercheval/oo-learning | 1 | python | def test_CenterScaleTransformer_column_all_same_values(self):
'\n the standard deviation of a column containing all of the same number is 0, which creates a problem\n because we divide by the standard deviation (i.e. 0) which gives NaN values.\n in this case, if there is no standard deviation, all of the valuse should simply be 0 for\n Center/Scaling around a mean of 0\n '
data = TestHelper.get_housing_data()
data['longitude'] = ([1] * len(data))
assert all((data.longitude.values == 1))
assert (data.drop(columns='total_bedrooms').isna().sum().sum() == 0)
target_variable = 'median_house_value'
(training_set, _, test_set, _) = TestHelper.split_train_holdout_regression(data, target_variable)
transformer = CenterScaleTransformer()
transformed_training = transformer.fit_transform(data_x=training_set.copy())
assert (transformed_training.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_training.longitude == 0))
transformed_test = transformer.transform(data_x=test_set.copy())
assert (transformed_test.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_test.longitude == 0))
test_set.loc[(3396, 'longitude')] = 2
assert (not all((test_set.longitude == 1)))
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=test_set.copy()))) | def test_CenterScaleTransformer_column_all_same_values(self):
'\n the standard deviation of a column containing all of the same number is 0, which creates a problem\n because we divide by the standard deviation (i.e. 0) which gives NaN values.\n in this case, if there is no standard deviation, all of the valuse should simply be 0 for\n Center/Scaling around a mean of 0\n '
data = TestHelper.get_housing_data()
data['longitude'] = ([1] * len(data))
assert all((data.longitude.values == 1))
assert (data.drop(columns='total_bedrooms').isna().sum().sum() == 0)
target_variable = 'median_house_value'
(training_set, _, test_set, _) = TestHelper.split_train_holdout_regression(data, target_variable)
transformer = CenterScaleTransformer()
transformed_training = transformer.fit_transform(data_x=training_set.copy())
assert (transformed_training.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_training.longitude == 0))
transformed_test = transformer.transform(data_x=test_set.copy())
assert (transformed_test.drop(columns='total_bedrooms').isna().sum().sum() == 0)
assert all((transformed_test.longitude == 0))
test_set.loc[(3396, 'longitude')] = 2
assert (not all((test_set.longitude == 1)))
self.assertRaises(AssertionError, (lambda : transformer.transform(data_x=test_set.copy())))<|docstring|>the standard deviation of a column containing all of the same number is 0, which creates a problem
because we divide by the standard deviation (i.e. 0) which gives NaN values.
in this case, if there is no standard deviation, all of the valuse should simply be 0 for
Center/Scaling around a mean of 0<|endoftext|> |
6bf0115b598ec0b94bc85e3859635a12d4a72cae70822c423fdc250055348b71 | def __init__(self, version_id: str, tx_fee: int, agent_addr_to_name: Dict[(Address, str)], currency_id_to_name: Dict[(str, str)], good_id_to_name: Dict[(str, str)]):
'\n Instantiate a game configuration.\n\n :param version_id: the version of the game.\n :param tx_fee: the fee for a transaction.\n :param agent_addr_to_name: a dictionary mapping agent addresses to agent names (as strings).\n :param currency_id_to_name: the mapping of currency id to name.\n :param good_id_to_name: the mapping of good id to name.\n '
self._version_id = version_id
self._tx_fee = tx_fee
self._agent_addr_to_name = agent_addr_to_name
self._currency_id_to_name = currency_id_to_name
self._good_id_to_name = good_id_to_name
self._contract_address = None
self._check_consistency() | Instantiate a game configuration.
:param version_id: the version of the game.
:param tx_fee: the fee for a transaction.
:param agent_addr_to_name: a dictionary mapping agent addresses to agent names (as strings).
:param currency_id_to_name: the mapping of currency id to name.
:param good_id_to_name: the mapping of good id to name. | packages/fetchai/skills/tac_control/game.py | __init__ | bryanchriswhite/agents-aea | 126 | python | def __init__(self, version_id: str, tx_fee: int, agent_addr_to_name: Dict[(Address, str)], currency_id_to_name: Dict[(str, str)], good_id_to_name: Dict[(str, str)]):
'\n Instantiate a game configuration.\n\n :param version_id: the version of the game.\n :param tx_fee: the fee for a transaction.\n :param agent_addr_to_name: a dictionary mapping agent addresses to agent names (as strings).\n :param currency_id_to_name: the mapping of currency id to name.\n :param good_id_to_name: the mapping of good id to name.\n '
self._version_id = version_id
self._tx_fee = tx_fee
self._agent_addr_to_name = agent_addr_to_name
self._currency_id_to_name = currency_id_to_name
self._good_id_to_name = good_id_to_name
self._contract_address = None
self._check_consistency() | def __init__(self, version_id: str, tx_fee: int, agent_addr_to_name: Dict[(Address, str)], currency_id_to_name: Dict[(str, str)], good_id_to_name: Dict[(str, str)]):
'\n Instantiate a game configuration.\n\n :param version_id: the version of the game.\n :param tx_fee: the fee for a transaction.\n :param agent_addr_to_name: a dictionary mapping agent addresses to agent names (as strings).\n :param currency_id_to_name: the mapping of currency id to name.\n :param good_id_to_name: the mapping of good id to name.\n '
self._version_id = version_id
self._tx_fee = tx_fee
self._agent_addr_to_name = agent_addr_to_name
self._currency_id_to_name = currency_id_to_name
self._good_id_to_name = good_id_to_name
self._contract_address = None
self._check_consistency()<|docstring|>Instantiate a game configuration.
:param version_id: the version of the game.
:param tx_fee: the fee for a transaction.
:param agent_addr_to_name: a dictionary mapping agent addresses to agent names (as strings).
:param currency_id_to_name: the mapping of currency id to name.
:param good_id_to_name: the mapping of good id to name.<|endoftext|> |
dfea2d638b2aea6e29b56f91e550c337975324654c56a46c47e282863922f235 | @property
def version_id(self) -> str:
'Agent number of a TAC instance.'
return self._version_id | Agent number of a TAC instance. | packages/fetchai/skills/tac_control/game.py | version_id | bryanchriswhite/agents-aea | 126 | python | @property
def version_id(self) -> str:
return self._version_id | @property
def version_id(self) -> str:
return self._version_id<|docstring|>Agent number of a TAC instance.<|endoftext|> |
66126cfac11284df9bf6bf3a30f410eec121ac0f3064b781dc1159488a639795 | @property
def fee_by_currency_id(self) -> Dict[(str, int)]:
'Transaction fee for the TAC instance.'
return {next(iter(self.currency_id_to_name.keys())): self._tx_fee} | Transaction fee for the TAC instance. | packages/fetchai/skills/tac_control/game.py | fee_by_currency_id | bryanchriswhite/agents-aea | 126 | python | @property
def fee_by_currency_id(self) -> Dict[(str, int)]:
return {next(iter(self.currency_id_to_name.keys())): self._tx_fee} | @property
def fee_by_currency_id(self) -> Dict[(str, int)]:
return {next(iter(self.currency_id_to_name.keys())): self._tx_fee}<|docstring|>Transaction fee for the TAC instance.<|endoftext|> |
2d42f1072840be7f9c09257dc48fa1fe8814309dc864ed7c71e40eb012a3bd24 | @property
def agent_addr_to_name(self) -> Dict[(Address, str)]:
'Map agent addresses to names.'
return self._agent_addr_to_name | Map agent addresses to names. | packages/fetchai/skills/tac_control/game.py | agent_addr_to_name | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_name(self) -> Dict[(Address, str)]:
return self._agent_addr_to_name | @property
def agent_addr_to_name(self) -> Dict[(Address, str)]:
return self._agent_addr_to_name<|docstring|>Map agent addresses to names.<|endoftext|> |
91d84a70a4dd873b23cec58f2cf1ffca6b2a31cfe10bbb373f9b98a6e80b225e | @property
def currency_id_to_name(self) -> Dict[(str, str)]:
'Map currency ids to names.'
return self._currency_id_to_name | Map currency ids to names. | packages/fetchai/skills/tac_control/game.py | currency_id_to_name | bryanchriswhite/agents-aea | 126 | python | @property
def currency_id_to_name(self) -> Dict[(str, str)]:
return self._currency_id_to_name | @property
def currency_id_to_name(self) -> Dict[(str, str)]:
return self._currency_id_to_name<|docstring|>Map currency ids to names.<|endoftext|> |
33743f02df1667053e14de8cec009fbcaaab8cf9a528ad0100049307d971a477 | @property
def good_id_to_name(self) -> Dict[(str, str)]:
'Map good ids to names.'
return self._good_id_to_name | Map good ids to names. | packages/fetchai/skills/tac_control/game.py | good_id_to_name | bryanchriswhite/agents-aea | 126 | python | @property
def good_id_to_name(self) -> Dict[(str, str)]:
return self._good_id_to_name | @property
def good_id_to_name(self) -> Dict[(str, str)]:
return self._good_id_to_name<|docstring|>Map good ids to names.<|endoftext|> |
afca6d9e17f77c5ea45d0d57c823a4e204e2f65e1c122f4d48174aca90cc8f75 | @property
def has_contract_address(self) -> bool:
'Check if contract address is present.'
return (self._contract_address is not None) | Check if contract address is present. | packages/fetchai/skills/tac_control/game.py | has_contract_address | bryanchriswhite/agents-aea | 126 | python | @property
def has_contract_address(self) -> bool:
return (self._contract_address is not None) | @property
def has_contract_address(self) -> bool:
return (self._contract_address is not None)<|docstring|>Check if contract address is present.<|endoftext|> |
701dd2bea4a083369a7d8129554ba8fc72e347f6e6fedef33e54bf097432527d | @property
def contract_address(self) -> str:
'Get the contract address for the game.'
if (self._contract_address is None):
raise AEAEnforceError('Contract_address not set yet!')
return self._contract_address | Get the contract address for the game. | packages/fetchai/skills/tac_control/game.py | contract_address | bryanchriswhite/agents-aea | 126 | python | @property
def contract_address(self) -> str:
if (self._contract_address is None):
raise AEAEnforceError('Contract_address not set yet!')
return self._contract_address | @property
def contract_address(self) -> str:
if (self._contract_address is None):
raise AEAEnforceError('Contract_address not set yet!')
return self._contract_address<|docstring|>Get the contract address for the game.<|endoftext|> |
325bba863b7a392988648787831944516c94fd2e2b71817d13e359c7b0e477fa | @contract_address.setter
def contract_address(self, contract_address: str) -> None:
'Set the contract address for the game.'
enforce((self._contract_address is None), 'Contract_address already set!')
self._contract_address = contract_address | Set the contract address for the game. | packages/fetchai/skills/tac_control/game.py | contract_address | bryanchriswhite/agents-aea | 126 | python | @contract_address.setter
def contract_address(self, contract_address: str) -> None:
enforce((self._contract_address is None), 'Contract_address already set!')
self._contract_address = contract_address | @contract_address.setter
def contract_address(self, contract_address: str) -> None:
enforce((self._contract_address is None), 'Contract_address already set!')
self._contract_address = contract_address<|docstring|>Set the contract address for the game.<|endoftext|> |
b18bc1b4f08a901ffd2b1d19f455d2f9fa870159fad54f718b72e7da3685d37d | def _check_consistency(self) -> None:
'\n Check the consistency of the game configuration.\n\n :raises: AEAEnforceError: if some constraint is not satisfied.\n '
if (self.version_id is None):
raise AEAEnforceError('A version id must be set.')
enforce((self._tx_fee >= 0), 'Tx fee must be non-negative.')
enforce((len(self.agent_addr_to_name) >= 2), 'Must have at least two agents.')
enforce((len(self.good_id_to_name) >= 2), 'Must have at least two goods.')
enforce((len(self.currency_id_to_name) == 1), 'Must have exactly one currency.')
enforce((next(iter(self.currency_id_to_name)) not in self.good_id_to_name), 'Currency id and good ids cannot overlap.') | Check the consistency of the game configuration.
:raises: AEAEnforceError: if some constraint is not satisfied. | packages/fetchai/skills/tac_control/game.py | _check_consistency | bryanchriswhite/agents-aea | 126 | python | def _check_consistency(self) -> None:
'\n Check the consistency of the game configuration.\n\n :raises: AEAEnforceError: if some constraint is not satisfied.\n '
if (self.version_id is None):
raise AEAEnforceError('A version id must be set.')
enforce((self._tx_fee >= 0), 'Tx fee must be non-negative.')
enforce((len(self.agent_addr_to_name) >= 2), 'Must have at least two agents.')
enforce((len(self.good_id_to_name) >= 2), 'Must have at least two goods.')
enforce((len(self.currency_id_to_name) == 1), 'Must have exactly one currency.')
enforce((next(iter(self.currency_id_to_name)) not in self.good_id_to_name), 'Currency id and good ids cannot overlap.') | def _check_consistency(self) -> None:
'\n Check the consistency of the game configuration.\n\n :raises: AEAEnforceError: if some constraint is not satisfied.\n '
if (self.version_id is None):
raise AEAEnforceError('A version id must be set.')
enforce((self._tx_fee >= 0), 'Tx fee must be non-negative.')
enforce((len(self.agent_addr_to_name) >= 2), 'Must have at least two agents.')
enforce((len(self.good_id_to_name) >= 2), 'Must have at least two goods.')
enforce((len(self.currency_id_to_name) == 1), 'Must have exactly one currency.')
enforce((next(iter(self.currency_id_to_name)) not in self.good_id_to_name), 'Currency id and good ids cannot overlap.')<|docstring|>Check the consistency of the game configuration.
:raises: AEAEnforceError: if some constraint is not satisfied.<|endoftext|> |
8dcb71cc8bcc8911d1e4bbbe7f8fd77e21ab336c2d3b2380a4b39e06ac555164 | def __init__(self, agent_addr_to_currency_endowments: Dict[(Address, CurrencyEndowment)], agent_addr_to_exchange_params: Dict[(Address, ExchangeParams)], agent_addr_to_good_endowments: Dict[(Address, GoodEndowment)], agent_addr_to_utility_params: Dict[(Address, UtilityParams)], good_id_to_eq_prices: Dict[(GoodId, float)], agent_addr_to_eq_good_holdings: Dict[(Address, EquilibriumGoodHoldings)], agent_addr_to_eq_currency_holdings: Dict[(Address, EquilibriumCurrencyHoldings)]):
'\n Instantiate a game initialization.\n\n :param agent_addr_to_currency_endowments: the currency endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the currency id.\n :param agent_addr_to_exchange_params: the exchange params representing the exchange rate the agents use between currencies.\n :param agent_addr_to_good_endowments: the good endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the good id.\n :param agent_addr_to_utility_params: the utility params representing the preferences of the agents.\n :param good_id_to_eq_prices: the competitive equilibrium prices of the goods. A list.\n :param agent_addr_to_eq_good_holdings: the competitive equilibrium good holdings of the agents.\n :param agent_addr_to_eq_currency_holdings: the competitive equilibrium money holdings of the agents.\n '
self._agent_addr_to_currency_endowments = agent_addr_to_currency_endowments
self._agent_addr_to_exchange_params = agent_addr_to_exchange_params
self._agent_addr_to_good_endowments = agent_addr_to_good_endowments
self._agent_addr_to_utility_params = agent_addr_to_utility_params
self._good_id_to_eq_prices = good_id_to_eq_prices
self._agent_addr_to_eq_good_holdings = agent_addr_to_eq_good_holdings
self._agent_addr_to_eq_currency_holdings = agent_addr_to_eq_currency_holdings
self._check_consistency() | Instantiate a game initialization.
:param agent_addr_to_currency_endowments: the currency endowments of the agents. A nested dict where the outer key is the agent id
and the inner key is the currency id.
:param agent_addr_to_exchange_params: the exchange params representing the exchange rate the agents use between currencies.
:param agent_addr_to_good_endowments: the good endowments of the agents. A nested dict where the outer key is the agent id
and the inner key is the good id.
:param agent_addr_to_utility_params: the utility params representing the preferences of the agents.
:param good_id_to_eq_prices: the competitive equilibrium prices of the goods. A list.
:param agent_addr_to_eq_good_holdings: the competitive equilibrium good holdings of the agents.
:param agent_addr_to_eq_currency_holdings: the competitive equilibrium money holdings of the agents. | packages/fetchai/skills/tac_control/game.py | __init__ | bryanchriswhite/agents-aea | 126 | python | def __init__(self, agent_addr_to_currency_endowments: Dict[(Address, CurrencyEndowment)], agent_addr_to_exchange_params: Dict[(Address, ExchangeParams)], agent_addr_to_good_endowments: Dict[(Address, GoodEndowment)], agent_addr_to_utility_params: Dict[(Address, UtilityParams)], good_id_to_eq_prices: Dict[(GoodId, float)], agent_addr_to_eq_good_holdings: Dict[(Address, EquilibriumGoodHoldings)], agent_addr_to_eq_currency_holdings: Dict[(Address, EquilibriumCurrencyHoldings)]):
'\n Instantiate a game initialization.\n\n :param agent_addr_to_currency_endowments: the currency endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the currency id.\n :param agent_addr_to_exchange_params: the exchange params representing the exchange rate the agents use between currencies.\n :param agent_addr_to_good_endowments: the good endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the good id.\n :param agent_addr_to_utility_params: the utility params representing the preferences of the agents.\n :param good_id_to_eq_prices: the competitive equilibrium prices of the goods. A list.\n :param agent_addr_to_eq_good_holdings: the competitive equilibrium good holdings of the agents.\n :param agent_addr_to_eq_currency_holdings: the competitive equilibrium money holdings of the agents.\n '
self._agent_addr_to_currency_endowments = agent_addr_to_currency_endowments
self._agent_addr_to_exchange_params = agent_addr_to_exchange_params
self._agent_addr_to_good_endowments = agent_addr_to_good_endowments
self._agent_addr_to_utility_params = agent_addr_to_utility_params
self._good_id_to_eq_prices = good_id_to_eq_prices
self._agent_addr_to_eq_good_holdings = agent_addr_to_eq_good_holdings
self._agent_addr_to_eq_currency_holdings = agent_addr_to_eq_currency_holdings
self._check_consistency() | def __init__(self, agent_addr_to_currency_endowments: Dict[(Address, CurrencyEndowment)], agent_addr_to_exchange_params: Dict[(Address, ExchangeParams)], agent_addr_to_good_endowments: Dict[(Address, GoodEndowment)], agent_addr_to_utility_params: Dict[(Address, UtilityParams)], good_id_to_eq_prices: Dict[(GoodId, float)], agent_addr_to_eq_good_holdings: Dict[(Address, EquilibriumGoodHoldings)], agent_addr_to_eq_currency_holdings: Dict[(Address, EquilibriumCurrencyHoldings)]):
'\n Instantiate a game initialization.\n\n :param agent_addr_to_currency_endowments: the currency endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the currency id.\n :param agent_addr_to_exchange_params: the exchange params representing the exchange rate the agents use between currencies.\n :param agent_addr_to_good_endowments: the good endowments of the agents. A nested dict where the outer key is the agent id\n and the inner key is the good id.\n :param agent_addr_to_utility_params: the utility params representing the preferences of the agents.\n :param good_id_to_eq_prices: the competitive equilibrium prices of the goods. A list.\n :param agent_addr_to_eq_good_holdings: the competitive equilibrium good holdings of the agents.\n :param agent_addr_to_eq_currency_holdings: the competitive equilibrium money holdings of the agents.\n '
self._agent_addr_to_currency_endowments = agent_addr_to_currency_endowments
self._agent_addr_to_exchange_params = agent_addr_to_exchange_params
self._agent_addr_to_good_endowments = agent_addr_to_good_endowments
self._agent_addr_to_utility_params = agent_addr_to_utility_params
self._good_id_to_eq_prices = good_id_to_eq_prices
self._agent_addr_to_eq_good_holdings = agent_addr_to_eq_good_holdings
self._agent_addr_to_eq_currency_holdings = agent_addr_to_eq_currency_holdings
self._check_consistency()<|docstring|>Instantiate a game initialization.
:param agent_addr_to_currency_endowments: the currency endowments of the agents. A nested dict where the outer key is the agent id
and the inner key is the currency id.
:param agent_addr_to_exchange_params: the exchange params representing the exchange rate the agents use between currencies.
:param agent_addr_to_good_endowments: the good endowments of the agents. A nested dict where the outer key is the agent id
and the inner key is the good id.
:param agent_addr_to_utility_params: the utility params representing the preferences of the agents.
:param good_id_to_eq_prices: the competitive equilibrium prices of the goods. A list.
:param agent_addr_to_eq_good_holdings: the competitive equilibrium good holdings of the agents.
:param agent_addr_to_eq_currency_holdings: the competitive equilibrium money holdings of the agents.<|endoftext|> |
6e4f3f460955900ebb6c1ac884d6bcb54f3a2f3db3c8cebd54b867d723fc042d | @property
def agent_addr_to_currency_endowments(self) -> Dict[(Address, CurrencyEndowment)]:
'Get currency endowments of agents.'
return self._agent_addr_to_currency_endowments | Get currency endowments of agents. | packages/fetchai/skills/tac_control/game.py | agent_addr_to_currency_endowments | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_currency_endowments(self) -> Dict[(Address, CurrencyEndowment)]:
return self._agent_addr_to_currency_endowments | @property
def agent_addr_to_currency_endowments(self) -> Dict[(Address, CurrencyEndowment)]:
return self._agent_addr_to_currency_endowments<|docstring|>Get currency endowments of agents.<|endoftext|> |
d0a8317c7dcd4a3138044fe8220f72b26098bbe25586186906ccf19f5e590ffc | @property
def agent_addr_to_exchange_params(self) -> Dict[(Address, ExchangeParams)]:
'Get exchange params of agents.'
return self._agent_addr_to_exchange_params | Get exchange params of agents. | packages/fetchai/skills/tac_control/game.py | agent_addr_to_exchange_params | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_exchange_params(self) -> Dict[(Address, ExchangeParams)]:
return self._agent_addr_to_exchange_params | @property
def agent_addr_to_exchange_params(self) -> Dict[(Address, ExchangeParams)]:
return self._agent_addr_to_exchange_params<|docstring|>Get exchange params of agents.<|endoftext|> |
207eea6ec66877c7df21ff89920e83ee4f2502bc6ee09572c60dd997bc1d48c6 | @property
def agent_addr_to_good_endowments(self) -> Dict[(Address, GoodEndowment)]:
'Get good endowments of the agents.'
return self._agent_addr_to_good_endowments | Get good endowments of the agents. | packages/fetchai/skills/tac_control/game.py | agent_addr_to_good_endowments | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_good_endowments(self) -> Dict[(Address, GoodEndowment)]:
return self._agent_addr_to_good_endowments | @property
def agent_addr_to_good_endowments(self) -> Dict[(Address, GoodEndowment)]:
return self._agent_addr_to_good_endowments<|docstring|>Get good endowments of the agents.<|endoftext|> |
3ac0c8dbb5d1ec8ee8bfa31f8db75b9b6a5fbe0c28c5f82637b3a7080e106f2d | @property
def agent_addr_to_utility_params(self) -> Dict[(Address, UtilityParams)]:
'Get utility parameters of agents.'
return self._agent_addr_to_utility_params | Get utility parameters of agents. | packages/fetchai/skills/tac_control/game.py | agent_addr_to_utility_params | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_utility_params(self) -> Dict[(Address, UtilityParams)]:
return self._agent_addr_to_utility_params | @property
def agent_addr_to_utility_params(self) -> Dict[(Address, UtilityParams)]:
return self._agent_addr_to_utility_params<|docstring|>Get utility parameters of agents.<|endoftext|> |
7833a1b7f97460751e0f248772135c27d8f6b00d4dfc518fe83a50250c687240 | @property
def good_id_to_eq_prices(self) -> Dict[(GoodId, float)]:
'Get theoretical equilibrium prices (a benchmark).'
return self._good_id_to_eq_prices | Get theoretical equilibrium prices (a benchmark). | packages/fetchai/skills/tac_control/game.py | good_id_to_eq_prices | bryanchriswhite/agents-aea | 126 | python | @property
def good_id_to_eq_prices(self) -> Dict[(GoodId, float)]:
return self._good_id_to_eq_prices | @property
def good_id_to_eq_prices(self) -> Dict[(GoodId, float)]:
return self._good_id_to_eq_prices<|docstring|>Get theoretical equilibrium prices (a benchmark).<|endoftext|> |
17e29d908677f658abe138d06dd87aa3d7216241c723b81b10aade838f1ef055 | @property
def agent_addr_to_eq_good_holdings(self) -> Dict[(Address, EquilibriumGoodHoldings)]:
'Get theoretical equilibrium good holdings (a benchmark).'
return self._agent_addr_to_eq_good_holdings | Get theoretical equilibrium good holdings (a benchmark). | packages/fetchai/skills/tac_control/game.py | agent_addr_to_eq_good_holdings | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_eq_good_holdings(self) -> Dict[(Address, EquilibriumGoodHoldings)]:
return self._agent_addr_to_eq_good_holdings | @property
def agent_addr_to_eq_good_holdings(self) -> Dict[(Address, EquilibriumGoodHoldings)]:
return self._agent_addr_to_eq_good_holdings<|docstring|>Get theoretical equilibrium good holdings (a benchmark).<|endoftext|> |
67a62096ddbaa6792b1b3caf1f7be178aa88a5b7a5345cd73b42c59231692549 | @property
def agent_addr_to_eq_currency_holdings(self) -> Dict[(Address, EquilibriumCurrencyHoldings)]:
'Get theoretical equilibrium currency holdings (a benchmark).'
return self._agent_addr_to_eq_currency_holdings | Get theoretical equilibrium currency holdings (a benchmark). | packages/fetchai/skills/tac_control/game.py | agent_addr_to_eq_currency_holdings | bryanchriswhite/agents-aea | 126 | python | @property
def agent_addr_to_eq_currency_holdings(self) -> Dict[(Address, EquilibriumCurrencyHoldings)]:
return self._agent_addr_to_eq_currency_holdings | @property
def agent_addr_to_eq_currency_holdings(self) -> Dict[(Address, EquilibriumCurrencyHoldings)]:
return self._agent_addr_to_eq_currency_holdings<|docstring|>Get theoretical equilibrium currency holdings (a benchmark).<|endoftext|> |
dfceaa679a1928f3d78806cdcb9ef235214e19562bf5dcebb81afd4d268d7955 | def _check_consistency(self) -> None:
'Check the consistency of the game configuration.'
enforce(all(((c_e >= 0) for currency_endowments in self.agent_addr_to_currency_endowments.values() for c_e in currency_endowments.values())), 'Currency endowments must be non-negative.')
enforce(all(((p > 0) for params in self.agent_addr_to_exchange_params.values() for p in params.values())), 'ExchangeParams must be strictly positive.')
enforce(all(((g_e > 0) for good_endowments in self.agent_addr_to_good_endowments.values() for g_e in good_endowments.values())), 'Good endowments must be strictly positive.')
enforce(all(((p > 0) for params in self.agent_addr_to_utility_params.values() for p in params.values())), 'UtilityParams must be strictly positive.')
enforce((len(self.agent_addr_to_good_endowments.keys()) == len(self.agent_addr_to_currency_endowments.keys())), 'Length of endowments must be the same.')
enforce((len(self.agent_addr_to_exchange_params.keys()) == len(self.agent_addr_to_utility_params.keys())), 'Length of params must be the same.')
enforce(all(((len(self.good_id_to_eq_prices.values()) == len(eq_good_holdings)) for eq_good_holdings in self.agent_addr_to_eq_good_holdings.values())), 'Length of eq_prices and an element of eq_good_holdings must be the same.')
enforce((len(self.agent_addr_to_eq_good_holdings.values()) == len(self.agent_addr_to_eq_currency_holdings.values())), 'Length of eq_good_holdings and eq_currency_holdings must be the same.')
enforce(all(((len(self.agent_addr_to_exchange_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_currency_endowments.items())), 'Dimensions for exchange_params and currency_endowments rows must be the same.')
enforce(all(((len(self.agent_addr_to_utility_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_good_endowments.items())), 'Dimensions for utility_params and good_endowments rows must be the same.') | Check the consistency of the game configuration. | packages/fetchai/skills/tac_control/game.py | _check_consistency | bryanchriswhite/agents-aea | 126 | python | def _check_consistency(self) -> None:
enforce(all(((c_e >= 0) for currency_endowments in self.agent_addr_to_currency_endowments.values() for c_e in currency_endowments.values())), 'Currency endowments must be non-negative.')
enforce(all(((p > 0) for params in self.agent_addr_to_exchange_params.values() for p in params.values())), 'ExchangeParams must be strictly positive.')
enforce(all(((g_e > 0) for good_endowments in self.agent_addr_to_good_endowments.values() for g_e in good_endowments.values())), 'Good endowments must be strictly positive.')
enforce(all(((p > 0) for params in self.agent_addr_to_utility_params.values() for p in params.values())), 'UtilityParams must be strictly positive.')
enforce((len(self.agent_addr_to_good_endowments.keys()) == len(self.agent_addr_to_currency_endowments.keys())), 'Length of endowments must be the same.')
enforce((len(self.agent_addr_to_exchange_params.keys()) == len(self.agent_addr_to_utility_params.keys())), 'Length of params must be the same.')
enforce(all(((len(self.good_id_to_eq_prices.values()) == len(eq_good_holdings)) for eq_good_holdings in self.agent_addr_to_eq_good_holdings.values())), 'Length of eq_prices and an element of eq_good_holdings must be the same.')
enforce((len(self.agent_addr_to_eq_good_holdings.values()) == len(self.agent_addr_to_eq_currency_holdings.values())), 'Length of eq_good_holdings and eq_currency_holdings must be the same.')
enforce(all(((len(self.agent_addr_to_exchange_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_currency_endowments.items())), 'Dimensions for exchange_params and currency_endowments rows must be the same.')
enforce(all(((len(self.agent_addr_to_utility_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_good_endowments.items())), 'Dimensions for utility_params and good_endowments rows must be the same.') | def _check_consistency(self) -> None:
enforce(all(((c_e >= 0) for currency_endowments in self.agent_addr_to_currency_endowments.values() for c_e in currency_endowments.values())), 'Currency endowments must be non-negative.')
enforce(all(((p > 0) for params in self.agent_addr_to_exchange_params.values() for p in params.values())), 'ExchangeParams must be strictly positive.')
enforce(all(((g_e > 0) for good_endowments in self.agent_addr_to_good_endowments.values() for g_e in good_endowments.values())), 'Good endowments must be strictly positive.')
enforce(all(((p > 0) for params in self.agent_addr_to_utility_params.values() for p in params.values())), 'UtilityParams must be strictly positive.')
enforce((len(self.agent_addr_to_good_endowments.keys()) == len(self.agent_addr_to_currency_endowments.keys())), 'Length of endowments must be the same.')
enforce((len(self.agent_addr_to_exchange_params.keys()) == len(self.agent_addr_to_utility_params.keys())), 'Length of params must be the same.')
enforce(all(((len(self.good_id_to_eq_prices.values()) == len(eq_good_holdings)) for eq_good_holdings in self.agent_addr_to_eq_good_holdings.values())), 'Length of eq_prices and an element of eq_good_holdings must be the same.')
enforce((len(self.agent_addr_to_eq_good_holdings.values()) == len(self.agent_addr_to_eq_currency_holdings.values())), 'Length of eq_good_holdings and eq_currency_holdings must be the same.')
enforce(all(((len(self.agent_addr_to_exchange_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_currency_endowments.items())), 'Dimensions for exchange_params and currency_endowments rows must be the same.')
enforce(all(((len(self.agent_addr_to_utility_params[agent_addr]) == len(endowments)) for (agent_addr, endowments) in self.agent_addr_to_good_endowments.items())), 'Dimensions for utility_params and good_endowments rows must be the same.')<|docstring|>Check the consistency of the game configuration.<|endoftext|> |
72069c8b456e425ae339c0f99cb50d8a7d6ee5e146006b610fe245c20285e4e3 | def __init__(self, ledger_id: str, sender_address: Address, counterparty_address: Address, amount_by_currency_id: Dict[(str, int)], quantities_by_good_id: Dict[(str, int)], is_sender_payable_tx_fee: bool, nonce: str, fee_by_currency_id: Optional[Dict[(str, int)]], sender_signature: str, counterparty_signature: str) -> None:
'\n Instantiate transaction.\n\n This extends a terms object to be used as a transaction.\n\n :param ledger_id: the ledger on which the terms are to be settled.\n :param sender_address: the sender address of the transaction.\n :param counterparty_address: the counterparty address of the transaction.\n :param amount_by_currency_id: the amount by the currency of the transaction.\n :param quantities_by_good_id: a map from good id to the quantity of that good involved in the transaction.\n :param is_sender_payable_tx_fee: whether the sender or counterparty pays the tx fee.\n :param nonce: nonce to be included in transaction to discriminate otherwise identical transactions.\n :param fee_by_currency_id: the fee associated with the transaction.\n :param sender_signature: the signature of the terms by the sender.\n :param counterparty_signature: the signature of the terms by the counterparty.\n '
super().__init__(ledger_id=ledger_id, sender_address=sender_address, counterparty_address=counterparty_address, amount_by_currency_id=amount_by_currency_id, quantities_by_good_id=quantities_by_good_id, is_sender_payable_tx_fee=is_sender_payable_tx_fee, nonce=nonce, fee_by_currency_id=fee_by_currency_id)
self._sender_signature = sender_signature
self._counterparty_signature = counterparty_signature | Instantiate transaction.
This extends a terms object to be used as a transaction.
:param ledger_id: the ledger on which the terms are to be settled.
:param sender_address: the sender address of the transaction.
:param counterparty_address: the counterparty address of the transaction.
:param amount_by_currency_id: the amount by the currency of the transaction.
:param quantities_by_good_id: a map from good id to the quantity of that good involved in the transaction.
:param is_sender_payable_tx_fee: whether the sender or counterparty pays the tx fee.
:param nonce: nonce to be included in transaction to discriminate otherwise identical transactions.
:param fee_by_currency_id: the fee associated with the transaction.
:param sender_signature: the signature of the terms by the sender.
:param counterparty_signature: the signature of the terms by the counterparty. | packages/fetchai/skills/tac_control/game.py | __init__ | bryanchriswhite/agents-aea | 126 | python | def __init__(self, ledger_id: str, sender_address: Address, counterparty_address: Address, amount_by_currency_id: Dict[(str, int)], quantities_by_good_id: Dict[(str, int)], is_sender_payable_tx_fee: bool, nonce: str, fee_by_currency_id: Optional[Dict[(str, int)]], sender_signature: str, counterparty_signature: str) -> None:
'\n Instantiate transaction.\n\n This extends a terms object to be used as a transaction.\n\n :param ledger_id: the ledger on which the terms are to be settled.\n :param sender_address: the sender address of the transaction.\n :param counterparty_address: the counterparty address of the transaction.\n :param amount_by_currency_id: the amount by the currency of the transaction.\n :param quantities_by_good_id: a map from good id to the quantity of that good involved in the transaction.\n :param is_sender_payable_tx_fee: whether the sender or counterparty pays the tx fee.\n :param nonce: nonce to be included in transaction to discriminate otherwise identical transactions.\n :param fee_by_currency_id: the fee associated with the transaction.\n :param sender_signature: the signature of the terms by the sender.\n :param counterparty_signature: the signature of the terms by the counterparty.\n '
super().__init__(ledger_id=ledger_id, sender_address=sender_address, counterparty_address=counterparty_address, amount_by_currency_id=amount_by_currency_id, quantities_by_good_id=quantities_by_good_id, is_sender_payable_tx_fee=is_sender_payable_tx_fee, nonce=nonce, fee_by_currency_id=fee_by_currency_id)
self._sender_signature = sender_signature
self._counterparty_signature = counterparty_signature | def __init__(self, ledger_id: str, sender_address: Address, counterparty_address: Address, amount_by_currency_id: Dict[(str, int)], quantities_by_good_id: Dict[(str, int)], is_sender_payable_tx_fee: bool, nonce: str, fee_by_currency_id: Optional[Dict[(str, int)]], sender_signature: str, counterparty_signature: str) -> None:
'\n Instantiate transaction.\n\n This extends a terms object to be used as a transaction.\n\n :param ledger_id: the ledger on which the terms are to be settled.\n :param sender_address: the sender address of the transaction.\n :param counterparty_address: the counterparty address of the transaction.\n :param amount_by_currency_id: the amount by the currency of the transaction.\n :param quantities_by_good_id: a map from good id to the quantity of that good involved in the transaction.\n :param is_sender_payable_tx_fee: whether the sender or counterparty pays the tx fee.\n :param nonce: nonce to be included in transaction to discriminate otherwise identical transactions.\n :param fee_by_currency_id: the fee associated with the transaction.\n :param sender_signature: the signature of the terms by the sender.\n :param counterparty_signature: the signature of the terms by the counterparty.\n '
super().__init__(ledger_id=ledger_id, sender_address=sender_address, counterparty_address=counterparty_address, amount_by_currency_id=amount_by_currency_id, quantities_by_good_id=quantities_by_good_id, is_sender_payable_tx_fee=is_sender_payable_tx_fee, nonce=nonce, fee_by_currency_id=fee_by_currency_id)
self._sender_signature = sender_signature
self._counterparty_signature = counterparty_signature<|docstring|>Instantiate transaction.
This extends a terms object to be used as a transaction.
:param ledger_id: the ledger on which the terms are to be settled.
:param sender_address: the sender address of the transaction.
:param counterparty_address: the counterparty address of the transaction.
:param amount_by_currency_id: the amount by the currency of the transaction.
:param quantities_by_good_id: a map from good id to the quantity of that good involved in the transaction.
:param is_sender_payable_tx_fee: whether the sender or counterparty pays the tx fee.
:param nonce: nonce to be included in transaction to discriminate otherwise identical transactions.
:param fee_by_currency_id: the fee associated with the transaction.
:param sender_signature: the signature of the terms by the sender.
:param counterparty_signature: the signature of the terms by the counterparty.<|endoftext|> |
27f7bd4cf7731c7c383f0db27e2b47d7ee5e9ca73e48f1165153ff0387aa3c55 | @property
def sender_signature(self) -> str:
'Get the sender signature.'
return self._sender_signature | Get the sender signature. | packages/fetchai/skills/tac_control/game.py | sender_signature | bryanchriswhite/agents-aea | 126 | python | @property
def sender_signature(self) -> str:
return self._sender_signature | @property
def sender_signature(self) -> str:
return self._sender_signature<|docstring|>Get the sender signature.<|endoftext|> |
6391ff8613b18f9378969a60d93d87f003278024597aeddfbe15c7e6b9edcf65 | @property
def counterparty_signature(self) -> str:
'Get the counterparty signature.'
return self._counterparty_signature | Get the counterparty signature. | packages/fetchai/skills/tac_control/game.py | counterparty_signature | bryanchriswhite/agents-aea | 126 | python | @property
def counterparty_signature(self) -> str:
return self._counterparty_signature | @property
def counterparty_signature(self) -> str:
return self._counterparty_signature<|docstring|>Get the counterparty signature.<|endoftext|> |
8f7d2108877308136036884182a535e841189f14c20d7a302011c517e295d378 | def has_matching_signatures(self) -> bool:
'\n Check that the signatures match the terms of trade.\n\n :return: True if the transaction has been signed by both parties\n '
result = (self.sender_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.sender_hash.encode('utf-8'), signature=self.sender_signature))
result = (result and (self.counterparty_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.counterparty_hash.encode('utf-8'), signature=self.counterparty_signature)))
return result | Check that the signatures match the terms of trade.
:return: True if the transaction has been signed by both parties | packages/fetchai/skills/tac_control/game.py | has_matching_signatures | bryanchriswhite/agents-aea | 126 | python | def has_matching_signatures(self) -> bool:
'\n Check that the signatures match the terms of trade.\n\n :return: True if the transaction has been signed by both parties\n '
result = (self.sender_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.sender_hash.encode('utf-8'), signature=self.sender_signature))
result = (result and (self.counterparty_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.counterparty_hash.encode('utf-8'), signature=self.counterparty_signature)))
return result | def has_matching_signatures(self) -> bool:
'\n Check that the signatures match the terms of trade.\n\n :return: True if the transaction has been signed by both parties\n '
result = (self.sender_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.sender_hash.encode('utf-8'), signature=self.sender_signature))
result = (result and (self.counterparty_address in LedgerApis.recover_message(identifier=self.ledger_id, message=self.counterparty_hash.encode('utf-8'), signature=self.counterparty_signature)))
return result<|docstring|>Check that the signatures match the terms of trade.
:return: True if the transaction has been signed by both parties<|endoftext|> |
edfc0c457ab6a409be9e9603b2c3330eaf0608494fd5fe04d5de2cf454af2785 | @classmethod
def from_message(cls, message: TacMessage) -> 'Transaction':
'\n Create a transaction from a proposal.\n\n :param message: the message\n :return: Transaction\n '
enforce((message.performative == TacMessage.Performative.TRANSACTION), 'Wrong performative')
sender_is_seller = all([(value >= 0) for value in message.amount_by_currency_id.values()])
transaction = Transaction(ledger_id=message.ledger_id, sender_address=message.sender_address, counterparty_address=message.counterparty_address, amount_by_currency_id=message.amount_by_currency_id, fee_by_currency_id=message.fee_by_currency_id, quantities_by_good_id=message.quantities_by_good_id, is_sender_payable_tx_fee=(not sender_is_seller), nonce=message.nonce, sender_signature=message.sender_signature, counterparty_signature=message.counterparty_signature)
enforce((transaction.id == message.transaction_id), 'Transaction content does not match hash.')
return transaction | Create a transaction from a proposal.
:param message: the message
:return: Transaction | packages/fetchai/skills/tac_control/game.py | from_message | bryanchriswhite/agents-aea | 126 | python | @classmethod
def from_message(cls, message: TacMessage) -> 'Transaction':
'\n Create a transaction from a proposal.\n\n :param message: the message\n :return: Transaction\n '
enforce((message.performative == TacMessage.Performative.TRANSACTION), 'Wrong performative')
sender_is_seller = all([(value >= 0) for value in message.amount_by_currency_id.values()])
transaction = Transaction(ledger_id=message.ledger_id, sender_address=message.sender_address, counterparty_address=message.counterparty_address, amount_by_currency_id=message.amount_by_currency_id, fee_by_currency_id=message.fee_by_currency_id, quantities_by_good_id=message.quantities_by_good_id, is_sender_payable_tx_fee=(not sender_is_seller), nonce=message.nonce, sender_signature=message.sender_signature, counterparty_signature=message.counterparty_signature)
enforce((transaction.id == message.transaction_id), 'Transaction content does not match hash.')
return transaction | @classmethod
def from_message(cls, message: TacMessage) -> 'Transaction':
'\n Create a transaction from a proposal.\n\n :param message: the message\n :return: Transaction\n '
enforce((message.performative == TacMessage.Performative.TRANSACTION), 'Wrong performative')
sender_is_seller = all([(value >= 0) for value in message.amount_by_currency_id.values()])
transaction = Transaction(ledger_id=message.ledger_id, sender_address=message.sender_address, counterparty_address=message.counterparty_address, amount_by_currency_id=message.amount_by_currency_id, fee_by_currency_id=message.fee_by_currency_id, quantities_by_good_id=message.quantities_by_good_id, is_sender_payable_tx_fee=(not sender_is_seller), nonce=message.nonce, sender_signature=message.sender_signature, counterparty_signature=message.counterparty_signature)
enforce((transaction.id == message.transaction_id), 'Transaction content does not match hash.')
return transaction<|docstring|>Create a transaction from a proposal.
:param message: the message
:return: Transaction<|endoftext|> |
0700b8a65d814b3070d2585375aadfbea2071b911a9df4e2dfe109b24a5bb9f6 | def __eq__(self, other: Any) -> bool:
'Compare to another object.'
return (isinstance(other, Transaction) and super().__eq__(other) and (self.sender_signature == other.sender_signature) and (self.counterparty_signature == other.counterparty_signature)) | Compare to another object. | packages/fetchai/skills/tac_control/game.py | __eq__ | bryanchriswhite/agents-aea | 126 | python | def __eq__(self, other: Any) -> bool:
return (isinstance(other, Transaction) and super().__eq__(other) and (self.sender_signature == other.sender_signature) and (self.counterparty_signature == other.counterparty_signature)) | def __eq__(self, other: Any) -> bool:
return (isinstance(other, Transaction) and super().__eq__(other) and (self.sender_signature == other.sender_signature) and (self.counterparty_signature == other.counterparty_signature))<|docstring|>Compare to another object.<|endoftext|> |
ecac22156fb2ddbbf912f6577171ab10a0514d829d919f72a764b935e55fc7a5 | def __init__(self, agent_address: Address, amount_by_currency_id: Dict[(CurrencyId, Quantity)], exchange_params_by_currency_id: Dict[(CurrencyId, Parameter)], quantities_by_good_id: Dict[(GoodId, Quantity)], utility_params_by_good_id: Dict[(GoodId, Parameter)]):
'\n Instantiate an agent state object.\n\n :param agent_address: the agent address\n :param amount_by_currency_id: the amount for each currency\n :param exchange_params_by_currency_id: the exchange parameters of the different currencies\n :param quantities_by_good_id: the quantities for each good.\n :param utility_params_by_good_id: the utility params for every good.\n '
enforce((len(amount_by_currency_id.keys()) == len(exchange_params_by_currency_id.keys())), 'Different number of elements in amount_by_currency_id and exchange_params_by_currency_id')
enforce((len(quantities_by_good_id.keys()) == len(utility_params_by_good_id.keys())), 'Different number of elements in quantities_by_good_id and utility_params_by_good_id')
self._agent_address = agent_address
self._amount_by_currency_id = copy.copy(amount_by_currency_id)
self._exchange_params_by_currency_id = copy.copy(exchange_params_by_currency_id)
self._quantities_by_good_id = quantities_by_good_id
self._utility_params_by_good_id = copy.copy(utility_params_by_good_id) | Instantiate an agent state object.
:param agent_address: the agent address
:param amount_by_currency_id: the amount for each currency
:param exchange_params_by_currency_id: the exchange parameters of the different currencies
:param quantities_by_good_id: the quantities for each good.
:param utility_params_by_good_id: the utility params for every good. | packages/fetchai/skills/tac_control/game.py | __init__ | bryanchriswhite/agents-aea | 126 | python | def __init__(self, agent_address: Address, amount_by_currency_id: Dict[(CurrencyId, Quantity)], exchange_params_by_currency_id: Dict[(CurrencyId, Parameter)], quantities_by_good_id: Dict[(GoodId, Quantity)], utility_params_by_good_id: Dict[(GoodId, Parameter)]):
'\n Instantiate an agent state object.\n\n :param agent_address: the agent address\n :param amount_by_currency_id: the amount for each currency\n :param exchange_params_by_currency_id: the exchange parameters of the different currencies\n :param quantities_by_good_id: the quantities for each good.\n :param utility_params_by_good_id: the utility params for every good.\n '
enforce((len(amount_by_currency_id.keys()) == len(exchange_params_by_currency_id.keys())), 'Different number of elements in amount_by_currency_id and exchange_params_by_currency_id')
enforce((len(quantities_by_good_id.keys()) == len(utility_params_by_good_id.keys())), 'Different number of elements in quantities_by_good_id and utility_params_by_good_id')
self._agent_address = agent_address
self._amount_by_currency_id = copy.copy(amount_by_currency_id)
self._exchange_params_by_currency_id = copy.copy(exchange_params_by_currency_id)
self._quantities_by_good_id = quantities_by_good_id
self._utility_params_by_good_id = copy.copy(utility_params_by_good_id) | def __init__(self, agent_address: Address, amount_by_currency_id: Dict[(CurrencyId, Quantity)], exchange_params_by_currency_id: Dict[(CurrencyId, Parameter)], quantities_by_good_id: Dict[(GoodId, Quantity)], utility_params_by_good_id: Dict[(GoodId, Parameter)]):
'\n Instantiate an agent state object.\n\n :param agent_address: the agent address\n :param amount_by_currency_id: the amount for each currency\n :param exchange_params_by_currency_id: the exchange parameters of the different currencies\n :param quantities_by_good_id: the quantities for each good.\n :param utility_params_by_good_id: the utility params for every good.\n '
enforce((len(amount_by_currency_id.keys()) == len(exchange_params_by_currency_id.keys())), 'Different number of elements in amount_by_currency_id and exchange_params_by_currency_id')
enforce((len(quantities_by_good_id.keys()) == len(utility_params_by_good_id.keys())), 'Different number of elements in quantities_by_good_id and utility_params_by_good_id')
self._agent_address = agent_address
self._amount_by_currency_id = copy.copy(amount_by_currency_id)
self._exchange_params_by_currency_id = copy.copy(exchange_params_by_currency_id)
self._quantities_by_good_id = quantities_by_good_id
self._utility_params_by_good_id = copy.copy(utility_params_by_good_id)<|docstring|>Instantiate an agent state object.
:param agent_address: the agent address
:param amount_by_currency_id: the amount for each currency
:param exchange_params_by_currency_id: the exchange parameters of the different currencies
:param quantities_by_good_id: the quantities for each good.
:param utility_params_by_good_id: the utility params for every good.<|endoftext|> |
34299fab60f8e5b3f6f38e93f73247081bfa778428080f60883cec0ce74de30f | @property
def agent_address(self) -> str:
'Get address of the agent which state that is.'
return self._agent_address | Get address of the agent which state that is. | packages/fetchai/skills/tac_control/game.py | agent_address | bryanchriswhite/agents-aea | 126 | python | @property
def agent_address(self) -> str:
return self._agent_address | @property
def agent_address(self) -> str:
return self._agent_address<|docstring|>Get address of the agent which state that is.<|endoftext|> |
72582e54ae2d2e7e5a006a393e5e69e721051c3a6298e057d8a670e6c895d6be | @property
def amount_by_currency_id(self) -> Dict[(CurrencyId, Quantity)]:
'Get the amount for each currency.'
return copy.copy(self._amount_by_currency_id) | Get the amount for each currency. | packages/fetchai/skills/tac_control/game.py | amount_by_currency_id | bryanchriswhite/agents-aea | 126 | python | @property
def amount_by_currency_id(self) -> Dict[(CurrencyId, Quantity)]:
return copy.copy(self._amount_by_currency_id) | @property
def amount_by_currency_id(self) -> Dict[(CurrencyId, Quantity)]:
return copy.copy(self._amount_by_currency_id)<|docstring|>Get the amount for each currency.<|endoftext|> |
50f87836512a2c9f4ed9aeb3fd5afafbacd580ed56d0955730aa72bf4a318b1d | @property
def exchange_params_by_currency_id(self) -> Dict[(CurrencyId, Parameter)]:
'Get the exchange parameters for each currency.'
return copy.copy(self._exchange_params_by_currency_id) | Get the exchange parameters for each currency. | packages/fetchai/skills/tac_control/game.py | exchange_params_by_currency_id | bryanchriswhite/agents-aea | 126 | python | @property
def exchange_params_by_currency_id(self) -> Dict[(CurrencyId, Parameter)]:
return copy.copy(self._exchange_params_by_currency_id) | @property
def exchange_params_by_currency_id(self) -> Dict[(CurrencyId, Parameter)]:
return copy.copy(self._exchange_params_by_currency_id)<|docstring|>Get the exchange parameters for each currency.<|endoftext|> |
e96fd6c6adbf09a1562edb0797d427b1bacbab5b7b9efd26d12441bb77c3d5d7 | @property
def quantities_by_good_id(self) -> Dict[(GoodId, Quantity)]:
'Get holding of each good.'
return copy.copy(self._quantities_by_good_id) | Get holding of each good. | packages/fetchai/skills/tac_control/game.py | quantities_by_good_id | bryanchriswhite/agents-aea | 126 | python | @property
def quantities_by_good_id(self) -> Dict[(GoodId, Quantity)]:
return copy.copy(self._quantities_by_good_id) | @property
def quantities_by_good_id(self) -> Dict[(GoodId, Quantity)]:
return copy.copy(self._quantities_by_good_id)<|docstring|>Get holding of each good.<|endoftext|> |
5e2b85a1638651651f31499821e9e2bc7a40795f53564e281c3818b5e0aa4d9d | @property
def utility_params_by_good_id(self) -> Dict[(GoodId, Parameter)]:
'Get utility parameter for each good.'
return copy.copy(self._utility_params_by_good_id) | Get utility parameter for each good. | packages/fetchai/skills/tac_control/game.py | utility_params_by_good_id | bryanchriswhite/agents-aea | 126 | python | @property
def utility_params_by_good_id(self) -> Dict[(GoodId, Parameter)]:
return copy.copy(self._utility_params_by_good_id) | @property
def utility_params_by_good_id(self) -> Dict[(GoodId, Parameter)]:
return copy.copy(self._utility_params_by_good_id)<|docstring|>Get utility parameter for each good.<|endoftext|> |
8d0583f78a429cca58d8ff59c44c89d03876d1ffccae01bfe8efc5f5f7cfb27e | def get_score(self) -> float:
'\n Compute the score of the current state.\n\n The score is computed as the sum of all the utilities for the good holdings\n with positive quantity plus the money left.\n :return: the score.\n '
goods_score = logarithmic_utility(self.utility_params_by_good_id, self.quantities_by_good_id)
money_score = linear_utility(self.exchange_params_by_currency_id, self.amount_by_currency_id)
score = (goods_score + money_score)
return score | Compute the score of the current state.
The score is computed as the sum of all the utilities for the good holdings
with positive quantity plus the money left.
:return: the score. | packages/fetchai/skills/tac_control/game.py | get_score | bryanchriswhite/agents-aea | 126 | python | def get_score(self) -> float:
'\n Compute the score of the current state.\n\n The score is computed as the sum of all the utilities for the good holdings\n with positive quantity plus the money left.\n :return: the score.\n '
goods_score = logarithmic_utility(self.utility_params_by_good_id, self.quantities_by_good_id)
money_score = linear_utility(self.exchange_params_by_currency_id, self.amount_by_currency_id)
score = (goods_score + money_score)
return score | def get_score(self) -> float:
'\n Compute the score of the current state.\n\n The score is computed as the sum of all the utilities for the good holdings\n with positive quantity plus the money left.\n :return: the score.\n '
goods_score = logarithmic_utility(self.utility_params_by_good_id, self.quantities_by_good_id)
money_score = linear_utility(self.exchange_params_by_currency_id, self.amount_by_currency_id)
score = (goods_score + money_score)
return score<|docstring|>Compute the score of the current state.
The score is computed as the sum of all the utilities for the good holdings
with positive quantity plus the money left.
:return: the score.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.