seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2863726451 | import matplotlib.pyplot as plt
import csv
# 1. 读取数据;数据数组
data = []
headers = ['工作年限' ,'学历','职位','薪水','城市','发布时间']
city = set()
with open('jobs.csv', 'r', encoding='utf-8') as fd:
reader = csv.DictReader(fd, fieldnames=headers) # 返回的是迭代器
next(reader) # 把头略过
for row in reader:
data.append(row['城市'])
city.add(row['城市'])
# print(data)
# print(city, len(city))
# 2. 显示数据matplotlib
figure = plt.figure('职位数量分布图', figsize=(8, 6))
ax = figure.add_axes([0.1, 0.1, 0.8, 0.8])
ax.set_xlim(-1, 12)
ax.hist(
x=data,
bins=len(city),
range=(0, 12), # 0到12 全部统计
rwidth=0.6, # 控制柱状图的大小宽度
align='left',
density=True,
color='blue',
# orientation='vertical' # 默认就是这个
)
plt.show()
| XiaJune/A-small | d16_plot_linalg/demo_hist.py | demo_hist.py | py | 944 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "csv.DictReader",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.figure",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "matplotlib.p... |
2360933175 | # -*- coding: utf-8 -*-
"""
DIAGNOSTICS OF THE CARDIOVASCULAR SYSTEM BASED ON NEURAL NETWORKS
Classify ECG-Signals to CAD-Symptoms by means of artificial neural networks
Skript containing function to plot results.
"""
import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import style
from collections import Counter
def plot_filtered_signal(signal,filtered_signal, freq, dirPath, picName, begin = None, end = None):
'''
PLots the comparision of two signals in one fig.
'''
if begin is None:
begin = 0
if end is None:
end = int(len(signal) / freq)
fig, ax = plt.subplots(3, sharex = True, sharey = True)
time = np.linspace(begin, end, (end - begin)*freq)
ax[0].plot(time,signal[begin * freq:end * freq],'black', linewidth = 1, label = 'signal before filtering' )
ax[0].legend(loc = 'upper right')
ax[1].plot(time,filtered_signal[begin * freq:end * freq], 'g', linewidth = 1, label = 'signal after filtering')
ax[1].legend(loc = 'upper right')
ax[2].plot(time,signal[begin * freq:end * freq],'black', linewidth = 1, label = 'signal before filtering' )
ax[2].plot(time,filtered_signal[begin * freq:end * freq], 'g', linewidth = 1, label = 'signal after filtering')
ax[2].legend(loc = 'upper right')
ax[2].set(xlabel = 'time in s', ylabel = 'amplitude')
plt.grid()
fig.savefig(os.path.join(dirPath, picName))
plt.close(fig)
def plot_powerlinespectrum(signal, filtered_signal, freq, dirPath, picName):
'''
Plots Powerlinespectrum before and after filtering.
'''
fig, ax = plt.subplots(2, sharex = True, sharey = True)
ax[0].psd(signal, 512, freq, label = 'before filtering')
ax[0].legend(loc = 'upper right')
ax[1].psd(filtered_signal, 512, freq, label = 'after filtering')
ax[1].legend(loc = 'upper right')
fig.savefig(os.path.join(dirPath,picName))
plt.close(fig)
def plot_rpeak_detection(signal, rpeaks, freq, dirPath, picName):
signal = np.array(signal)
rpeaks = np.array(rpeaks, dtype = np.int_)
r_indx = np.array([np.nan] * len(signal))
r_indx[rpeaks] = signal[rpeaks]
timeline = np.linspace(0, len(signal)/360, len(signal))
ax1 = plt.subplot(211) # Plot full ecg signal
ax1.plot(timeline,signal, 'b') # Plot full ecg signal
#plt.plot(rpeaks, signal[rpeaks], 'ro') # Plot R-Peaks as points
ax1.plot(timeline,r_indx, 'ro', markersize=1)
ax1.set_title('ECG-signal with detected R-Peaks')
ax1.set_ylabel('ECG (mV)')
ax1.set_xlabel('Time (s)')
ax2 = plt.subplot(212) # Plot detailed ecg signal
ax2.plot(timeline[10 * freq:20 * freq],signal[10 * freq:20 * freq]) # Plot detailed ecg signal
ax2.plot(timeline[10 * freq:20 * freq],r_indx[10 * freq:20 * freq], 'ro', markersize=1) # Plot R-Peaks of the detailed interval
ax2.set_title('Detailed ECG-signal with detected R-Peaks ')
ax2.set_ylabel('ECG (mV)')
ax2.set_xlabel('Time (s)')
plt.subplots_adjust(hspace=0.5)
plt.savefig(os.path.join(dirPath,picName))
plt.clf()
def plot_ints_timeseries(rr_intervals, nn_intervals, dirPath, picName, autoscale = True, y_min = None, y_max = None):
style.use("seaborn-darkgrid")
plt.figure(figsize=(12, 8))
plt.title("Interval time series")
plt.ylabel("Interval duration (ms)", fontsize=15)
plt.xlabel("Time (s)", fontsize=15)
plt.plot(np.cumsum(rr_intervals) / 1000, rr_intervals, 'black', label='RR-Intervals')
plt.plot(np.cumsum(rr_intervals) / 1000, nn_intervals, label = 'NN-Intervals')
plt.legend(loc = 'upper right')
if not autoscale:
plt.ylim(y_min, y_max)
plt.savefig(os.path.join(dirPath,picName))
plt.clf()
plt.close()
def plot_class_distribution(dataset, y_train, y_test):
colors = sns.color_palette('colorblind')
class_count1 = Counter(dataset['Label'])
data1 = [class_count1[key] for key in sorted(class_count1.keys())]
class_count2 = Counter(y_train)
data2 = [class_count2[key] for key in sorted(class_count2.keys())]
class_count3 = Counter(y_test)
data3 = [class_count3[key] for key in sorted(class_count3.keys())]
fig, ax = plt.subplots(figsize=(9, 5))
ax.invert_yaxis()
ax.yaxis.set_tick_params(labelsize=20)
ax.xaxis.set_visible(False)
ax.set_xlim(0, np.sum(data1))
category_names = ['class 0', 'class 1', 'class 2']
data1_cum = np.array(data1).cumsum()
data2_cum = np.array(data2).cumsum()
data3_cum = np.array(data3).cumsum()
for i, colname in enumerate(category_names):
width1 = data1[i]
start1 = data1_cum[i] - width1
ax.barh(['Complete Dataset'], width1, left = start1, height = 0.5, color = colors[i], label = colname)
ax.text(start1 + width1/2, 0, str(width1), ha='center', va = 'center', color = 'white', fontsize=25)
width2 = data2[i]
start2 = data2_cum[i] - width2
ax.barh(['Train Dataset'], width2, left = start2, height = 0.5, color = colors[i], label = colname)
ax.text(start2 + width2/2, 1, str(width2), ha='center', va = 'center', color = 'white', fontsize=25)
width3 = data3[i]
start3 = np.sum(data2) + data3_cum[i] - width3
ax.barh(['Test Dataset'], width3, left = start3, height = 0.5, color = colors[i], label = colname)
ax.text(start3 + width3/2, 2, str(width3), ha='center', va = 'center', color = 'white', fontsize=25)
ax.legend(ncol = 3,bbox_to_anchor=(0, 1), loc='lower left', fontsize = 20)
plt.show()
| Judweep/ECG_Classifier | Source_code/Plotting_Functions.py | Plotting_Functions.py | py | 5,669 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "matplotlib.pyplot.subplots",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 25,
"usage_type": "name"
},
{
"api_name": "numpy.linspace",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "matplotli... |
13925791934 | import numpy as np
import cv2 as cv
import scipy.io
from PIL import Image
import time
import os
import errno
import random
from sklearn.model_selection import train_test_split
import shutil
import cv2
###############################################################################
###############################################################################
# Reads _dep and _vis images and stacks them into 4-dimensional image;
# Also divides dataset into vis_only, dep_only, and fused_only, and partitions
# data into train and test folders using 70-30 split
# note: for some reason, the train and test folders end up inside the "/all/"
# directory for vis and dep, but not for fused...I'll trouble shoot this later,
# but for now this script generates the folders needed for training and we can
# just move them to the outter directory (i.e., "vis_only")
###############################################################################
fuse_data = False
dep_dir = '/home/chris/cse455_final/Annotated/dep'
vis_dir = '/home/chris/cse455_final/Annotated/vis'
fused_dir = '/home/chris/cse455_final/Annotated/fuse'
directories = [dep_dir, vis_dir, fused_dir]
image_types = ['dep', 'vis', 'fused']
dep_annotations = [os.path.join(dep_dir, x) for x in os.listdir(dep_dir) if x[-3:] == "txt"]
dep_images = [os.path.join(dep_dir, x) for x in os.listdir(dep_dir) if x[-3:] == "jpg"]
vis_annotations = [os.path.join(vis_dir, x) for x in os.listdir(vis_dir) if x[-3:] == "txt"]
vis_images = [os.path.join(vis_dir, x) for x in os.listdir(vis_dir) if x[-3:] == "jpg"]
dep_annotations.sort()
dep_images.sort()
vis_annotations.sort()
vis_images.sort()
if fuse_data:
for index, image in enumerate(dep_images):
dep_data = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
vis_data = cv2.imread(vis_images[index], cv2.IMREAD_UNCHANGED)
fused_img = np.dstack((vis_data,dep_data))
old_path, fname = os.path.split(image)
name, ext = os.path.splitext(fname)
new_name = name.replace('dep', 'fused.png')
cv2.imwrite(os.path.join(fused_dir, new_name), fused_img)
# print(vis_data.shape)
# print(dep_data.shape)
# print(fused_img.shape)
# cv2.imshow('dep', dep_data)
# cv2.imshow('vis', vis_data)
# cv2.imshow('fused', fused_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
else:
fused_images = [os.path.join(fused_dir, x) for x in os.listdir(fused_dir) if x[-3:] == "png"]
fused_annotations = [os.path.join(fused_dir, x) for x in os.listdir(fused_dir) if x[-3:] == "txt"]
fused_annotations.sort()
fused_images.sort()
for k, outter_dir in enumerate(directories):
#temp = os.path.split(outter_dir)
#out_dir = os.path.join(temp[0])
#print(temp[0])
image_type = image_types[k]
if image_type == 'dep':
images_master = dep_images
annotations_master = dep_annotations
elif image_type == 'vis':
images_master = vis_images
annotations_master = vis_annotations
elif image_type == 'fused':
images_master = fused_images
annotations_master = fused_annotations
try:
print(outter_dir)
os.makedirs(os.path.join(outter_dir,'test'))
os.makedirs(os.path.join(outter_dir,'train'))
except OSError as e:
if e.errno != errno.EEXIST:
raise
if len(os.listdir(os.path.join(outter_dir,'test')))==0:
# does 70-30 split between train and test (https://realpython.com/train-test-split-python-data/)
x_train, x_test, y_train, y_test = train_test_split(images_master,annotations_master)
for index,image in enumerate(x_train):
shutil.copy2(image,os.path.join(outter_dir,'train/'))
shutil.copy2(y_train[index],os.path.join(outter_dir,'train/'))
for index,image in enumerate(x_test):
shutil.copy2(image,os.path.join(outter_dir,'test/'))
shutil.copy2(y_test[index],os.path.join(outter_dir,'test/'))
else:
print('dir is not empty') | haynec/yolov5_4_channel | fuse_and_reorg_dataset.py | fuse_and_reorg_dataset.py | py | 4,190 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 32,
"usage_type": "attribute"
},
{
"api_name": "os.listdir",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line_number"... |
17894590970 | import collections
import time
from typing import Any, Dict
from absl import logging
import numpy as np
import robustness_metrics as rm
from sklearn.metrics import accuracy_score
from sklearn.metrics import auc
from sklearn.metrics import log_loss
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import check_array
from sklearn.utils import check_consistent_length
import tensorflow as tf
from . import metric_utils # local file import
from . import results_storage_utils # local file import
@tf.function
def eval_step_tf(dataset_iterator, dataset_steps, strategy, estimator,
estimator_args, uncertainty_estimator_fn, is_deterministic):
"""Eval step.
Run TensorFlow model evaluation, using an `uncertainty_estimator_fn`
to produce predictions and decomposed uncertainty estimates for each example.
Args:
dataset_iterator: tf.data.Dataset, dataset on which we will evaluate the
model.
dataset_steps: int, number of gradient steps in the dataset.
strategy: tf.distribute strategy, used to distribute datasets.
estimator: model wrapped to produce a `tf.Tensor`, predictive mean, with
shape [B].
estimator_args: Dict, extra args for the `uncertainty_estimator_fn`, such as
the number of MC samples, `num_samples`.
uncertainty_estimator_fn: Callable, method to produce predictive means along
with various metrics of uncertainty, e.g., predictive_entropy, epistemic
uncertainty (mutual information).
is_deterministic: bool, is the model a single deterministic network. In this
case, we cannot capture epistemic uncertainty.
Returns:
Dict, contains `tf.Tensor` predictions, ground truth,
and uncertainty estimates.
"""
print('Tracing in `eval_utils.eval_step_tf`.')
def step_fn(inputs):
print('Tracing in `eval_utils.eval_step_tf.step_fn`.')
images = inputs['features']
labels = inputs['labels']
# Compute prediction, total, aleatoric, and epistemic uncertainty estimates
pred_and_uncert = uncertainty_estimator_fn(
images, estimator, training_setting=False, **estimator_args)
# Return a tuple
y_true = labels
y_pred = pred_and_uncert['prediction']
y_pred_entropy = pred_and_uncert['predictive_entropy']
if not is_deterministic:
y_pred_variance = pred_and_uncert['predictive_variance']
y_aleatoric_uncert = pred_and_uncert['aleatoric_uncertainty']
y_epistemic_uncert = pred_and_uncert['epistemic_uncertainty']
else:
y_pred_variance = tf.zeros(0)
y_aleatoric_uncert = tf.zeros(0)
y_epistemic_uncert = tf.zeros(0)
return (y_true, y_pred, y_pred_entropy, y_pred_variance, y_aleatoric_uncert,
y_epistemic_uncert)
# Containers for storage of
# predictions, ground truth, uncertainty estimates
# Construct tf.TensorArrays to store model results
n_per_core_batches = dataset_steps * strategy.num_replicas_in_sync
y_true = tf.TensorArray(tf.int32, size=n_per_core_batches)
y_pred = tf.TensorArray(tf.float32, size=n_per_core_batches)
y_pred_entropy = tf.TensorArray(tf.float32, size=n_per_core_batches)
y_pred_variance = tf.TensorArray(tf.float32, size=n_per_core_batches)
y_aleatoric_uncert = tf.TensorArray(tf.float32, size=n_per_core_batches)
y_epistemic_uncert = tf.TensorArray(tf.float32, size=n_per_core_batches)
for i in tf.range(dataset_steps):
result = strategy.run(step_fn, args=(next(dataset_iterator),))
# Parse results tuple
(y_true_, y_pred_, y_pred_entropy_, y_pred_variance_, y_aleatoric_uncert_,
y_epistemic_uncert_) = result
# Convert from Per-Replica object to tuple
if strategy.num_replicas_in_sync > 1:
y_true_ = y_true_.values
y_pred_ = y_pred_.values
y_pred_entropy_ = y_pred_entropy_.values
if not is_deterministic:
y_pred_variance_ = y_pred_variance_.values
y_aleatoric_uncert_ = y_aleatoric_uncert_.values
y_epistemic_uncert_ = y_epistemic_uncert_.values
# Iterate through per-batch results
# This is written in a very un-Pythonic manner to have updates only
# rely on arguments successfully passed to TPU scope
for replica_id in tf.range(strategy.num_replicas_in_sync):
index = (strategy.num_replicas_in_sync * i) + replica_id
for batch_result in y_true_:
y_true = y_true.write(index, batch_result)
for batch_result in y_pred_:
y_pred = y_pred.write(index, batch_result)
for batch_result in y_pred_entropy_:
y_pred_entropy = y_pred_entropy.write(index, batch_result)
if not is_deterministic:
for batch_result in y_pred_variance_:
y_pred_variance = y_pred_variance.write(index, batch_result)
for batch_result in y_aleatoric_uncert_:
y_aleatoric_uncert = y_aleatoric_uncert.write(index, batch_result)
for batch_result in y_epistemic_uncert_:
y_epistemic_uncert = y_epistemic_uncert.write(index, batch_result)
else:
y_true = y_true.write(i, y_true_)
y_pred = y_pred.write(i, y_pred_)
y_pred_entropy = y_pred_entropy.write(i, y_pred_entropy_)
if not is_deterministic:
y_pred_variance = y_pred_variance.write(i, y_pred_variance_)
y_aleatoric_uncert = y_aleatoric_uncert.write(i, y_aleatoric_uncert_)
y_epistemic_uncert = y_epistemic_uncert.write(i, y_epistemic_uncert_)
results_arrs = {
'y_true': y_true.stack(),
'y_pred': y_pred.stack(),
'y_pred_entropy': y_pred_entropy.stack(),
}
if not is_deterministic:
results_arrs['y_pred_variance'] = y_pred_variance.stack()
results_arrs['y_aleatoric_uncert'] = y_aleatoric_uncert.stack()
results_arrs['y_epistemic_uncert'] = y_epistemic_uncert.stack()
return results_arrs
def evaluate_model_on_datasets(strategy,
datasets,
steps,
estimator,
estimator_args,
uncertainty_estimator_fn,
eval_batch_size,
call_dataset_iter,
is_deterministic=False,
backend='tf',
eval_step_jax=None,
verbose=False):
"""Eval on dataset.
Run model evaluation on all provided datasets, using an
`uncertainty_estimator_fn` to produce predictions and decomposed
uncertainty estimates for each example.
Additionally constructs joint dataset predictions, composed of predictions
on both in-domain and OOD datasets.
Args:
strategy: tf.distribute strategy, used to distribute datasets.
datasets: Dict[str, tf.data.Dataset], datasets on which we evaluate the
model.
steps: Dict[str, int], number of gradient steps in each dataset.
estimator: model wrapped to produce a `tf.Tensor` (if `backend`=='tf') or
`np.ndarray` (if `backend`=='jax'), predictive mean, with shape [B].
estimator_args: Dict, extra args for the `uncertainty_estimator_fn`, such as
the number of MC samples, `num_samples`.
uncertainty_estimator_fn: Callable, method to produce predictive means along
with various metrics of uncertainty, e.g., predictive_entropy, epistemic
uncertainty (mutual information).
eval_batch_size: int, size of evaluation minibatches.
call_dataset_iter: bool, if True, should call `iter()` on each dataset. May
not need if evaluation datasets have been repeated.
is_deterministic: bool, is the model a single deterministic network. In this
case, we cannot capture epistemic uncertainty.
backend: str, in {'tf', 'jax'}, specifies the evaluation method.
eval_step_jax: Callable, evaluation method used for Jax model.
verbose: bool, extra logging.
Returns:
Dict, for each dataset, contains `np.array` predictions, ground truth,
and uncertainty estimates.
"""
# Need to collect these so we can form joint datasets:
# e.g., joint_test = in_domain_test UNION ood_test
dataset_split_to_containers = {}
for dataset_split, dataset in datasets.items():
# Begin iteration for this dataset split
start_time = time.time()
if call_dataset_iter:
dataset_iterator = iter(dataset)
else:
dataset_iterator = dataset
logging.info(f'Creating iterator took {time.time() - start_time} seconds.')
dataset_steps = steps[dataset_split]
logging.info(f'Evaluating split {dataset_split}.')
if backend == 'jax':
eval_epoch_arrs = eval_step_jax(dataset_iterator, dataset_steps,
is_deterministic, **estimator_args)
elif backend == 'tf':
eval_epoch_arrs = eval_step_tf(dataset_iterator,
tf.convert_to_tensor(dataset_steps),
strategy, estimator, estimator_args,
uncertainty_estimator_fn, is_deterministic)
else:
raise NotImplementedError(f'Backend {backend} is not supported yet.')
# Update metadata
time_elapsed = time.time() - start_time
dataset_split_to_containers[dataset_split] = {}
dataset_split_dict = dataset_split_to_containers[dataset_split]
dataset_split_dict['total_ms_elapsed'] = time_elapsed * 1e6
dataset_split_dict['dataset_size'] = dataset_steps * eval_batch_size
# Use vectorized NumPy containers
for eval_key, eval_arr in eval_epoch_arrs.items():
tmp_eval_arr = eval_arr if backend == 'jax' else eval_arr.numpy()
if tmp_eval_arr.ndim > 1:
tmp_eval_arr = np.concatenate(tmp_eval_arr).flatten()
dataset_split_dict[eval_key] = tmp_eval_arr
if verbose:
print(f'Concatenated {eval_key} into shape '
f'{dataset_split_dict[eval_key].shape}')
dataset_split_dict['y_pred'] = dataset_split_dict['y_pred'].astype(
'float64')
# Add Joint Dicts
dataset_split_to_containers = results_storage_utils.add_joint_dicts(
dataset_split_to_containers, is_deterministic=is_deterministic)
return dataset_split_to_containers
def evaluate_model_and_compute_metrics(
strategy,
eval_datasets,
steps,
metrics,
eval_estimator,
uncertainty_estimator_fn,
eval_batch_size,
available_splits,
estimator_args,
call_dataset_iter,
is_deterministic=False,
num_bins=15,
use_tpu=True,
return_per_pred_results=False,
backend='tf',
eval_step_jax=None):
"""Main.
Main method for evaluation and computing metrics using TF or Jax
models. Usable for evaluation during tuning.
Args:
strategy: tf.distribute strategy, used to distribute datasets.
eval_datasets: Dict[str, tf.data.Dataset], datasets on which we evaluate the
model.
steps: Dict[str, int], number of gradient steps in each dataset.
metrics: metrics.
eval_estimator: model wrapped to produce a `tf.Tensor` (if `backend`=='tf')
or `np.ndarray` (if `backend`=='jax'), predictive mean, with shape [B].
uncertainty_estimator_fn: Callable, method to produce predictive means along
with various metrics of uncertainty, e.g., predictive_entropy, epistemic
uncertainty (mutual information).
eval_batch_size: int, size of evaluation minibatches.
available_splits: List[str], names of the evaluation datasets provided, used
to log results only for these splits.
estimator_args: Dict, extra args for the `uncertainty_estimator_fn`, such as
the number of MC samples, `num_samples`.
call_dataset_iter: bool, if True, should call `iter()` on each dataset. May
not need if evaluation datasets have been repeated.
is_deterministic: bool, is the model a single deterministic network. In this
case, we cannot capture epistemic uncertainty.
num_bins: int, number of bins to use with expected calibration error.
use_tpu: bool, currently exists a bug that disallows collecting ECE during
training with TPU, this is used to avoid logging that metric.
return_per_pred_results: bool,
backend: str, in {'tf', 'jax'}, specifies the evaluation method.
eval_step_jax: Callable, evaluation method used for Jax model.
Returns:
Union[Tuple[Dict, Dict], Dict]
If return_per_pred_results, return two Dicts. Else, return only the
second.
first Dict:
for each dataset, per-prediction results (e.g., each prediction,
ground-truth, loss, retention arrays).
second Dict:
for each dataset, contains `np.array` predictions, ground truth,
and uncertainty estimates.
"""
# Compute predictions on all evaluation datasets
# When we eval during training we don't need to re-iterate the
# evaluation datasets
eval_results = evaluate_model_on_datasets(
strategy=strategy,
datasets=eval_datasets,
steps=steps,
estimator=eval_estimator,
estimator_args=estimator_args,
uncertainty_estimator_fn=uncertainty_estimator_fn,
eval_batch_size=eval_batch_size,
call_dataset_iter=call_dataset_iter,
is_deterministic=is_deterministic,
backend=backend,
eval_step_jax=eval_step_jax)
# For each eval dataset, add NLL and accuracy for each example
eval_results = compute_loss_and_accuracy_arrs_for_all_datasets(eval_results)
# Compute all metrics for each dataset --
# Robustness, Open Set Recognition, Retention AUC
metrics_results = compute_metrics_for_all_datasets(
eval_results,
use_precomputed_arrs=False,
ece_num_bins=num_bins,
compute_retention_auc=True,
verbose=False)
# Log metrics
metrics_results = metric_utils.log_epoch_metrics(
metrics=metrics,
eval_results=metrics_results,
use_tpu=use_tpu,
dataset_splits=available_splits)
if return_per_pred_results:
return eval_results, metrics_results
else:
return metrics_results
def evaluate_model_on_datasets_np(
datasets,
steps,
estimator,
estimator_args,
uncertainty_estimator_fn,
eval_batch_size,
is_deterministic,
np_input=False,
):
"""Main method for evaluation and computing metrics.
Appropriate for evaluation loops with a single GPU (i.e., no
distribution strategy), and is framework-agnostic (will work just as
well with a TF, Jax, or PyTorch model, given an `uncertainty_estimator_fn`
to cast to NumPy ndarrays.
Args:
datasets: Dict[str, tf.data.Dataset], datasets on which we evaluate the
model.
steps: Dict[str, int], number of gradient steps in each dataset.
estimator: model wrapped to produce a `np.ndarray`, predictive mean, with
shape [B].
estimator_args: Dict, extra args for the `uncertainty_estimator_fn`, such as
the number of MC samples, `num_samples`.
uncertainty_estimator_fn: Callable, method to produce predictive means along
with various metrics of uncertainty, e.g., predictive_entropy, epistemic
uncertainty (mutual information).
eval_batch_size: int, size of evaluation minibatches.
is_deterministic: bool, is the model a single deterministic network. In this
case, we cannot capture epistemic uncertainty.
np_input: bool, True if the model expects a NumPy input; we add a cast.
Returns:
Dict, for each dataset, contains `np.array` predictions, ground truth,
and uncertainty estimates.
"""
# Need to collect these so we can form joint datasets:
# e.g., joint_test = in_domain_test UNION ood_test
dataset_split_to_containers = {}
for dataset_split, dataset in datasets.items():
# Containers for numpy storage of
# image names, predictions, ground truth, uncertainty estimates
names = list()
y_true = list()
y_pred = list()
y_pred_entropy = list()
if not is_deterministic:
y_pred_variance = list()
y_aleatoric_uncert = list()
y_epistemic_uncert = list()
# Begin iteration for this dataset split
start_time = time.time()
dataset_iterator = iter(dataset)
dataset_steps = steps[dataset_split]
logging.info(f'Evaluating split {dataset_split}.')
for step in range(dataset_steps):
if step % 10 == 0:
logging.info('Evaluated %d/%d batches.', step, dataset_steps)
inputs = next(dataset_iterator) # pytype: disable=attribute-error
images = inputs['features']
labels = inputs['labels']
# Compute prediction, total, aleatoric, and epistemic
# uncertainty estimates
pred_and_uncert = uncertainty_estimator_fn(
images._numpy() if np_input else images, # pylint: disable=protected-access
estimator,
training_setting=False,
**estimator_args)
# Add this batch of predictions to the containers
names.append(inputs['name'])
y_true.append(labels.numpy())
y_pred.append(pred_and_uncert['prediction'])
y_pred_entropy.append(pred_and_uncert['predictive_entropy'])
if not is_deterministic:
y_pred_variance.append(pred_and_uncert['predictive_variance'])
y_aleatoric_uncert.append(pred_and_uncert['aleatoric_uncertainty'])
y_epistemic_uncert.append(pred_and_uncert['epistemic_uncertainty'])
# Update metadata
time_elapsed = time.time() - start_time
dataset_split_to_containers[dataset_split] = {}
dataset_split_dict = dataset_split_to_containers[dataset_split]
dataset_split_dict['total_ms_elapsed'] = time_elapsed * 1e6
dataset_split_dict['dataset_size'] = dataset_steps * eval_batch_size
dataset_split_dict['names'] = np.concatenate(names).flatten()
dataset_split_dict['y_true'] = np.concatenate(y_true).flatten()
dataset_split_dict['y_pred'] = np.concatenate(y_pred).flatten()
dataset_split_dict['y_pred'] = dataset_split_dict['y_pred'].astype(
'float64')
# Use vectorized NumPy containers
dataset_split_dict['y_pred_entropy'] = (
np.concatenate(y_pred_entropy).flatten())
if not is_deterministic:
dataset_split_dict['y_pred_variance'] = (
np.concatenate(y_pred_variance).flatten())
dataset_split_dict['y_aleatoric_uncert'] = (
np.concatenate(y_aleatoric_uncert).flatten())
dataset_split_dict['y_epistemic_uncert'] = (
np.concatenate(y_epistemic_uncert).flatten())
# Add Joint Dicts
dataset_split_to_containers = results_storage_utils.add_joint_dicts(
dataset_split_to_containers, is_deterministic=is_deterministic)
return dataset_split_to_containers
def eval_model_numpy(datasets,
steps,
estimator,
estimator_args,
uncertainty_estimator_fn,
eval_batch_size,
is_deterministic,
distribution_shift,
num_bins=15,
np_input=False):
"""Main method for evaluation and computing metrics.
Appropriate for evaluation loops with a single GPU (i.e., no
distribution strategy), and is framework-agnostic (will work just as
well with a TF, Jax, or PyTorch model, given an `uncertainty_estimator_fn`
to cast to NumPy ndarrays.
Args:
datasets: Dict[str, tf.data.Dataset], datasets on which we evaluate the
model.
steps: Dict[str, int], number of gradient steps in each dataset.
estimator: model wrapped to produce a `np.ndarray`, predictive mean, with
shape [B].
estimator_args: Dict, extra args for the `uncertainty_estimator_fn`, such as
the number of MC samples, `num_samples`.
uncertainty_estimator_fn: Callable, method to produce predictive means along
with various metrics of uncertainty, e.g., predictive_entropy, epistemic
uncertainty (mutual information).
eval_batch_size: int, size of evaluation minibatches.
is_deterministic: bool, is the model a single deterministic network. In this
case, we cannot capture epistemic uncertainty.
distribution_shift: which distribution shift to run on.
num_bins: the number of bins to use for ECE.
np_input: bool, True if the model expects a NumPy input; we add a cast.
Returns:
Dict, for each dataset, contains `np.array` predictions, ground truth,
and uncertainty estimates.
"""
eval_results = evaluate_model_on_datasets_np(
datasets,
steps,
estimator,
estimator_args,
uncertainty_estimator_fn,
eval_batch_size,
is_deterministic=is_deterministic,
np_input=np_input)
if distribution_shift == 'aptos':
# TODO(nband): generalize
aptos_metadata_path = 'gs://ub-data/aptos/metadata.csv'
eval_results['ood_test_balanced'] = compute_rebalanced_aptos_dataset(
aptos_dataset=eval_results['ood_test'],
aptos_metadata_path=aptos_metadata_path,
new_aptos_size=10000)
# For each eval dataset, add NLL and accuracy for each example
eval_results = compute_loss_and_accuracy_arrs_for_all_datasets(eval_results)
# Precompute ROC/PR curves, retention and balanced retention curves
logging.info('Precomputing ROC/PR curves, retention and balanced'
' retention curves.')
eval_results = precompute_arrs_for_all_datasets(eval_results=eval_results)
logging.info('Computing metrics with precomputed arrs.')
metrics_results = compute_metrics_for_all_datasets(
eval_results,
use_precomputed_arrs=True,
ece_num_bins=num_bins,
compute_retention_auc=True,
verbose=False)
# Log metrics
available_splits = [split for split in eval_results.keys()]
metrics_results = metric_utils.log_epoch_metrics(
metrics=None,
eval_results=metrics_results,
use_tpu=False,
dataset_splits=available_splits)
return eval_results, metrics_results
def compute_metrics_for_all_datasets(eval_results,
use_precomputed_arrs,
ece_num_bins=15,
compute_retention_auc=False,
verbose=False):
"""Computes scalar metrics for all datasets.
Args:
eval_results: Dict[str, Dict], evaluation results for each dataset.
use_precomputed_arrs: selects which eval function to use.
ece_num_bins: int, used to compute expected calibration error metric.
compute_retention_auc: bool, should compute retention metrics.
verbose: bool, extra logging.
Returns:
Dict[str, Dict], scalar metric results for each dataset.
"""
dataset_eval_fn = (
compute_dataset_eval_metrics_with_precomputed_arrs
if use_precomputed_arrs else compute_dataset_eval_metrics)
metric_results = {}
for dataset_key, results_dict in eval_results.items():
if verbose:
logging.info(f'Computing metrics for dataset split {dataset_key}.')
compute_open_set_recognition = 'joint' in dataset_key
metric_results[dataset_key] = dataset_eval_fn(
dataset_key,
results_dict,
ece_num_bins=ece_num_bins,
compute_open_set_recognition=compute_open_set_recognition,
compute_retention_auc=compute_retention_auc)
return metric_results
def precompute_arrs_for_all_datasets(eval_results, verbose=False):
"""Precompute metric arrays for all datasets, e.g., log loss, retention
arrays, etc.
Args:
eval_results: Dict[str, Dict], evaluation results for each dataset.
verbose: bool, extra logging.
Returns:
Dict[str, Dict], metric arrays for each dataset.
"""
for dataset_key, results_dict in eval_results.items():
if verbose:
logging.info(f'Computing metrics for dataset split {dataset_key}.')
compute_open_set_recognition = 'joint' in dataset_key
eval_results[dataset_key] = precompute_metric_arrs(
results=results_dict,
compute_open_set_recognition=compute_open_set_recognition)
return eval_results
def compute_loss_and_accuracy_arrs_for_all_datasets(eval_results):
"""Compute loss and accuracy arrays for each dataset.
Args:
eval_results: Dict[str, Dict], evaluation results for each dataset.
Returns:
Dict[str, Dict], loss and accuracy arrays for each dataset.
"""
for dataset_key, results_dict in eval_results.items():
eval_results[dataset_key] = compute_loss_and_accuracy_arrs(results_dict)
return eval_results
def compute_loss_and_accuracy_arrs(results):
"""Compute loss and accuracy arrays for a particular dataset results dict.
Args:
results: Dict, evaluation results for a single dataset.
Returns:
Dict, loss and accuracy arrays for a single dataset.
"""
results = compute_log_loss_arr(results)
y_pred, y_true = results['y_pred'], results['y_true']
results['accuracy_arr'] = y_true == (y_pred > 0.5)
return results
def compute_log_loss_arr(results, labels=np.asarray([0, 1]), eps=1e-15):
"""Based on sklearn.preprocessing.log_loss, no aggregation.
Args:
results: Dict, evaluation results for a single dataset.
labels: np.ndarray, binary classification task labels.
eps: float, for numerical stability.
Returns:
Dict containing unaggregated log loss `np.ndarray`.
"""
y_pred, y_true = results['y_pred'], results['y_true']
y_pred = check_array(y_pred, ensure_2d=False)
check_consistent_length(y_pred, y_true, None)
lb = LabelBinarizer()
if labels is not None:
lb.fit(labels)
else:
lb.fit(y_true)
if len(lb.classes_) == 1:
if labels is None:
raise ValueError('y_true contains only one label ({0}). Please '
'provide the true labels explicitly through the '
'labels argument.'.format(lb.classes_[0]))
else:
raise ValueError('The labels array needs to contain at least two '
'labels for log_loss, '
'got {0}.'.format(lb.classes_))
transformed_labels = lb.transform(y_true)
if transformed_labels.shape[1] == 1:
transformed_labels = np.append(
1 - transformed_labels, transformed_labels, axis=1)
# Clipping
y_pred = np.clip(y_pred, eps, 1 - eps)
# If y_pred is of single dimension, assume y_true to be binary
# and then check.
if y_pred.ndim == 1:
y_pred = y_pred[:, np.newaxis]
if y_pred.shape[1] == 1:
y_pred = np.append(1 - y_pred, y_pred, axis=1)
# Check if dimensions are consistent.
transformed_labels = check_array(transformed_labels)
if len(lb.classes_) != y_pred.shape[1]:
if labels is None:
raise ValueError('y_true and y_pred contain different number of '
'classes {0}, {1}. Please provide the true '
'labels explicitly through the labels argument. '
'Classes found in '
'y_true: {2}'.format(transformed_labels.shape[1],
y_pred.shape[1], lb.classes_))
else:
raise ValueError('The number of classes in labels is different '
'from that in y_pred. Classes found in '
'labels: {0}'.format(lb.classes_))
# Renormalize
y_pred /= y_pred.sum(axis=1)[:, np.newaxis]
loss = -(transformed_labels * np.log(y_pred)).sum(axis=1)
results['nll_arr'] = loss
return results
def compute_rebalanced_aptos_dataset(aptos_dataset,
aptos_metadata_path,
new_aptos_size=10000):
"""The APTOS dataset has a significantly different underlying distribution
of clinical severity (e.g., there are far more severe examples) versus
the EyePACS dataset.
This might tend to inflate the performance of a model (by providing more
easily classified "severe" examples) without rebalancing of the dataset
and metrics.
Here we match the test empirical distribution of EyePACS by sampling
from each underlying category with replacement, bringing the total size
of the dataset to `new_aptos_size`.
Args:
aptos_dataset: Dict, predictions and ground truths on the APTOS dataset.
aptos_metadata_path: str, location of APTOS metadata (names and clinical
labels of each example).
new_aptos_size: int, target size of the new rebalanced APTOS dataset.
Returns:
Dict, rebalanced APTOS dataset predictions, ground truths, etc.
"""
# EyePACS Test Data: clinical severity label to proportion of dataset
label_to_proportion = {
0: 0.7359503164,
1: 0.07129130537,
2: 0.1472228732,
3: 0.0228966487,
4: 0.02263885634
}
# Load in APTOS metadata
aptos_metadata_df = results_storage_utils.load_dataframe_gfile(
file_path=aptos_metadata_path, sep=',')
name_to_diagnosis = dict(
zip(aptos_metadata_df['id_code'], aptos_metadata_df['diagnosis']))
# Determine location of indices corresponding to each diagnosis
diagnosis_to_indices = collections.defaultdict(list)
names = aptos_dataset['names']
for i, name in enumerate(names):
try:
name = name.decode('utf-8')
except UnicodeDecodeError:
name = str(name)
diagnosis = int(name_to_diagnosis[name])
diagnosis_to_indices[diagnosis].append(i)
# Uniformly sample without replacement to form a new dataset,
# with approximately same proportions as EyePACS Test Data
# and total size ~10000
new_indices = []
for diagnosis, indices in diagnosis_to_indices.items():
total_count_in_new_dataset = int(label_to_proportion[diagnosis] *
new_aptos_size)
new_indices.append(
np.random.choice(
indices, size=total_count_in_new_dataset, replace=True))
new_indices = np.concatenate(new_indices)
new_aptos_dataset = {}
for key, value in aptos_dataset.items():
try:
new_aptos_dataset[key] = value[new_indices]
except IndexError:
new_aptos_dataset[key] = value
return new_aptos_dataset
def compute_rebalanced_retention_curves(results: Dict[str, Any]):
"""Compute rebalanced retention curves.
Compute rebalanced retention curves, which are used for joint (ID + OOD)
tuning. This is done by repeating the OOD indices many times, and then
bringing the number of OOD indices to the number of ID indices by sampling
from the OOD indices without replacement.
Args:
results: Dict, results for a particular dataset (must be joint to have the
`is_ood` key, for a binary `np.ndarray`.
Returns:
Dict, contains rebalanced retention curves.
"""
y_pred_entropy, is_ood = results['y_pred_entropy'], results['is_ood']
# Convert the boolean list to numpy array
is_ood = np.array(is_ood)
in_domain_indices = np.where(is_ood == 0)[0]
n_in_domain = in_domain_indices.shape[0]
ood_indices = np.where(is_ood == 1)[0]
n_ood = ood_indices.shape[0]
# We first tile the OOD indices this many times
n_ood_repeats = int(n_in_domain / n_ood)
# To bring the number of OOD indices = the number of ID indices, we sample
# the necessary indices without replacement
remaining_n_ood_indices = n_in_domain - (n_ood_repeats * n_ood)
remaining_ood_indices = np.random.choice(
ood_indices, size=remaining_n_ood_indices, replace=False)
# Construct a list of all of the indices to retrieve
all_indices = (
in_domain_indices.tolist() + (n_ood_repeats * ood_indices.tolist()) +
remaining_ood_indices.tolist())
# Construct predictive entropy, accuracy, NLL arrays with these indices
rebalanced_y_pred_entropy = y_pred_entropy[all_indices]
rebalanced_accuracy = results['accuracy_arr'][all_indices]
rebalanced_nll = results['nll_arr'][all_indices]
rebalanced_accuracy_retention_curve = compute_retention_curve_on_accuracies(
accuracies=rebalanced_accuracy, uncertainty=rebalanced_y_pred_entropy)
rebalanced_nll_retention_curve = compute_retention_curve_on_losses(
losses=rebalanced_nll, uncertainty=rebalanced_y_pred_entropy)
y_pred = results['y_pred']
y_true = results['y_true']
rebalanced_auroc_retention_curve = compute_auc_retention_curve(
y_pred=y_pred, y_true=y_true, uncertainty=y_pred_entropy, auc_str='roc')
rebalanced_auprc_retention_curve = compute_auc_retention_curve(
y_pred=y_pred, y_true=y_true, uncertainty=y_pred_entropy, auc_str='prc')
return {
'accuracy': rebalanced_accuracy_retention_curve,
'nll': rebalanced_nll_retention_curve,
'auroc': rebalanced_auroc_retention_curve,
'auprc': rebalanced_auprc_retention_curve
}
def compute_rebalanced_retention_scores(results: Dict[str, Any]):
"""Computes rebalanced retention curves, then the mean to get an AUC.
Args:
results: Dict, results for a particular dataset (must be joint to have the
`is_ood` key, for a binary `np.ndarray`.
Returns:
Dict, contains the AUCs of the retention curves built on various
base metrics.
"""
rebalanced_curves = compute_rebalanced_retention_curves(results)
return {
'accuracy': np.mean(rebalanced_curves['accuracy']),
'nll': np.mean(rebalanced_curves['nll']),
'auroc': np.mean(rebalanced_curves['auroc']),
'auprc': np.mean(rebalanced_curves['auprc'])
}
def precompute_metric_arrs(results, compute_open_set_recognition=False):
"""Compute retention arrays and ROC/PR curves.
Used for caching to do downstream plots and scalar metrics quickly.
Args:
results: dict, results for a particular dataset split.
compute_open_set_recognition: bool, if True, compute OOD detection PR and
AUROC metrics.
Returns:
Dict, contains retention arrays and ROC/PR curves.
"""
y_true = results['y_true']
y_pred = results['y_pred']
y_pred_entropy = results['y_pred_entropy']
# Compute ROC curve
# try:
results['fpr_arr'], results['tpr_arr'], _ = roc_curve(
y_true=y_true, y_score=y_pred)
# except:
# pass
# Compute PR curve
# try:
results['precision_arr'], results['recall_arr'], _ = precision_recall_curve(
y_true=y_true, probas_pred=y_pred)
# except:
# pass
if compute_open_set_recognition:
is_ood = results['is_ood']
results['ood_detection_fpr_arr'], results['ood_detection_tpr_arr'], _ = (
roc_curve(y_true=is_ood, y_score=y_pred_entropy))
(results['ood_detection_precision_arr'],
results['ood_detection_recall_arr'], _) = (
precision_recall_curve(y_true=is_ood, probas_pred=y_pred_entropy))
# For the joint datasets, we also compute a rebalanced retention metric,
# in which we duplicate the OOD dataset to match the size of the in-domain
# dataset, and then compute the retention metrics.
ret_curves = compute_rebalanced_retention_curves(results)
results['balanced_retention_accuracy_arr'] = ret_curves['accuracy']
results['balanced_retention_nll_arr'] = ret_curves['nll']
results['balanced_retention_auroc_arr'] = ret_curves['auroc']
results['balanced_retention_auprc_arr'] = ret_curves['auprc']
# Retention curves
assert 'accuracy_arr' in results
assert 'nll_arr' in results
results['retention_accuracy_arr'] = compute_retention_curve_on_accuracies(
accuracies=results['accuracy_arr'], uncertainty=y_pred_entropy)
results['retention_nll_arr'] = compute_retention_curve_on_losses(
losses=results['nll_arr'], uncertainty=y_pred_entropy)
results['retention_auroc_arr'] = compute_auc_retention_curve(
y_pred=y_pred, y_true=y_true, uncertainty=y_pred_entropy, auc_str='roc')
results['retention_auprc_arr'] = compute_auc_retention_curve(
y_pred=y_pred, y_true=y_true, uncertainty=y_pred_entropy, auc_str='prc')
return results
def compute_dataset_eval_metrics_with_precomputed_arrs(
dataset_key,
results,
ece_num_bins=15,
compute_open_set_recognition=False,
compute_retention_auc=False):
"""Compute scalar metrics using cached retention and ROC/PR curves for
efficiency.
Args:
dataset_key: str, name of dataset (prepends each metric in returned Dict).
results: Dict, results for a particular dataset split including precomputed
arrays.
ece_num_bins: int, number of bins used in computing expected calibration
error.
compute_open_set_recognition: bool, if True, compute OOD detection PR and
AUROC metrics.
compute_retention_auc: bool, if True, compute retention AUC metrics by
taking the mean of the retention arrays.
Returns:
Dict, scalar metrics.
"""
y_pred = results['y_pred']
y_true = results['y_true']
eval_metrics = dict()
# Standard predictive metrics
eval_metrics[f'{dataset_key}/negative_log_likelihood'] = log_loss(
y_pred=y_pred, y_true=y_true, labels=np.asarray([0, 1]))
if 'fpr_arr' in results.keys() and 'tpr_arr' in results.keys():
eval_metrics[f'{dataset_key}/auroc'] = auc(results['fpr_arr'],
results['tpr_arr'])
else:
eval_metrics[f'{dataset_key}/auroc'] = None
if 'precision_arr' in results.keys() and 'recall_arr' in results.keys():
recall = results['recall_arr']
precision = results['precision_arr']
eval_metrics[f'{dataset_key}/auprc'] = auc(recall, precision)
eval_metrics[f'{dataset_key}/accuracy'] = (
accuracy_score(y_true=y_true, y_pred=(y_pred > 0.5)))
# Uncertainty metrics
ece = rm.metrics.ExpectedCalibrationError(num_bins=ece_num_bins)
ece.add_batch(y_pred, label=y_true)
eval_metrics[f'{dataset_key}/ece'] = ece.result()['ece']
if compute_open_set_recognition:
eval_metrics[f'{dataset_key}/ood_detection_auroc'] = auc(
results['ood_detection_fpr_arr'], results['ood_detection_tpr_arr'])
eval_metrics[f'{dataset_key}/ood_detection_auprc'] = auc(
results['ood_detection_recall_arr'],
results['ood_detection_precision_arr'])
eval_metrics[f'{dataset_key}/balanced_retention_accuracy_auc'] = np.mean(
results['balanced_retention_accuracy_arr'])
eval_metrics[f'{dataset_key}/balanced_retention_nll_auc'] = np.mean(
results['balanced_retention_nll_arr'])
eval_metrics[f'{dataset_key}/balanced_retention_auroc_auc'] = np.mean(
results['balanced_retention_auroc_arr'])
eval_metrics[f'{dataset_key}/balanced_retention_auprc_auc'] = np.mean(
results['balanced_retention_auprc_arr'])
else:
# This is added for convenience when logging (so the entry exists
# in tabular format)
eval_metrics[f'{dataset_key}/ood_detection_auroc'] = None
eval_metrics[f'{dataset_key}/ood_detection_auprc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_accuracy_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_nll_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_auroc_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_auprc_auc'] = None
if compute_retention_auc:
assert 'accuracy_arr' in results
assert 'nll_arr' in results
eval_metrics[f'{dataset_key}/retention_accuracy_auc'] = np.mean(
results['retention_accuracy_arr'])
eval_metrics[f'{dataset_key}/retention_nll_auc'] = np.mean(
results['retention_nll_arr'])
eval_metrics[f'{dataset_key}/retention_auroc_auc'] = np.mean(
results['retention_auroc_arr'])
eval_metrics[f'{dataset_key}/retention_auprc_auc'] = np.mean(
results['retention_auprc_arr'])
return eval_metrics
def compute_dataset_eval_metrics(
dataset_key,
results,
ece_num_bins=15,
compute_open_set_recognition=False,
compute_retention_auc=False,
):
"""Compute scalar metrics.
Args:
dataset_key: str, name of dataset (prepends each metric in returned Dict).
results: Dict, results for a particular dataset split.
ece_num_bins: int, number of bins used in computing expected calibration
error.
compute_open_set_recognition: bool, if True, compute OOD detection PR and
AUROC metrics.
compute_retention_auc: bool, if True, compute retention AUC metrics by
taking the mean of the retention arrays.
Returns:
Dict, scalar metrics.
"""
y_pred, y_true, y_pred_entropy = (results['y_pred'], results['y_true'],
results['y_pred_entropy'])
eval_metrics = dict()
# Standard predictive metrics
eval_metrics[f'{dataset_key}/negative_log_likelihood'] = log_loss(
y_pred=y_pred, y_true=y_true, labels=np.asarray([0, 1]))
try:
eval_metrics[f'{dataset_key}/auroc'] = roc_auc_score(
y_true=y_true, y_score=y_pred, labels=np.asarray([0, 1]))
except ValueError:
eval_metrics[f'{dataset_key}/auroc'] = None
precision, recall, _ = precision_recall_curve(
y_true=y_true, probas_pred=y_pred)
eval_metrics[f'{dataset_key}/auprc'] = auc(recall, precision)
eval_metrics[f'{dataset_key}/accuracy'] = (
accuracy_score(y_true=y_true, y_pred=(y_pred > 0.5)))
# Uncertainty metrics
ece = rm.metrics.ExpectedCalibrationError(num_bins=ece_num_bins)
ece.add_batch(y_pred, label=y_true)
eval_metrics[f'{dataset_key}/ece'] = ece.result()['ece']
if compute_open_set_recognition:
is_ood = results['is_ood']
eval_metrics[f'{dataset_key}/ood_detection_auroc'] = roc_auc_score(
y_true=is_ood, y_score=y_pred_entropy)
precision, recall, _ = precision_recall_curve(
y_true=is_ood, probas_pred=y_pred_entropy)
eval_metrics[f'{dataset_key}/ood_detection_auprc'] = auc(recall, precision)
# For the joint datasets, we also compute a rebalanced retention metric,
# in which we duplicate the OOD dataset to match the size of the in-domain
# dataset, and then compute the retention metrics.
rebal_ret_scores = compute_rebalanced_retention_scores(results)
eval_metrics[f'{dataset_key}/balanced_retention_accuracy_auc'] = (
rebal_ret_scores['accuracy'])
eval_metrics[f'{dataset_key}/balanced_retention_nll_auc'] = (
rebal_ret_scores['nll'])
eval_metrics[f'{dataset_key}/balanced_retention_auroc_auc'] = (
rebal_ret_scores['auroc'])
eval_metrics[f'{dataset_key}/balanced_retention_auprc_auc'] = (
rebal_ret_scores['auprc'])
else:
# This is added for convenience when logging (so the entry exists
# in tabular format)
eval_metrics[f'{dataset_key}/ood_detection_auroc'] = None
eval_metrics[f'{dataset_key}/ood_detection_auprc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_accuracy_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_nll_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_auroc_auc'] = None
eval_metrics[f'{dataset_key}/balanced_retention_auprc_auc'] = None
if compute_retention_auc:
assert 'accuracy_arr' in results
assert 'nll_arr' in results
eval_metrics[f'{dataset_key}/retention_accuracy_auc'] = np.mean(
compute_retention_curve_on_accuracies(
accuracies=results['accuracy_arr'], uncertainty=y_pred_entropy))
eval_metrics[f'{dataset_key}/retention_nll_auc'] = np.mean(
compute_retention_curve_on_losses(
losses=results['nll_arr'], uncertainty=y_pred_entropy))
eval_metrics[f'{dataset_key}/retention_auroc_auc'] = np.mean(
compute_auc_retention_curve(
y_pred=y_pred,
y_true=y_true,
uncertainty=y_pred_entropy,
auc_str='roc'))
eval_metrics[f'{dataset_key}/retention_auprc_auc'] = np.mean(
compute_auc_retention_curve(
y_pred=y_pred,
y_true=y_true,
uncertainty=y_pred_entropy,
auc_str='prc'))
return eval_metrics
def compute_roc_curve(y_uncertainty: np.ndarray, is_ood: np.ndarray):
"""Compute OOD detection ROC curve using sklearn methods.
Args:
y_uncertainty: np.ndarray, uncertainty scores for each example.
is_ood: np.ndarray, Boolean array indicating if an example is from the OOD
dataset (True) or in-domain (False).
Returns:
Tuple[np.ndarray, np.ndarray, np.float]:
FPR curve, TPR curve, and ROC-AUC value.
"""
fpr, tpr, _ = roc_curve(y_true=is_ood, y_score=y_uncertainty)
roc_auc = auc(x=fpr, y=tpr)
return fpr, tpr, roc_auc
def get_retention_curve_normalizer(use_oracle, n_objects):
"""Obtain normalization constants for each entry of the unnormalized
retention curve.
When using an oracle, we divide by the total number of objects.
When not, we divide by the object index (i.e., the number of objects used
to compute the model metric at each referral rate).
Args:
use_oracle: Bool, if True, evaluate the combined predictive performance
of the model and an oracle that is correct on all referred datapoints.
n_objects: int, number of objects used to create the retention curve.
"""
if use_oracle:
return n_objects
else:
# e.g., for 5 objects, returns [5, 4, 3, 2, 1, 1], where the extra
# element at the end divides the term corresponding to referring
# all examples.
normalizer = np.arange(n_objects + 1)
normalizer[0] = 1
return normalizer[::-1]
def compute_retention_curve_on_losses(losses, uncertainty, use_oracle=False):
"""Computes a retention curve on a loss (where lower loss is better)
and corresponding per-example uncertainty values.
Based on utils by Andrey Malinin, Yandex Research.
https://github.com/yandex-research/shifts/blob/main/weather/assessment.py
Args:
losses: np.ndarray, losses from a particular dataset.
uncertainty: np.ndarray, per-example uncertainties for the same dataset,
should follow the order of the losses.
use_oracle: Bool (default: False), if True, evaluate the combined predictive
performance of the model and an oracle that is correct on all referred
datapoints.
Returns:
np.ndarray, retention curve at all possible retention thresholds,
including all examples retained (i.e., no referral) and no examples
retained (i.e., all points referred to an expert).
"""
n_objects = losses.shape[0]
uncertainty_order = uncertainty.argsort()
# Losses in order of increasing uncertainty
losses = losses[uncertainty_order]
error_rates = np.zeros(n_objects + 1)
error_rates[:-1] = np.cumsum(losses)[::-1]
# With oracle:
# * Divide by total number of predictions
# Without oracle:
# * Divide by only the number of predictions the model must make at each
# * referral rate
normalizer = get_retention_curve_normalizer(use_oracle, n_objects)
error_rates = error_rates / normalizer
return error_rates
def compute_retention_curve_on_accuracies(
accuracies,
uncertainty,
use_oracle=False
):
"""Computes a retention curve on an accuracy (where higher accuracy is better)
and corresponding per-example uncertainty values.
Based on utils by Andrey Malinin, Yandex Research.
https://github.com/yandex-research/shifts/blob/main/weather/assessment.py
Args:
accuracies: np.ndarray, accuracies from a particular dataset.
uncertainty: np.ndarray, per-example uncertainties for the same dataset,
should follow the order of the accuracies.
use_oracle: Bool (default: False), if True, evaluate the combined predictive
performance of the model and an oracle that is correct on all referred
datapoints.
Returns:
np.ndarray, retention curve at all possible retention thresholds,
including all examples retained (i.e., no referral) and no examples
retained (i.e., all points referred to an expert).
"""
n_objects = accuracies.shape[0]
uncertainty_order = uncertainty.argsort()
# Per-point accuracy (binary) in order of increasing uncertainty
accuracies = accuracies[uncertainty_order]
retention_arr = np.zeros(n_objects + 1)
for i in range(1, n_objects):
accuracy_i = accuracies[:i].sum()
if use_oracle:
j = n_objects - i
accuracy_i += j
retention_arr[i] = accuracy_i
# With oracle:
# * Divide by total number of predictions
# Without oracle:
# * Divide by only the number of predictions the model must make at each
# * referral rate
normalizer = get_retention_curve_normalizer(use_oracle, n_objects)
# Assume perfect performance when all examples have been referred.
retention_arr[0] = n_objects if use_oracle else 1
retention_arr[-1] = accuracies.sum()
acc_rates = retention_arr[::-1] / normalizer
return acc_rates
def compute_auc_retention_curve(y_pred,
y_true,
uncertainty,
auc_str,
n_buckets=100,
use_oracle=False):
"""Computes a retention curve for AUC or AUPRC using predictions, ground
truths, and corresponding per-example uncertainty values.
Based on utils by Andrey Malinin, Yandex Research.
https://github.com/yandex-research/shifts/blob/main/weather/assessment.py
Args:
y_pred: np.ndarray, predicted sigmoid probabilities.
y_true: np.ndarray, ground truth values.
uncertainty: np.ndarray, per-example uncertainties for the same dataset,
should follow the order of the accuracies.
auc_str: str, determines if we evaluate the retention AUC or AUPRC.
n_buckets: int, number of retention thresholds to evaluate (AUC can be
costly to evaluate for thousands of possible thresholds.
use_oracle: Bool (default: False), if True, evaluate the combined predictive
performance of the model and an oracle that is correct on all referred
datapoints.
Returns:
np.ndarray, AUC or AUPRC retention curve at specified number of thresholds.
"""
def compute_auroc(true, pred):
return roc_auc_score(y_true=true, y_score=pred)
def compute_auprc(true, pred):
precision, recall, _ = precision_recall_curve(y_true=true, probas_pred=pred)
return auc(recall, precision)
if auc_str == 'roc':
auc_fn = compute_auroc
elif auc_str == 'prc':
auc_fn = compute_auprc
else:
raise NotImplementedError
n_objects = y_pred.shape[0]
bucket_indices = (np.arange(n_buckets) / n_buckets) * n_objects
bucket_indices = bucket_indices.astype(int)
uncertainty_order = uncertainty.argsort()
y_pred = y_pred[uncertainty_order]
y_true = y_true[uncertainty_order]
retention_arr = np.zeros(n_buckets + 1)
if use_oracle:
# We will later divide by n_objects
perfect_performance = n_objects
else:
perfect_performance = 1
# Assume perfect performance when all examples have been referred.
retention_arr[0] = perfect_performance
check_n_unique = True
for i_buckets in range(1, n_buckets):
i_objects = bucket_indices[i_buckets]
j_objects = n_objects - i_objects
y_pred_curr = y_pred[:i_objects]
y_true_curr = y_true[:i_objects]
# For the first few low uncertainty points, we may be predicting the same
# (correct) label, which would break AUC. We default to assigning
# perfect AUC until this condition is broken.
if (check_n_unique and
len(np.unique(y_true_curr)) == 1 and
np.array_equal(y_pred_curr > 0.5, y_true_curr)):
retention_arr[i_buckets] = perfect_performance
else:
try:
auc_val = auc_fn(true=y_true_curr, pred=y_pred_curr)
if use_oracle:
# Weight current AUC/AUPRC by number of objects, and
# add weight of oracle's perfect prediction.
retention_arr[i_buckets] = (i_objects * auc_val) + j_objects
else:
retention_arr[i_buckets] = auc_val
except ValueError: # All of the preds are the same
if use_oracle:
retention_arr[i_buckets] = j_objects
else:
retention_arr[i_buckets] = 0
check_n_unique = False
# Handle the case when no examples have been referred.
try:
auc_val = auc_fn(true=y_true, pred=y_pred)
if use_oracle:
retention_arr[-1] = n_objects * auc_val
else:
retention_arr[-1] = auc_val
except ValueError:
retention_arr[-1] = 0
if use_oracle:
auc_retention = retention_arr[::-1] / n_objects
else:
auc_retention = retention_arr[::-1]
return auc_retention
def compute_ood_calibration_curve(y_pred: np.ndarray):
"""OOO calibration curve.
Form a curve by sweeping over confidences in [0, 1], and counting
the number of predictions with confidence over the threshold.
On an OOD dataset, we should expect low confidence.
Args:
y_pred: np.ndarray, predictions on the OOD dataset
Returns:
Tuple[np.ndarray, np.ndarray]
First np.ndarray:
sorted probabilities for the predicted class
Second np.ndarray:
number of predictions with confidence greater than or equal to
the confidence at a given threshold
"""
# TODO(nband): Debug OOD calibration curve metric.
raise NotImplementedError('Implementation in progress.')
| google/uncertainty-baselines | baselines/diabetic_retinopathy_detection/utils/eval_utils.py | eval_utils.py | py | 52,854 | python | en | code | 1,305 | github-code | 36 | [
{
"api_name": "tensorflow.zeros",
"line_number": 71,
"usage_type": "call"
},
{
"api_name": "tensorflow.zeros",
"line_number": 72,
"usage_type": "call"
},
{
"api_name": "tensorflow.zeros",
"line_number": 73,
"usage_type": "call"
},
{
"api_name": "tensorflow.TensorA... |
7182787702 | #!/usr/bin/env python
# encoding: utf-8
#
# facke-guider.py
#
# Created by José Sánchez-Gallego on 29 Mar 2017.
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import opscore
from opscore.protocols.parser import CommandParser
from opscore.utility.qstr import qstr
from opscore.utility.tback import tback
from opscore.utility.sdss3logging import setupRootLogger, setConsoleLevel
import logging
import opscore.protocols.keys as keys
import opscore.protocols.validation as validation
import actorcore.CommandLinkManager as cmdLinkManager
import actorcore.Command as actorCmd
import actorcore.CmdrConnection
import ConfigParser
import Queue
from twisted.internet import reactor
import imp
import inspect
import os
import re
import sys
import threading
import traceback
class FakeGuider(object):
def __init__(self, name, productName='guiderActor', makeCmdrConnection=True):
self.ii = 1026
self.name = name
self.productName = productName if productName else self.name
product_dir_name = '$%s_DIR' % (self.productName.upper())
self.product_dir = os.path.expandvars(product_dir_name)
self.parser = CommandParser()
self.config = ConfigParser.ConfigParser()
self.config.read(os.path.join(os.path.dirname(__file__), 'guider.cfg'))
self.configureLogs()
# The list of all connected sources.
tronInterface = ''
tronPort = 9994
self.commandSources = cmdLinkManager.listen(self,
port=tronPort,
interface=tronInterface)
# The Command which we send uncommanded output to.
self.bcast = actorCmd.Command(self.commandSources,
'self.0', 0, 0, None, immortal=True)
# IDs to send commands to ourself.
self.selfCID = self.commandSources.fetchCid()
self.synthMID = 1
# commandSets are the command handler packages. Each handles
# a vocabulary, which it registers when loaded.
# We gather them in one place mainly so that "meta-commands" (init, status)
# can find the others.
self.commandSets = {}
self.handler = validation.CommandHandler()
self.attachAllCmdSets()
self.commandQueue = Queue.Queue()
self.shuttingDown = False
if makeCmdrConnection:
self.cmdr = actorcore.CmdrConnection.Cmdr(name, self)
self.cmdr.connectionMade = self._connectionMade
self.cmdr.connect()
else:
self.cmdr = None
def configureLogs(self, cmd=None):
""" (re-)configure our logs. """
self.logDir = self.config.get('logging', 'logdir')
assert self.logDir, "logdir must be set!"
# Make the root logger go to a rotating file. All others derive from this.
setupRootLogger(self.logDir)
# The real stderr/console filtering is actually done through the console Handler.
try:
consoleLevel = int(self.config.get('logging', 'consoleLevel'))
except:
consoleLevel = int(self.config.get('logging', 'baseLevel'))
setConsoleLevel(consoleLevel)
# self.console needs to be renamed ore deleted, I think.
self.console = logging.getLogger('')
self.console.setLevel(int(self.config.get('logging', 'baseLevel')))
self.logger = logging.getLogger('actor')
self.logger.setLevel(int(self.config.get('logging', 'baseLevel')))
self.logger.propagate = True
self.logger.info('(re-)configured root and actor logs')
self.cmdLog = logging.getLogger('cmds')
self.cmdLog.setLevel(int(self.config.get('logging', 'cmdLevel')))
self.cmdLog.propagate = True
self.cmdLog.info('(re-)configured cmds log')
if cmd:
cmd.inform('text="reconfigured logs"')
def versionString(self, cmd):
""" Return the version key value.
If you simply want to generate the keyword, call .sendVersionKey().
"""
cmd.warn("text='pathetic version string: unknown'")
return 'unknown'
def sendVersionKey(self, cmd):
""" Generate the version keyword in response to cmd. """
version = self.versionString(cmd)
cmd.inform('version=%s' % (qstr(version)))
def triggerHubConnection(self):
""" Send the hub a command to connect back to us. """
if not self.cmdr:
self.bcast.warn('text="CANNOT ask hub to connect to us, '
'since we do not have a connection to it yet!"')
return
self.bcast.warn('%s is asking the hub to connect back to us' % (self.name))
self.cmdr.dispatcher.executeCmd(opscore.actor.keyvar.CmdVar
(actor='hub', cmdStr='startNubs %s' % (self.name),
timeLim=5.0))
def _connectionMade(self):
""" twisted arranges to call this when self.cmdr has been established. """
self.bcast.warn('%s is connected to the hub.' % (self.name))
#
# Request that tron connect to us.
#
self.triggerHubConnection()
self.connectionMade()
def connectionMade(self):
""" For overriding. """
pass
def attachCmdSet(self, cname, path=None):
""" (Re-)load and attach a named set of commands. """
if path is None:
path = [os.path.join(self.product_dir, 'python', self.productName, 'Commands')]
self.logger.info("attaching command set %s from path %s", cname, path)
file = None
try:
file, filename, description = imp.find_module(cname, path)
self.logger.debug("command set file=%s filename=%s from path %s",
file, filename, path)
mod = imp.load_module(cname, file, filename, description)
except ImportError as e:
raise RuntimeError('Import of %s failed: %s' % (cname, e))
finally:
if file:
file.close()
# Instantiate and save a new command handler.
cmdSet = getattr(mod, cname)(self)
# Check any new commands before finishing with the load. This
# is a bit messy, as the commands might depend on a valid
# keyword dictionary, which also comes from the module
# file.
#
# BAD problem here: the Keys define a single namespace. We need
# to check for conflicts and allow unloading. Right now we unilaterally
# load the Keys and do not unload them if the validation fails.
if hasattr(cmdSet, 'keys') and cmdSet.keys:
keys.CmdKey.addKeys(cmdSet.keys)
valCmds = []
for v in cmdSet.vocab:
try:
verb, args, func = v
except ValueError as e:
raise RuntimeError("vocabulary word needs three parts: %s" % (v))
# Check that the function exists and get its help.
#
funcDoc = inspect.getdoc(func)
valCmd = validation.Cmd(verb, args, help=funcDoc) >> func
valCmds.append(valCmd)
# Got this far? Commit. Save the Cmds so that we can delete them later.
oldCmdSet = self.commandSets.get(cname, None)
cmdSet.validatedCmds = valCmds
self.commandSets[cname] = cmdSet
# Delete previous set of consumers for this named CmdSet, add new ones.
if oldCmdSet:
self.handler.removeConsumers(*oldCmdSet.validatedCmds)
self.handler.addConsumers(*cmdSet.validatedCmds)
self.logger.debug("handler verbs: %s" % (self.handler.consumers.keys()))
def attachAllCmdSets(self, path=None):
""" (Re-)load all command classes -- files in ./Command which end with Cmd.py.
"""
if path is None:
self.attachAllCmdSets(path=os.path.join(os.path.expandvars('$ACTORCORE_DIR'),
'python', 'actorcore', 'Commands'))
# self.attachAllCmdSets(path=os.path.join(self.product_dir, 'python', self.productName,
# 'Commands'))
return
dirlist = os.listdir(path)
dirlist.sort()
self.logger.info("loading %s" % (dirlist))
for f in dirlist:
if os.path.isdir(f) and not f.startswith('.'):
self.attachAllCmdSets(path=f)
if re.match('^[a-zA-Z][a-zA-Z0-9_-]*Cmd\.py$', f):
self.attachCmdSet(f[:-3], [path])
def cmdTraceback(self, e):
eType, eValue, eTraceback = sys.exc_info()
tbList = traceback.extract_tb(eTraceback)
where = tbList[-1]
return "%r at %s:%d" % (eValue, where[0], where[1])
def runActorCmd(self, cmd):
self.output_file()
try:
cmdStr = cmd.rawCmd
self.cmdLog.debug('raw cmd: %s' % (cmdStr))
try:
validatedCmd, cmdFuncs = self.handler.match(cmdStr)
except Exception as e:
cmd.fail('text=%s' % (qstr("Unmatched command: %s (exception: %s)" %
(cmdStr, e))))
# tback('actor_loop', e)
return
if not validatedCmd:
cmd.fail('text=%s' % (qstr("Unrecognized command: %s" % (cmdStr))))
return
self.cmdLog.info('< %s:%d %s' % (cmd.cmdr, cmd.mid, validatedCmd))
if len(cmdFuncs) > 1:
cmd.warn('text=%s' % (qstr("command has more than one callback (%s): %s" %
(cmdFuncs, validatedCmd))))
try:
cmd.cmd = validatedCmd
for func in cmdFuncs:
func(cmd)
except Exception as e:
oneLiner = self.cmdTraceback(e)
cmd.fail('text=%s' % (qstr("command failed: %s" % (oneLiner))))
# tback('newCmd', e)
return
except Exception as e:
cmd.fail('text=%s' %
(qstr('completely unexpected exception when processing a new command: %s'
% (e))))
try:
tback('newCmdFail', e)
except:
pass
def actor_loop(self):
""" Check the command queue and dispatch commands."""
while True:
try:
cmd = self.commandQueue.get(block=True, timeout=3)
except Queue.Empty:
if self.shuttingDown:
return
else:
continue
self.runActorCmd(cmd)
def commandFailed(self, cmd):
""" Gets called when a command has failed. """
pass
def newCmd(self, cmd):
""" Dispatch a newly received command. """
self.cmdLog.info('new cmd: %s' % (cmd))
# Empty cmds are OK; send an empty response...
if len(cmd.rawCmd) == 0:
cmd.finish('')
return None
if self.runInReactorThread:
self.runActorCmd(cmd)
else:
self.commandQueue.put(cmd)
return self
def callCommand(self, cmdStr):
""" Send ourselves a command. """
cmd = actorCmd.Command(self.commandSources, 'self.%d' % (self.selfCID),
cid=self.selfCID, mid=self.synthMID, rawCmd=cmdStr)
self.synthMID += 1
self.newCmd(cmd)
def _shutdown(self):
self.shuttingDown = True
def run(self, doReactor=True):
""" Actually run the twisted reactor. """
try:
self.runInReactorThread = self.config.getboolean(self.name, 'runInReactorThread')
except:
self.runInReactorThread = False
self.logger.info("starting reactor (in own thread=%s)...." % (not self.runInReactorThread))
try:
if not self.runInReactorThread:
threading.Thread(target=self.actor_loop).start()
if doReactor:
reactor.run()
except Exception as e:
tback('run', e)
if doReactor:
self.logger.info("reactor dead, cleaning up...")
self._shutdown()
def output_file(self):
self.bcast.inform('guideState="on"')
self.bcast.inform('file=/data/gcam/57831/,proc-gimg-{0}.fits.gz'.format(self.ii))
self.ii += 1
reactor.callLater(10, self.output_file)
if __name__ == '__main__':
guider = FakeGuider('guider')
guider.run()
| albireox/lcoHacks | python/lcoHacks/fake-guider.py | fake-guider.py | py | 12,732 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.expandvars",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 49,
"usage_type": "attribute"
},
{
"api_name": "opscore.protocols.parser.CommandParser",
"line_number": 51,
"usage_type": "call"
},
{
"api_name":... |
14412924035 | import util.settings as settings
import time
import sys, getopt
from util.logging import *
from colorama import init
import supermarkets.runner as srunner
def main(argv):
init()
# Parsing of arguments
try:
#opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
opts, args = getopt.getopt(argv,"hve",["help","verbose","error"])
except getopt.GetoptError:
sys.exit(2)
for opt, arg in opts:
if opt == '-h' or opt == '--help':
LogH("SupermarketScraper Help function")
LogH("Permitted parameters are:")
LogH("-h, --help (Show this info)")
LogH("-v, --verbose (Verbose logging)")
LogH("-e, --error (Error logging)")
#LogI("# -t, --tor (Send all trafic via Tor")
sys.exit()
elif opt == '-e' or opt == '--error':
settings.debugging = True
elif opt == '-v' or opt == '--verbose':
settings.verbose = True
# End of argument parsing
start_time = time.time() * 1000
settings.print_info()
LogD("Verbose logging enabled!!\n")
srunner.run()
seconds = (time.time() * 1000) - start_time
PrintLine()
LogI("Scraper finished in {0}ms.\n".format(format(seconds, '.2f')))
if __name__ == '__main__':
main(sys.argv[1:]) | tonsmets/SupermarketScraper | supermarketscraper/main.py | main.py | py | 1,164 | python | en | code | 21 | github-code | 36 | [
{
"api_name": "colorama.init",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "getopt.getopt",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "getopt.GetoptError",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "sys.exit",
"li... |
12404712601 | from vegetation_index import psri_index
from osgeo import gdal
import numpy as np
import zipfile
import os
# adjust with band data filename
target_band = ["B04_10m.jp2", "B08_10m.jp2"]
print(target_band)
zip_folder_path = "./data/2020"
files = os.listdir(zip_folder_path)
# make folder if not exits
output_folder = f"./index/psri/2020"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# shp file
shp_file = './shp/poly_paddy_13.5768_101.717.shp'
for path in files:
zip_file_path = f'{zip_folder_path}/{path}'
file_inside_zip = []
with zipfile.ZipFile(zip_file_path, 'r') as zip_file:
for file_name in zip_file.namelist():
for target_fl in target_band:
if file_name.endswith(target_fl):
file_inside_zip.append(file_name)
# config to accesing the zip
gdal.VSICurlClearCache()
gdal.PushErrorHandler('CPLQuietErrorHandler')
gdal.SetConfigOption('CPL_VSIL_CURL_ALLOWED_EXTENSIONS', 'jp2')
gdal.SetConfigOption('CPL_VSIL_CURL_ALLOWED_EXTENSIONS', 'jp2')
# Open Using Gdal (adjust it with target_band)
b8 = gdal.Open('/vsizip/' + zip_file_path + '/' + file_inside_zip[0])
b4 = gdal.Open('/vsizip/' + zip_file_path + '/' + file_inside_zip[1])
geoTransform = b4.GetGeoTransform()
geoProjection = b4.GetProjection()
nir = b8.GetRasterBand(1).ReadAsArray().astype(np.float32)
red = b4.GetRasterBand(1).ReadAsArray().astype(np.float32)
psri = psri_index(red, nir)
# Save ram
b4 = None
b8 = None
nir = None
red = None
# save psri
driver = gdal.GetDriverByName('GTiff')
output_path = f'{output_folder}/{path.split(".")[0]}.tif'
cols, rows = psri.shape
lon_start = geoTransform[0]
lat_start = geoTransform[3]
pixel_width = geoTransform[1]
pixel_height = geoTransform[5]
lon_values = np.arange(lon_start, lon_start +
cols * pixel_width, pixel_width)
lat_values = np.arange(lat_start, lat_start + rows *
pixel_height, pixel_height)
output_dataset = driver.Create(
output_path, cols, rows, 1, gdal.GDT_Float32)
output_dataset.GetRasterBand(1).WriteArray(psri)
output_dataset.SetGeoTransform(geoTransform)
output_dataset.SetProjection(geoProjection)
metadata = {
'Latitude': ' '.join(map(str, lat_values)),
'Longitude': ' '.join(map(str, lon_values))
}
output_dataset.SetMetadata(metadata)
print(f"Extract {path} : Completed")
| primagiant/auto-mapping-and-predicting-crops-production | utils/index/psri_calc.py | psri_calc.py | py | 2,539 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.listdir",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "os.path.exists",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "os.makedirs",
"line_number... |
16055989419 | import discord
from discord.ext import commands
from core.classes import Cog_Extension
import json, asyncio, datetime, sqlite3, shutil, os, time
class Task(Cog_Extension):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.time_task_counters = 0
self.bg_task = self.bot.loop.create_task(self.time_task())
async def time_task(self):
await self.bot.wait_until_ready()
with open("setting.json", 'r', encoding='utf-8') as jFile:
jdata = json.load(jFile)
self.channel = self.bot.get_channel(jdata['test_channel'])
while not self.bot.is_closed():
now_time = datetime.datetime.now().strftime("%H%M")
with open('setting.json', 'r', encoding='utf-8') as JJ:
Godjj = json.load(JJ)
if now_time == Godjj['指定排程'] and self.time_task_counters == 0:
await self.channel.send('汪汪汪汪!! 瘋狗動出沒')
self.time_task_counters = 1
await asyncio.sleep(1)
else:
await asyncio.sleep(1) #間隔用
pass
async def record_task(self, num):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
await asyncio.sleep(60)
with open("setting.json", 'r', encoding='utf-8') as jFile:
jdata = json.load(jFile)
now_time = datetime.datetime.now().strftime('%H%M') # X小時X分才進行備份
if now_time == jdata['time']:
#在刪除舊有檔案前 把檔案備份至log資料夾------------------------------------------------------------------
if not os.path.exists(".\\log"): # 檢查有沒有log資料夾
os.mkdir(".\\log")
with open('setting.json', 'r', encoding='utf-8-sig') as jFile:
jdata = json.load(jFile)
cur_path = ("{}.db".format(time.strftime("%Y%m%d%H%M%S\
", time.localtime())))
shutil.copy("log.db", cur_path)
shutil.move(cur_path, jdata['log_path'])
#------------------------------------------------------------------
try:
conn = sqlite3.connect('log.db')
conn.execute("DROP TABLE member")
conn.commit()
conn.close()
except Exception as e:
print("讀取失敗 原因: ", e)
self.channel = self.bot.get_channel(648202897259233355)
await self.channel.send("清除資料庫完成")
@commands.command()
async def cancel_rd_task(self, ctx):
self.rd_task.cancel()
await ctx.send(f'關閉背景任務')
@commands.command()
async def create_rd_task(self, ctx, num: int):
self.rd_task = self.bot.loop.create_task(self.record_task(num))
await ctx.send(f'開始每隔{num}秒自動清除資料庫')
@commands.command()
async def set_channel(self, ctx, ch: int):
self.channel = self.bot.get_channel(ch)
await ctx.send(f'Set Channel: {self.channel.mention}') #mention 標記功能
@commands.command() #使用者可以指定排程
async def set_time(self, ctx, time):
self.counters = 0
with open('setting.json', 'r', encoding='utf-8') as JJ:
Godjj = json.load(JJ)
Godjj['指定排程'] = time #使用者的資料傳入json裡
with open('setting.json', 'w', encoding='utf-8') as JJ:
json.dump(Godjj, JJ, indent=4)
await ctx.send('排程設定成功')
def setup(bot):
bot.add_cog(Task(bot)) | healthyvitamin/discord_bot | discord_bot/cmds/background_task.py | background_task.py | py | 3,875 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "core.classes.Cog_Extension",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "json.load",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.now",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "datetime.da... |
32268751295 | #!/usr/bin/env python
import sys
import os
import shutil
#os.environ['OPENBLAS_NUM_THREADS'] = '1'
import argparse
import subprocess
import requests
import stat
import json
import pathlib
import zipfile
import pysam
import pandas as pd
import numpy as np
from collections import Counter
from functools import reduce
from sys import platform
from nimble.types import Config
from nimble.parse import parse_fasta, parse_filter_config, parse_csv
from nimble.usage import print_usage_and_exit
from nimble.utils import get_exec_name_from_platform, low_complexity_filter_amount, append_path_string
ALIGN_TRIES = 10
ALIGN_TRIES_THRESHOLD = 0
# Generate and write human-editable config json files to disk. Input data is a CSV, FASTA, or both
def generate(file, opt_file, output_path):
(data, config, is_csv_req) = process_file(file, opt_file)
(data_opt, config_opt, is_csv_opt) = process_file(opt_file, file)
final_config = config
if data_opt != None and is_csv_opt:
final_config = config_opt
final_data = None
if data_opt != None:
if is_csv_req:
final_data = collate_data(data_opt, data)
elif is_csv_opt:
final_data = collate_data(data, data_opt)
else:
final_data = data
print("Filtered " + str(low_complexity_filter_amount) + " base pairs from reference library.")
# Write reference and default config to disk
with open(output_path, "w") as f:
json.dump([ final_config.__dict__, final_data.__dict__], f, indent=2)
# Parse a lone FASTA/lone CSV/CSV-FASTA tuple. If there's a lone FASTA, generate a simple library.
# If there's a lone CSV, assume it has sequence information or a genbank link.
# If there is not a lone CSV, assume it contains the metadata and that the sequence information is contained in the FASTA.
def process_file(file, paired_file):
data = None
config = None
is_csv = False
if file:
if pathlib.Path(file).suffix == ".fasta":
(data, config) = parse_fasta(file)
elif pathlib.Path(file).suffix == ".csv" and paired_file:
(data, config) = parse_csv(file, False)
is_csv = True
elif pathlib.Path(file).suffix == ".csv" and not paired_file:
(data, config) = parse_csv(file, True)
is_csv = True
return (data, config, is_csv)
def collate_data(data, metadata):
name_idx = data.headers.index("sequence_name")
sequence_idx = data.headers.index("sequence")
nt_length_idx = data.headers.index("nt_length")
meta_name_idx = metadata.headers.index("sequence_name")
meta_sequence_idx = metadata.headers.index("sequence")
meta_nt_length_idx = metadata.headers.index("nt_length")
metadata.columns[meta_sequence_idx] = ["" for _ in range(0, len(data.columns[sequence_idx]))]
metadata.columns[meta_nt_length_idx] = ["" for _ in range(0, len(data.columns[nt_length_idx]))]
for (from_idx, name) in enumerate(data.columns[name_idx]):
if name not in metadata.columns[meta_name_idx]:
print("Error -- record " + name + " is not found in both input files.")
sys.exit()
update_idx = metadata.columns[meta_name_idx].index(name)
metadata.columns[meta_sequence_idx][update_idx] = data.columns[sequence_idx][from_idx]
metadata.columns[meta_nt_length_idx][update_idx] = data.columns[nt_length_idx][from_idx]
return metadata
# Given the name of a release, download the platform-specific executable from that release.
# Given no name, default to the most recent release.
def download(release):
exec_name = get_exec_name_from_platform()
print("Downloading " + exec_name)
url = ""
if len(release) == 1:
url = (
"https://github.com/BimberLab/nimble-aligner/releases/download/"
+ release[0]
+ "/"
+ exec_name
)
else:
url = (
"https://github.com/BimberLab/nimble-aligner/releases/latest/download/"
+ exec_name
)
# Download aligner
r = requests.get(url)
# The executable will be placed in the python package directory
aligner_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "aligner")
print("Aligner download path: " + aligner_path)
# If we successfully downloaded it, write the file to disk and give it execution permissions if necessary
if r.status_code == 200:
with open(aligner_path, "wb") as f:
f.write(r.content)
if sys.platform == "linux" or sys.platform == "darwin": # If we're on a Unix, ensure permission to write
st = os.stat(aligner_path)
os.chmod(aligner_path, st.st_mode | stat.S_IEXEC | stat.S_IXOTH)
else:
print("Error -- could not download aligner, status code " + str(r.status_code))
sys.exit()
# Check if the aligner exists -- if it does, call it with the given parameters.
def align(reference, output, input, _alignment_path, log_path, num_cores, strand_filter):
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "aligner")
input_ext = os.path.splitext(input[0])[-1].lower()
if os.path.exists(path):
if input_ext == ".bam":
split = input[0].rsplit("/", 1)
sort_input_bam(split, num_cores)
input = [split[0] + "/sorted-" + split[1]]
print("Aligning input data to the reference libraries")
sys.stdout.flush()
library_list = reference.split(",")
processed_param_list = []
for input_file in input:
processed_param_list.extend(["--input", input_file])
processed_param_list.extend(["-c", str(num_cores), "--strand_filter", strand_filter])
for library in library_list:
out_file_append = ""
if len(library_list) > 1:
out_file_append = "." + os.path.splitext(os.path.basename(library))[0]
processed_param_list.extend(["-r", library, "-o", append_path_string(output, out_file_append)])
print(processed_param_list)
proc = subprocess.Popen([path] + processed_param_list)
proc.wait()
return_code = proc.returncode
if input_ext == ".bam" and return_code == 0:
print("Deleting intermediate sorted .bam file")
os.remove(input[0])
return return_code
else:
print("No aligner found. Attempting to download the latest release.\n")
download([])
global ALIGN_TRIES
ALIGN_TRIES = ALIGN_TRIES + 1
if ALIGN_TRIES >= ALIGN_THRESHOLD:
print("Error -- could not find or download aligner.")
sys.exit()
return align(reference, output, input, alignment_path, log_path, num_cores, strand_filter)
def intersect_lists(lists):
# Returns the intersection of all lists in a list
return list(reduce(set.intersection, map(set, lists)))
def write_empty_df(output):
print('No data to parse from input file, writing empty output.')
empty_df = pd.DataFrame(columns=['feature', 'count', 'cell_barcode'])
empty_df.to_csv(output, sep='\t', index=False, compression='gzip', header=False)
def report(input, output):
df = None
# if the file has data, try to read it. write an empty output and return if there is no data.
if os.path.getsize(input) > 0:
try:
df = pd.read_csv(input, sep='\t', compression='gzip')
df.rename(columns={'r1_cb': 'cb', 'r1_umi': 'umi'}, inplace=True) # Use the r1 version of the cb and umi flags
except pd.errors.EmptyDataError:
write_empty_df(output)
return
else:
write_empty_df(output)
return
# If the file is not empty but the DataFrame is, write an empty output
if df.empty:
write_empty_df(output)
return
# Keep only necessary columns
df = df[['features', 'umi', 'cb']]
# Drop rows where 'features', 'umi', or 'cb' are null or empty
df = df.dropna(subset=['features', 'umi', 'cb'])
df = df[(df['features'] != '') & (df['umi'] != '') & (df['cb'] != '')]
# Split the feature strings into lists
df['features'] = df['features'].str.split(',')
# Group by cell barcode (CB) and UMI, aggregate features into a list
df_grouped = df.groupby(['cb', 'umi'])['features'].apply(list)
# Calculate the intersection of features within each UMI
df_grouped = df_grouped.apply(intersect_lists)
# Convert back to a DataFrame
df_grouped = df_grouped.reset_index()
# Identify rows where the intersection resulted in an empty list
empty_intersection_rows = df_grouped['features'].apply(lambda x: len(x) == 0)
# Count these rows and print the number
empty_intersection_count = empty_intersection_rows.sum()
print(f"Dropped {empty_intersection_count} counts due to empty intersections")
# Drop these rows from the DataFrame
df_grouped = df_grouped[~empty_intersection_rows]
# Join the intersected features back into a string
df_grouped['features'] = df_grouped['features'].apply(lambda x: ','.join(x))
# Rename columns
df_grouped.columns = ['cell_barcode', 'umi', 'feature']
# Count unique UMIs per cell_barcode-feature pair
df_counts = df_grouped.groupby(['cell_barcode', 'feature']).size().reset_index()
# Rename count column
df_counts.columns = ['cell_barcode', 'feature', 'count']
# Reorder the columns
df_counts = df_counts.reindex(['feature', 'count', 'cell_barcode'], axis=1)
# Write to output file
df_counts.to_csv(output, sep='\t', index=False, header=False)
def sort_input_bam(file_tuple, cores):
print("Sorting input .bam")
tmp_dir = os.environ.get("TMPDIR")
create_tmp_dir = False
bam = ""
sorted_bam = ""
if len(file_tuple) > 1:
bam = file_tuple[0] + "/" + file_tuple[1]
sorted_bam = file_tuple[0] + "/sorted-" + file_tuple[1]
else:
bam = file_tuple[0]
sorted_bam = "./sorted-" + file_tuple[0]
print("Sorting " + bam + " Outputting to " + sorted_bam)
sys.stdout.flush()
if os.path.isfile(sorted_bam):
print("Sorted bam file already exists, skipping the sorting step.")
sys.stdout.flush()
return
if tmp_dir and not os.path.exists(tmp_dir):
try:
os.makedirs(tmp_dir)
create_tmp_dir = True
print(f"Created temporary directory {tmp_dir}")
except OSError as e:
print(f"Could not create temporary directory {tmp_dir}: {e}")
sys.stdout.flush()
if tmp_dir:
pysam.sort('-t', 'UR', '-n', '-o', sorted_bam, '-@', str(cores), '-T', tmp_dir, bam)
else:
pysam.sort('-t', 'UR', '-n', '-o', sorted_bam, '-@', str(cores), bam)
sort_log = pysam.sort.get_messages()
if (sort_log):
print("samtools messages: " + sort_log)
if create_tmp_dir:
try:
shutil.rmtree(tmp_dir)
print(f"Deleted temporary directory {tmp_dir}")
except Exception as e:
print(f"Could not delete temporary directory {tmp_dir}: {e}")
sys.stdout.flush()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='nimble align')
subparsers = parser.add_subparsers(title='subcommands', dest='subcommand')
download_parser = subparsers.add_parser('download')
download_parser.add_argument('--release', help='The release to download.', type=str, default=[])
generate_parser = subparsers.add_parser('generate')
generate_parser.add_argument('--file', help='The file to process.', type=str, required=True)
generate_parser.add_argument('--opt-file', help='The optional file to process.', type=str, default=None)
generate_parser.add_argument('--output_path', help='The path to the output file.', type=str, required=True)
align_parser = subparsers.add_parser('align')
align_parser.add_argument('--reference', help='The reference genome to align to.', type=str, required=True)
align_parser.add_argument('--output', help='The path to the output file.', type=str, required=True)
align_parser.add_argument('--input', help='The input reads.', type=str, required=True, nargs='+')
align_parser.add_argument('--alignment_path', help='The path to the alignment file.', type=str, default=None)
align_parser.add_argument('--log_path', help='The path to the log file.', type=str, default=None)
align_parser.add_argument('-c', '--num_cores', help='The number of cores to use for alignment.', type=int, default=1)
align_parser.add_argument('--strand_filter', help='Filter reads based on strand information.', type=str, default="unstranded")
report_parser = subparsers.add_parser('report')
report_parser.add_argument('-i', '--input', help='The input file.', type=str, required=True)
report_parser.add_argument('-o', '--output', help='The path to the output file.', type=str, required=True)
args = parser.parse_args()
if args.subcommand == 'download':
download(args.release)
elif args.subcommand == 'generate':
generate(args.file, args.opt_file, args.output_path)
elif args.subcommand == 'align':
sys.exit(align(args.reference, args.output, args.input, args.alignment_path, args.log_path, args.num_cores, args.strand_filter))
elif args.subcommand == 'report':
report(args.input, args.output)
| BimberLab/nimble | nimble/__main__.py | __main__.py | py | 13,434 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "nimble.utils.low_complexity_filter_amount",
"line_number": 50,
"usage_type": "argument"
},
{
"api_name": "json.dump",
"line_number": 54,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 65,
"usage_type": "call"
},
{
"api_name": "... |
28662940889 | import logging
from ..models.formularios.form_accion_sort import Form_Accion_Sorteable
from ..models.formularios.form_campo import Form_Campo
from ..models.formularios.form_campo_sort import Form_Campo_Sorteable
from ..models.formularios.form_elemento import Form_Elemento
from ..models.formularios.form_filtro_param_sort import Form_Filtro_Params_Sorteable
from ..models.formularios.form_filtro_param import Form_Filtro_Param
from ..models.formularios.form_filtro import Form_Filtro
from ..models.formularios.form_formularios import Form_Formulario
from ..models.formularios.form_imagen import Form_Imagen
from ..models.formularios.form_multi import Form_Multi_Option
from ..models.formularios.form_multi_sort import Form_Multi_Options_Sorteable
from ..models.formularios.form_texto import Form_Texto
logger = logging.getLogger(name=__name__)
##################################################################################
# OBTENER FORM
##################################################################################
def obtener_form(solicitud, post=None, files=None, initial=False):
try:
instancia = Form_Formulario.objects.get(solicitud = solicitud)
form = form_to_dict(instancia)
return form
except Exception as e:
logger.error(e)
return "No se encontro el formulario especificado"
##################################################################################
# GENERA EL FORMATO DE LOS DATOS EN LOS CAMPOS QUE SE PUEDEN SORTEAR
##################################################################################
def get_datos_campos_sorteable(modelo, valor):
options_sort = modelo.objects.filter(form_id = valor.id)
dict_base= {}
if not options_sort:
return []
else:
for multi in options_sort:
dict_base.update({ multi.clave : multi.valor })
return dict_base
##################################################################################
# OBTIENE LA CLAVE SEGUN EL TIPO
##################################################################################
def get_clave_tipo(tipo, text, image):
if tipo == 'Texto':
return f'texto_{text}'
elif tipo == 'Imagen':
return f'imagen_{image}'
else:
return False
##################################################################################
# FORMATEA EL FORMULARIO PARA QUE SEA UN DICT PASABLE A JSON
##################################################################################
def form_to_dict(instancia : Form_Formulario):
form = {}
campos_sort = Form_Campo_Sorteable.objects.filter(form_id = instancia.id)
count_text = 0
count_image = 0
for campo_sort in campos_sort:
tipo = campo_sort.get_type()
#####################################################
# CHEQUEAMOS SI ALGUN CAMPO TIENE MAS DE UNA OPCION
#####################################################
if tipo == 'Error':
return "Uno de los campos sorteables tiene seleccionado mas de un tipo, solo aceptan una opcion"
#####################################################
# CHEQUEAMOS SI ALGUN CAMPO ESTA TODO VACIO
#####################################################
elif tipo == 'None':
return "Uno de los campos sorteables esta completamente vacio, eligale una opcion"
#####################################################
# CARGAMOS EL TEXTO
#####################################################
elif tipo == 'Texto':
count_text += 1
obj_texto = Form_Texto.objects.get(id = campo_sort.text_id)
dict_text = {}
for elemento in obj_texto._meta.get_fields():
if elemento.name != 'form_campo_sorteable' and elemento.name != 'id':
valor = getattr(obj_texto, elemento.name)
dict_text.update( { elemento.name : valor } )
dict_text["elemento_html"] = {"tipo": "text"}
dict_text["filtro"] = 8
form.update( { f"texto_{count_text}" : dict_text } )
#####################################################
# CARGAMOS EL IMAGEN
#####################################################
elif tipo == 'Imagen':
count_image += 1
obj_imagen = Form_Imagen.objects.get(id = campo_sort.image_id)
dict_imagen = {}
for elemento in obj_imagen._meta.get_fields():
if elemento.name != 'form_campo_sorteable' and elemento.name != 'id':
valor = getattr(obj_imagen, elemento.name)
dict_imagen.update( { elemento.name : valor } )
dict_imagen["elemento_html"] = {"tipo": "text"}
dict_imagen["filtro"] = 8
form.update( { f"imagen_{count_image}" : dict_imagen } )
#####################################################
# CARGAMOS EL ELEMENTO
#####################################################
elif tipo == 'Campo':
obj_campo = Form_Campo.objects.get(id = campo_sort.field_id)
dict_campo = {}
for elemento in obj_campo._meta.get_fields():
if elemento.name != 'form_campo_sorteable' and elemento.name != 'id' and elemento.name != 'key':
valor = getattr(obj_campo, elemento.name)
if isinstance(valor, Form_Elemento):
dict_campo.update( { elemento.name : valor.get_dict()})
elif isinstance(valor, Form_Filtro):
dict_campo.update( { elemento.name : valor.get_valor()})
elif isinstance(valor, Form_Filtro_Param):
res = get_datos_campos_sorteable(Form_Filtro_Params_Sorteable, valor)
dict_campo.update( { elemento.name : res } )
elif isinstance(valor, Form_Multi_Option):
res = get_datos_campos_sorteable(Form_Multi_Options_Sorteable, valor)
dict_campo.update( { elemento.name : res } )
elif valor is not None:
dict_campo.update( { elemento.name : valor } )
form.update( { obj_campo.key : dict_campo } )
#####################################################
# CARGAMOS ARCHIVO
#####################################################
if campo_sort.file == True:
clave = get_clave_tipo(tipo, count_text, count_image)
if clave :
form[clave].update( { "archivo" : True } )
else:
form[obj_campo.key].update( {"archivo" : True } )
#####################################################
# CARGAMOS FORM ERROR
#####################################################
if campo_sort.form_error == True:
clave = get_clave_tipo(tipo, count_text, count_image)
if clave :
form[clave].update( { "form_error" : True } )
else:
form[obj_campo.key].update( {"form_error" : True } )
#####################################################
# CARGAMOS FORM MENSAJE
#####################################################
if campo_sort.form_message == True:
clave = get_clave_tipo(tipo, count_text, count_image)
if clave :
form[clave].update( { "form_message" : True } )
else:
form[obj_campo.key].update( {"form_message" : True } )
#####################################################
# CARGAMOS MISMA LINEA QUE ELEMENTO ANTERIOR
#####################################################
if campo_sort.form_same_line:
clave = get_clave_tipo(tipo, count_text, count_image)
if clave :
form[clave].update( { "form_same_line" : campo_sort.form_same_line } )
else:
form[obj_campo.key].update( {"form_same_line" : campo_sort.form_same_line } )
#####################################################
# CARGAMOS ACCIONES
#####################################################
if campo_sort.get_action():
acciones_sort = Form_Accion_Sorteable.objects.filter(form_id = campo_sort.action_id)
dict_act = {}
for act in acciones_sort:
dict_act.update( { act.elemento : act.accion } )
clave = get_clave_tipo(tipo, count_text, count_image)
if clave :
form[clave].update( { "acciones" : dict_act } )
else:
form[obj_campo.key].update( {"acciones" : dict_act } )
return form | juanceweb/mayan_local | mayan/apps/unq/functions/functions_formularios.py | functions_formularios.py | py | 8,973 | python | es | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "models.formularios.form_formularios.Form_Formulario.objects.get",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "models.formularios.form_formularios.Form_Formulario.objects",
... |
8574496857 | from djoser.views import UserViewSet
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import IsAuthenticated
class DjoserUserViewSet(UserViewSet):
pagination_class = LimitOffsetPagination
permission_classes = [IsAuthenticated]
def me(self, request, *args, **kwargs):
response = super().me(request, *args, **kwargs)
response.data['is_subscribed'] = False
return response
| ticpragma/foodgram-project-react | foodgram/users/views.py | views.py | py | 452 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "djoser.views.UserViewSet",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "rest_framework.pagination.LimitOffsetPagination",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "rest_framework.permissions.IsAuthenticated",
"line_number": 8,
"us... |
39660373641 | from collections import Counter
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
counter = Counter(nums)
result = []
def backtracking(perm):
if len(perm) == len(nums):
result.append(perm[:])
return
for num in counter:
if counter[num] <= 0:
continue
counter[num] -= 1
perm.append(num)
backtracking(perm)
counter[num] += 1
perm.pop()
backtracking([])
return result | deusi/practice | 47-permutations-ii/47-permutations-ii.py | 47-permutations-ii.py | py | 686 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.Counter",
"line_number": 8,
"usage_type": "call"
}
] |
27162959135 | import gym
import numpy as np
import matplotlib.pyplot as plt
NUM_RUNS = 50
MAX_EPISODE_STEPS = 5000
NUM_EPISODES = 100
NUM_ACTIONS = 3
env = gym.make('MountainCar-v0').env
env._max_episode_steps = MAX_EPISODE_STEPS
POLYNOMIAL_FEATURES = True
POLYNOMIAL_DEGREE = 2
'''
https://github.com/openai/gym/wiki/MountainCar-v0
Summary for me:
There are 3 different actions (push left, nothing, push right) which
correspond to (0, 1, 2).
An state is a pair (position,velocity).
Position ranges from -1.2 to 0.6 and velocity from -0.07 to 0.07
'''
def convert_to_features(state, action, polynomial = POLYNOMIAL_FEATURES,
max_degree = POLYNOMIAL_DEGREE):
if polynomial:
'''
Converts the state to a polynomial of degree max_degree.
However, we cap the degree of action at 1, since we cannot expect
higher powers of action to deliver meaningful extra features.
(Action takes values in (0, 1, 2) )
'''
subfeatures = []
for n in range(max_degree + 1):
for k in range(n+1):
subfeatures += [state[0]**(n-k) * state[1]**(k)]
subfeatures = np.array(subfeatures)
features = np.zeros(2*len(subfeatures))
features[:len(subfeatures)] = subfeatures
features[len(subfeatures):] = action * subfeatures
return features
else:
''' Directly returns the state and action as a feature '''
return np.append(state, action)
state = env.reset()
NUM_FEATURES = len(convert_to_features(state, 0))
learning_rate = 1e-4
discount = 0.9
def action_value(state, action, weights):
''' Approximate the action value of an state'''
features = convert_to_features(state, action)
return features @ weights
def choose_action(state, weights, epsilon = 0.33):
''' A random action will be picked with probability epsilon '''
if epsilon > np.random.uniform():
action = np.random.randint(0, NUM_ACTIONS)
else:
action = np.argmax([action_value(state, action, weights)
for action in range(NUM_ACTIONS)])
return action
def update_weights(previous_state, state, action, next_action,
weights, reward, done = False):
gradient = convert_to_features(previous_state, action)
if done:
update = learning_rate * (reward
- action_value(previous_state, action, weights))
else:
update = learning_rate * (reward
+ discount * action_value(state, next_action, weights)
- action_value(previous_state, action, weights))
update *= gradient
weights -= update # Gradient descent
return weights
''' Calculate average reward per run and per episode '''
average_rewards = np.zeros((NUM_RUNS, NUM_EPISODES))
for j in range(NUM_RUNS):
''' Start of another run '''
print('Run:', j)
weights = np.random.rand(NUM_FEATURES)
for k in range(NUM_EPISODES):
''' Start of another episode '''
state = env.reset()
action = choose_action(state, weights.copy())
cumulative_reward = 0
for step in range(MAX_EPISODE_STEPS):
#env.render()
previous_state = state
state, reward, done, info = env.step(action)
next_action = choose_action(state, weights.copy())
weights = update_weights(previous_state, state, action,
next_action, weights.copy(), reward, done)
cumulative_reward += reward
if done:
break
action = next_action
average_reward = cumulative_reward
average_rewards[j,k] = average_reward
average_rewards_per_run = average_rewards.sum(axis=0)/NUM_RUNS/MAX_EPISODE_STEPS
plt.plot(average_rewards_per_run)
plt.xlabel('Episode')
plt.ylabel('Average reward per episode and run')
if POLYNOMIAL_FEATURES:
title = 'Using polynomial features\n'
else:
title = 'Using states and actions directly as features\n'
title += 'Average of ' + str(NUM_RUNS) + ' runs with ' \
+ str(MAX_EPISODE_STEPS) + ' steps per episode'
plt.title(title) | MaximilianSamsinger/Advanced-Machine-Learning | Assignment 3/Mountain_Car.py | Mountain_Car.py | py | 4,287 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "gym.make",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 45,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "numpy.append",
"line_number": 56... |
72311227944 | import os
import shutil
import subprocess
import traceback
from typing import Any, List
from src.manager.launcher.launcher_interface import ILauncher, LauncherException
class LauncherRos(ILauncher):
"""
Launcher for ROS/Gazebo
It's configuration should follow this spec:
{
"type": "module",
"module": "ros",
"resource_folders": [
"$EXERCISE_FOLDER/launch"
],
"model_folders": [
"$CUSTOM_ROBOTS/f1/models"
],
"plugin_folders": [
],
"parameters": [],
"launch_file": "$EXERCISE_FOLDER/launch/simple_line_follower_ros_headless_default.launch"
}
"""
exercise_id: str
type: str
module: str
resource_folders: List[str]
model_folders: List[str]
plugin_folders: List[str]
parameters: List[str]
launch_file: str
ros_command_line: str = shutil.which('roslaunch')
process: Any = None
def run(self):
try:
# generate entry_point environment variable
os.environ["EXERCISE_FOLDER"] = f"{os.environ.get('EXERCISES_STATIC_FOLDER')}/{self.exercise_id}"
# expand variables in configuration paths
resource_folders = [os.path.expandvars(
path) for path in self.resource_folders]
model_folders = [os.path.expandvars(
path) for path in self.model_folders]
plugin_folders = [os.path.expandvars(
path) for path in self.plugin_folders]
launch_file = os.path.expandvars(self.launch_file)
env = dict(os.environ)
env["GAZEBO_RESOURCE_PATH"] = f"{env.get('GAZEBO_RESOURCE_PATH', '')}:{':'.join(resource_folders)}"
env["GAZEBO_MODEL_PATH"] = f"{env.get('GAZEBO_MODEL_PATH', '')}:{':'.join(model_folders)}"
env["GAZEBO_PLUGIN_PATH"] = f"{env.get('GAZEBO_PLUGIN_PATH', '')}:{':'.join(plugin_folders)}"
parameters = " ".join(self.parameters)
command = f"{self.ros_command_line} {parameters} {launch_file}"
self.process = subprocess.Popen(command, env=env, shell=True,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=subprocess.STDOUT
)
# print(self.process.communicate())
except Exception as ex:
traceback.print_exc()
raise ex
def is_running(self):
return True if self.process.poll() is None else False
def terminate(self):
if self.is_running():
self.process.terminate()
else:
raise LauncherException("The process is not running")
| JdeRobot/RoboticsApplicationManager | manager/manager/launcher/launcher_ros.py | launcher_ros.py | py | 2,764 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "src.manager.launcher.launcher_interface.ILauncher",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 34,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 35,
"usage_type": "name"
},
{
"api_nam... |
27365994887 | import codecs
import json
import uuid
import re
from scrapy.utils.markup import remove_tags
from scrapy.utils.serialize import ScrapyJSONEncoder
from typing import Union
from scrapper.crowler.data.object import Variant, Step
class JsonWithEncodingPipeline(object):
def __init__(self):
self.file = \
codecs.open(f'scraped_data_{uuid.uuid4()}.json',
'w',
encoding='utf-8')
self.parsed_count = 0
self.delete_spaces = re.compile(r"[\f\n\r\t\v]")
def delete_tags(self, text: Union[str, None]) -> Union[str, None]:
if text is not None:
return remove_tags(text)
else:
return None
def process_step(self, step: Step) -> Step:
text = self.delete_spaces.sub("", step["text"])
text = [chunk for chunk in text.split("<p>") if len(chunk) > 2]
step["text"] = "<p>".join(text)
return step
def process_variant(self, variant: Variant) -> Variant:
variant["variant_name"] = self.delete_tags(variant["variant_name"])
variant["steps"] = [
self.process_step(step) for step in variant["steps"]
]
return variant
def process_item(self, article, spider):
if (self.parsed_count + 1) % 1000 == 0:
self.file.close()
self.file = \
codecs.open(f'scraped_data_{uuid.uuid4()}.json',
'w',
encoding='utf-8')
article["variants"] = [
self.process_variant(variant) for variant in article["variants"]
]
line = json.dumps(article, cls=ScrapyJSONEncoder) + "\n"
self.file.write(line)
self.parsed_count += 1
return article
def spider_closed(self, spider):
self.file.close()
| Paleontolog/summarizer_service | crowler/pipelines/pipel.py | pipel.py | py | 1,896 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "codecs.open",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "uuid.uuid4",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "re.compile",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "typing.Union",
"line_number": 2... |
20422284442 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 00:48:35 2019
@author: Vamshi Krishna
"""
import matplotlib.pyplot as plt
emp_names=['vamshi','preethi','santhosh','deexita']
emp_salary=[80000,75000,60000,80000]
plt.pie(emp_salary,labels=emp_names,radius=2,autopct='%0.0f%%',shadow=True,explode=[0.2,0,0,0])
plt.show()
| RevanthR/AI_Assignments | Assignment4piegraph.py | Assignment4piegraph.py | py | 334 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "matplotlib.pyplot.pie",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "matplotlib.pyplot.show",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "matplo... |
6290474507 | # Extract Adobe Analytics data strings from Adobe Assurance (Project Griffon) logs
# 24 Oct 2022 11:18
# Michael Powe
# reminder of what we are looking for
# (json_data['events'][3]['payload']['ACPExtensionEventData']['hitUrl'])
import json
import urllib.parse
from argparse import ArgumentParser
from pprint import pprint
def main():
parser = ArgumentParser()
parser.add_argument("-f", "--file", help="file from which to read")
parser.add_argument("-o", "--output", help="file to which to write results")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="print output to screen as well as to file",
)
args = parser.parse_args()
# source data file (default if no command line input)
griffon_data: str = (
r"c:\Users\micha\Dropbox\src\python\json\data\AssuranceTraining.json"
)
# written output file (default if no command line input)
url_data: str = r"c:\Users\micha\Dropbox\src\python\json\data\assurance-urls.txt"
inputfile: str = args.file if args.file is not None else griffon_data
outputfile: str = args.output if args.output is not None else url_data
context_list: list[str]
uri_list: list[str]
uri_list, context_list = process_file(inputfile, pfarg=args.verbose)
write_data(outputfile, uri_list, context_list)
def process_file(infile: str, pfarg: bool = None) -> tuple[list[str], list[str]]:
"""
Processes the file of JSON generated by Adobe Assurance and collects the
URI data string and the variable context data.
:rtype: object
:param arg: True to print to screen, default is False.
Will be set True by the presence of the `-v` command line option
:type arg: bool
:param infile: Complete path and filename for the file to be processed
:type infile: str
"""
pfarg = True if pfarg is not None and pfarg is not False else False
f = open(infile, "r")
# list to collect matching URIs. It will then be written to file at the end
uri_list: list[str] = []
# list to collect context data
context_list: list[str] = []
json_data: dict = json.load(f)
length: int = len(json_data["events"])
for k in range(length):
try:
# this is what we use for validating data is correct
if "hitUrl" in json_data["events"][k]["payload"]["ACPExtensionEventData"]:
# remove the URI encoding and add to list for printing
item: str = urllib.parse.unquote(
json_data["events"][k]["payload"]["ACPExtensionEventData"].get(
"hitUrl"
)
)
if pfarg:
print(item, "\n")
uri_list.append(item)
# this is what we use for validating context data variables (for SDR, &c)
elif (
"contextdata"
in json_data["events"][k]["payload"]["ACPExtensionEventData"]
):
item = (json_data["events"][k]["payload"]["ACPExtensionEventData"]).get(
"contextdata"
)
if pfarg:
print()
pprint(item)
print()
context_list.append(item)
# 'key' refers to dictionary key, not a keyboard key
except KeyError:
print(">>>>>>>>>> <<<<<<<<<<")
print(">>>>>>>>>> key error, `ACPExtensionEventData` not found <<<<<<<<<<")
print(
">>>>>>>>>> payload is ",
json_data["events"][k]["payload"],
"<<<<<<<<<<",
)
print(">>>>>>>>>> <<<<<<<<<<\n")
f.close()
return uri_list, context_list
def write_data(url_data: str, uri_list: list[str], context_list: list[str]) -> None:
"""
Writes the accumulated URI and context data to a file. URI is written to
the top of the file and context data follows it.
:param uri_list: list in which data URI are captured from `hitUrl`
:type uri_list: list
:param context_list: list in which context data objects are captured
from `contextdata`
:type context_list: list
:param url_data: the JSON file from which the data is to be extracted.
:type url_data: str
"""
w = open(url_data, "w")
# output to file
for i in uri_list:
w.write(i + "\n")
for i in context_list:
w.write("\n")
pprint(i, stream=w)
w.close()
if __name__ == "__main__":
main()
| nyambol/adobe-assurance-json | json-parser.py | json-parser.py | py | 4,571 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "json.load",
"line_number": 64,
"usage_type": "call"
},
{
"api_name": "urllib.parse.parse.unquote",
"line_number": 73,
"usage_type": "call"
},
{
"api_name": "urllib.p... |
4221751433 | #!/usr/bin/env python3
"""
Extensive database of location and timezone data for nearly every airport and landing strip in the world.
"""
from __future__ import annotations
import csv
from pathlib import Path
from typing import Dict, Literal, TypedDict
__project_name__ = __package__
# Release numbering follows the release date
__version__ = '20221121'
__min_python_version__ = (3, 8)
__author__ = 'Mike Borsetti <mike@borsetti.com>'
__copyright__ = 'Copyright 2020- Mike Borsetti'
__license__ = 'MIT'
__url__ = f'https://github.com/mborsetti/{__project_name__}'
Airport = TypedDict(
'Airport',
{
'icao': str,
'iata': str,
'name': str,
'city': str,
'subd': str,
'country': str,
'elevation': float,
'lat': float,
'lon': float,
'tz': str,
'lid': str,
},
)
CodeType = Literal['ICAO', 'IATA', 'LID']
def load(code_type: CodeType = 'ICAO') -> Dict[str, 'Airport']:
"""Loads airport data into a dict
:param code_type: optional argument defining the key in the dictionary: 'ICAO' (default if omitted),
'IATA' (for IATA Location Codes) or 'LID' (for U.S. FAA Location Identifiers).
:return: a dict of dicts, each entry having the following keys:
'icao': ICAO 4-letter Location Indicator or 4-alphanumeric FAA/TC LID
'iata': IATA 3-letter Location Code or an empty string
'name': Official name (latin script)
'city': City
'subd': Subdivision (e.g. state, province, region, etc.)
'country': ISO 3166-1 alpha 2-code (plus 'XK' for Kosovo)
'elevation': MSL elevation (the highest point of the landing area) in feet
'lat': Latitude (decimal)
'lon': Longitude (decimal)
'tz': Timezone expressed as a tz database name (IANA-compliant) or empty string for country 'AQ' (Antarctica).
Originally sourced from [TimeZoneDB](https://timezonedb.com)
'lid': The FAA Location Identifier (for US country only; others is blank)
"""
# with open(os.path.join(dir, 'airports.json'), encoding='utf8') as f:
# airports = json.load(f)
# if code_type.lower() == 'icao':
# return airports
# else:
# return {airport['iata']: airport for airport in dict(airports).values() if airport['iata']}
#
#
key = code_type.lower()
if key not in ('icao', 'iata', 'lid'):
raise ValueError(f'code_type must be one of ICAO, IATA or LID; received {code_type}')
this_dir = Path(__file__).parent
airports: Dict[str, Airport] = {}
with this_dir.joinpath('airports.csv').open(encoding='utf8') as f:
reader = csv.DictReader(f, quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
airports[row[key]] = row # type: ignore[assignment]
airports.pop('', None)
return airports
# Python 3.9 code used to save the dict to CSV:
# with open('airports.csv', 'w', newline='') as f:
# fieldnames = airports[list(airports.keys())[0]].keys()
# writer = csv.DictWriter(f, fieldnames=fieldnames, quoting=csv.QUOTE_NONNUMERIC)
# writer.writeheader()
# for data in airports.values():
# writer.writerow(data)
| legoironman1234/IATAGuesser | IATAGuesser/airportsdata/__init__.py | __init__.py | py | 3,193 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "typing.TypedDict",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "typing.Literal",
"line_number": 38,
"usage_type": "name"
},
{
"api_name": "pathlib.Path",
"line_number": 72,
"usage_type": "call"
},
{
"api_name": "typing.Dict",
"line_... |
21411610014 | from __future__ import absolute_import, division
import scipy.ndimage as ndimage
from matplotlib import widgets
import glob
import datetime
import scipy.interpolate as interpolate
import numpy as np
import matplotlib.pyplot as plt
__all__ = ['Slit']
#==============================================================================
# Slit Class
#==============================================================================
class Slit:
def __init__(self, image_animator):
self.image_animator = image_animator
self.axes = self.image_animator.axes
self.points = []
self.mpl_points = []
self.mpl_curve = []
self.anns = []
self.res = 100
self.curve_points = np.zeros([self.res,2])
self.data = []
self.data_run = []
self.distance = []
def add_point(self, x, y):
self.points.append([x,y])
self.mpl_points.append(self.axes.scatter(x,y))
self.anns.append(self.axes.annotate('%i' % len(self.mpl_points), (x + 1, y + 1)))
self.axes.figure.canvas.draw()
def remove_point(self):
if len(self.mpl_points) > 0:
point = self.mpl_points.pop(-1)
point.set_visible(False)
annote = self.anns.pop(-1)
annote.set_visible(False)
self.points.pop(-1)
self.axes.figure.canvas.draw()
def remove_all(self, slits):
if len(slits) > 0:
for i in range(len(slits)):
if len(slits[i].mpl_points) > 0:
for y in range(len(slits[i].mpl_points)):
point = slits[i].mpl_points.pop()
point.set_visible(False)
annote = slits[i].anns.pop()
annote.set_visible(False)
slits[i].points.pop()
if len(slits[i].mpl_curve) > 0:
for line in self.axes.lines:
self.axes.lines.pop()
self.axes.figure.canvas.draw()
def create_curve(self):
flag = False # True - Beizer Curve else Interpolation
if len(self.mpl_points) == 2:
self.curve_points = self.linear_bezier(*self.points)
elif len(self.mpl_points) == 3:
if flag:
self.curve_points = self.quad_bezier(self.points[0],self.points[-1],self.points[1])
else:
self.curve_points = self.interpol(*self.points)
elif len(self.mpl_points) == 4:
if flag:
self.curve_points = self.cubic_bezier(self.points[0],self.points[2],self.points[-1],self.points[1])
else:
self.curve_points = self.interpol(*self.points)
else:
self.curve_points = self.interpol(*self.points)
self.mpl_curve.append(self.axes.plot(self.curve_points[:,0], self.curve_points[:,1]))
self.axes.figure.canvas.draw()
def interpol(self,*args):
x,y = zip(*args)
if len(x) == 3:
k = 2
else:
k = 3
tck,u = interpolate.splprep([x,y], k = k)
unew = np.linspace(0, self.res,self.res) / self.res
curve = interpolate.splev(unew,tck)
ans = np.zeros([self.res, 2])
ans[:,0] = curve[0]
ans[:,1] = curve[1]
return ans
def cubic_bezier(self, P0, P1, P2, P3):
ans = np.zeros([self.res, 2])
t = np.linspace(0, self.res,self.res) / self.res
ans[:,0] = (1 - t)**3 * P0[0] + 3*(1 - t)**2 *t*P1[0] + 3*(1-t)*t**2*P2[0] + t**3*P3[0]
ans[:,1] = (1 - t)**3 * P0[1] + 3*(1 - t)**2 *t*P1[1] + 3*(1-t)*t**2*P2[1] + t**3*P3[1]
return ans
def quad_bezier(self, P0, P1, P2):
ans = np.zeros([self.res, 2])
t = np.linspace(0, self.res,self.res) / self.res
ans[:,0] = (1 - t)**2 * P0[0] + 2*(1 - t)*t*P1[0] + t**2*P2[0]
ans[:,1] = (1 - t)**2 * P0[1] + 2*(1 - t)*t*P1[1] + t**2*P2[1]
return ans
def linear_bezier(self, P0, P1):
ans = np.zeros([self.res, 2])
t = np.linspace(0, self.res,self.res) / self.res
ans[:,0] = (1 - t) * P0[0] + t*P1[0]
ans[:,1] = (1 - t) * P0[1] + t*P1[1]
return ans
def get_slit_data(self, data, extent, order=1):
if not hasattr(self, 'curve_points'):
print('You have not yet generated a curve.')
x_pixel = (self.curve_points[:,0] - extent[2] )/ ((extent[3] - extent[2]) / data.shape[2])
y_pixel = (self.curve_points[:,1] - extent[0] )/ ((extent[1] - extent[0]) / data.shape[2])
dist_x = (x_pixel[:-1] - x_pixel[1:]) ** 2
dist_y = (y_pixel[:-1] - y_pixel[1:]) ** 2
self.distance = np.sum(np.sqrt(dist_x + dist_y))
if len(data.shape) == 2:
slit = ndimage.interpolation.map_coordinates(data, [y_pixel,x_pixel], order=order)
elif len(data.shape) == 3:
slit = np.zeros([data.shape[0],self.res])
for i in range(0,data.shape[0]):
slit[i,:] = ndimage.interpolation.map_coordinates(data[i,:,:], [y_pixel,x_pixel], order=order)
else:
raise Exception
return slit
def get_run_diff(self, slit, sort='normal', j = 5):
if sort == 'normal':
self.data_run.append(slit[:-1] - slit[1:])
return self.data_run[-1]
elif sort == 'baseline':
self.data_run.append(slit[:-1] - slit[0])
return self.data_run[-1]
elif sort == 'symmetric':
self.data_run.append(slit[:-1] - slit[1:])
return self.data_run[-1]
elif sort == 'symmetric':
self.data_run.append(slit[:-1] - slit[1:])
return self.data_run[-1]
elif sort == 'symmetric':
self.data_run.append(slit[:-1] - slit[1:])
return self.data_run[-1] | CyclingNinja/sunkit-sst | sunkitsst/visualisation/slit.py | slit.py | py | 5,853 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.zeros",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "scipy.interpolate.splprep",
"line_number": 86,
"usage_type": "call"
},
{
"api_name": "scipy.interpolate",
"line_number": 86,
"usage_type": "name"
},
{
"api_name": "numpy.linspac... |
34140146726 | from __future__ import print_function, division
import we
import json
import numpy as np
import sys
if sys.version_info[0] < 3:
import io
open = io.open
"""
Hard-debias embedding
Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings
Tolga Bolukbasi, Kai-Wei Chang, James Zou, Venkatesh Saligrama, and Adam Kalai
2016
"""
def debias(E, gender_specific_words, definitional, equalize):
gender_direction = we.doPCA(definitional, E).components_[0]
#f = open("bolukbasi_debiased_gender_direction.txt", "w")
#f.write(str(gender_direction))
#f.close()
specific_set = set(gender_specific_words)
for i, w in enumerate(E.words):
if w not in specific_set:
E.vecs[i] = we.drop(E.vecs[i], gender_direction)
E.normalize()
candidates = {x for e1, e2 in equalize for x in [(e1.lower(), e2.lower()),
(e1.title(), e2.title()),
(e1.upper(), e2.upper())]}
print(candidates)
for (a, b) in candidates:
if (a in E.index and b in E.index):
y = we.drop((E.v(a) + E.v(b)) / 2, gender_direction)
z = np.sqrt(1 - np.linalg.norm(y)**2)
if (E.v(a) - E.v(b)).dot(gender_direction) < 0:
z = -z
E.vecs[E.index[a]] = z * gender_direction + y
E.vecs[E.index[b]] = -z * gender_direction + y
E.normalize()
if __name__ == "__main__":
embedding_filename = "word2vec_no_reg.txt"
definitional_filename = "definitional_pairs.json"
gendered_words_filename = "gendered_words.json"
equalize_filename = "equalized_pairs.json"
debiased_filename = "bolukbasi2016_debiased_word2vec.txt"
with open(definitional_filename, "r") as f:
defs = json.load(f)
print("definitional", defs)
with open(equalize_filename, "r") as f:
equalize_pairs = json.load(f)
with open(gendered_words_filename, "r") as f:
gender_specific_words = json.load(f)
print("gender specific", len(gender_specific_words), gender_specific_words[:10])
E = we.WordEmbedding(embedding_filename)
print("Debiasing...")
debias(E, gender_specific_words, defs, equalize_pairs)
print("Saving to file...")
if embedding_filename[-4:] == debiased_filename[-4:] == ".bin":
E.save_w2v(debiased_filename)
else:
E.save(debiased_filename)
print("\n\nDone!\n")
| JasmineZhangxyz/nlp-optimization-objective | bolukbais2016 + bias metrics/debias.py | debias.py | py | 2,466 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.version_info",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "io.open",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "we.doPCA",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "we.drop",
"line_number"... |
3576654470 |
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import average_precision_score
from sklearn.metrics import recall_score
# accuracy_scores: return the correctly classified samples. The set of labels predicted for a sample must exactly match the corresponding set of labels
# f1_score: F1 = 2 * (precision * recall) / (precision + recall), average could be micro, macro, weighted
# roc_auc_score: Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores. Note: this implementation is restricted to the binary classification task or multilabel classification task in label indicator format.
# average_precision_score: Compute average precision (AP) from prediction scores
# recall_score
#'micro': Calculate metrics globally by considering each element of the label indicator matrix as a label.
#'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
#'weighted': Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label).
# accuracy, f1 score, and recall use y_true and y_pred
# roc_auc_score and average_precision_score use y_true and y_score
def evaluation_true_pred(y_validation, y_predicted):
accuracy = accuracy_score(y_validation, y_predicted)
f1 = f1_score(y_validation, y_predicted, average = 'weighted')
recall = recall_score(y_validation, y_predicted, average = 'weighted')
print("Accuray is {}".format(accuracy))
print("F1 is {}".format(f1))
print("Recall is {}".format(recall))
def evaluation_true_scores(y_validation, y_scores):
roc = roc_auc_score(y_validation, y_scores)
average_precision = average_precision_score(y_validation, y_scores)
print("ROC is {}".format(roc))
print("Average Precision is {}".format(average_precision))
| ClarissaW/Predict-tags-on-StackOverflow | evaluation.py | evaluation.py | py | 1,960 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sklearn.metrics.accuracy_score",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics.f1_score",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics.recall_score",
"line_number": 27,
"usage_type": "call"
},
{
... |
7207753656 | # geospatial help functions
import geopandas as gpd
import matplotlib.pyplot as plt
def show_overlaps(data_temp, id_col):
# checks and plots which areas overlap
overlaps = []
for index, row in data_temp.iterrows():
data_temp1 = data_temp.loc[data_temp[id_col] != row[id_col]] # grab all rows, != this row
temp_list = data_temp1[data_temp1.geometry.overlaps(row.geometry)][id_col].tolist() # grab rows with overlap
# get index
if temp_list != []:
overlaps += temp_list
data_overlaps = data_temp.copy()
data_overlaps = data_overlaps.set_index(id_col)
overlap_areas = data_overlaps.loc[overlaps]
ax = data_temp.plot(figsize=size, linewidth=lw, edgecolor="k", color="whitesmoke")
if len(overlap_areas) > 0:
overlap_areas.plot(figsize=size, linewidth=lw, edgecolor="k", color="red", ax=ax)
print("This many rows still overlap:", overlap_areas.shape[0])
def boundary_cut(df_list, cut_df):
# cuts a list of dfs out of the input df
for df in df_list:
cut_df = gpd.overlay(cut_df, df, how="difference")
return cut_df
def plot_bounds(gdf):
# quick plot with standard parameters
gdf.plot(figsize=(24, 20), color="whitesmoke", edgecolor="k", linewidth=0.5)
| PeterFriedrich/bridge_the_gap | helper_functions.py | helper_functions.py | py | 1,286 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "geopandas.overlay",
"line_number": 30,
"usage_type": "call"
}
] |
74311600743 | import numpy as np
import glob
import os
from blimpy import Waterfall
import blimpy as bl
import gc
import time
import matplotlib
import matplotlib.pyplot as plt
start=time.time()
def get_elapsed_time(start=0):
end = time.time() - start
time_label = 'seconds'
if end > 3600:
end = end/3600
time_label = 'hours'
elif end > 60:
end = end/60
time_label = 'minutes'
return end, time_label
def plot_waterfall(wf, source_name=None, f_start=None, f_stop=None, **kwargs):
# get plot data
plot_f, plot_data = wf.grab_data(f_start=f_start, f_stop=f_stop)
# determine extent of the plotting panel for imshow
extent=(plot_f[0], plot_f[-1], (wf.timestamps[-1]-wf.timestamps[0])*24.*60.*60, 0.0)
# plot and scale intensity (log vs. linear)
kwargs['cmap'] = kwargs.get('cmap', 'viridis')
plot_data = 10.0 * np.log10(plot_data)
# get normalization parameters
vmin = plot_data.min()
vmax = plot_data.max()
normalized_plot_data = (plot_data - vmin) / (vmax - vmin)
# display the waterfall plot
this_plot = plt.imshow(normalized_plot_data,aspect='auto',rasterized=True,interpolation='nearest',extent=extent,**kwargs)
del plot_f, plot_data
return this_plot
def one_wf_plot(fil_file_list,f_start=0,f_stop=0,drift_rate=0,source_name_list=[],save_dir=None,save_name=None,extension='png'):
# set up the sub-plots
n_plots = len(fil_file_list)
fig,ax = plt.subplots(n_plots, sharex=True, sharey=True,figsize=(10, 2*n_plots))
if not f_start or not f_stop:
print('\nf_start and/or f_stop input error. Try again.\n')
return None
# define more plot parameters
mid_f = np.abs(f_start+f_stop)/2.
subplots = []
# Fill in each subplot for the full plot
for ii, filename in enumerate(fil_file_list):
# identify panel
subplot = plt.subplot(n_plots, 1, ii + 1)
subplots.append(subplot)
# read in data
max_load = bl.calcload.calc_max_load(filename)
wf = bl.Waterfall(filename, f_start=f_start, f_stop=f_stop, max_load=max_load)
this_plot = plot_waterfall(wf, f_start=f_start, f_stop=f_stop)
del wf
gc.collect()
plt.subplots_adjust(hspace=0,wspace=0)
[axi.set_axis_off() for axi in ax.ravel()]
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
# save the figures
if save_dir:
if save_dir[-1] != "/":
save_dir += "/"
if save_name:
path_png = save_dir+save_name
else:
path_png = save_dir + 'freq_' "{:0.6f}".format(mid_f) + '.' + extension
plt.savefig(path_png, bbox_inches='tight',format=extension, pad_inches=0)
return fig
blc32_f2_plots=sorted(glob.glob('/storage/home/nxt5197/work/PPO/TOI-216/node_by_node/blc32/Freqs_3904_to_4032/MJDate_59221/plots_TIC55652896_S_f2_snr10.0/*.png'))
os.chdir('/storage/home/nxt5197/scratch/PPO/TOI-216/')
fils=sorted(glob.glob('*h5'))
power_matrix = []
freq_ranges = []
counter_file = '/storage/home/nxt5197/work/589_Machine_Learning/plots/data/icounter.txt'
for i,png in enumerate(blc32_f2_plots):
f_start = float(png.split('_freq_')[1].split('.png')[0])
drift_rate = float(png.split('_freq_')[0].split('_dr_')[1])
if abs(drift_rate) <= 0.10:
half_f = 250
elif abs(drift_rate) == 0.11:
half_f = 272
elif abs(drift_rate) == 0.13:
half_f = 304
elif abs(drift_rate) == 0.14:
half_f = 337
elif abs(drift_rate) == 0.32:
half_f = 769
elif abs(drift_rate) == 9.14:
half_f = 21969
elif abs(drift_rate) == 24.31:
half_f = 58424
elif abs(drift_rate) == 36.21:
half_f = 87026
else:
print('You fucked up. You got the drift rate and frequency range wrong. Try again, buddy.')
break
f_mid = f_start+half_f*1e-6
delta_f = 500
f_stop = f_mid+delta_f/2*1e-6
f_start = f_mid-delta_f/2*1e-6
save_dir='/storage/home/nxt5197/work/589_Machine_Learning/plots/imgs/'
save_name=png.split('/')[-1]
image = one_wf_plot(fils,f_start=f_start,f_stop=f_stop,save_dir=save_dir,save_name=save_name,extension='png')
end, time_label = get_elapsed_time(start)
with open(counter_file, 'w') as f:
f.write(f'{i+1} of {len(blc32_f2_plots)} for loops completed in {end:.2f} {time_label}.')
os.chdir('/storage/home/nxt5197/work/589_Machine_Learning/plots/data/')
np.save('power_matrix.npy', power_matrix)
np.save('freq_ranges.npy', freq_ranges) | Tusay/589_ML | get_images.py | get_images.py | py | 4,546 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "time.time",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.log10",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.imshow",
"line_... |
41715969518 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class Actor(nn.Module):
"""Initialize parameters and build model.
Args:
state_size (int): Dimension of each state
action_size (int): Dimension of each action
max_action (float): highest action to take
seed (int): Random seed
h1_units (int): Number of nodes in first hidden layer
h2_units (int): Number of nodes in second hidden layer
Return:
action output of network with tanh activation
"""
def __init__(self, state_dim, action_dim, max_action, seed):
super(Actor, self).__init__()
self.seed = torch.manual_seed(seed)
self.l1 = nn.Linear(state_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, action_dim)
self.max_action = max_action
def forward(self, x):
x = F.relu(self.l1(x))
x = F.relu(self.l2(x))
x = self.max_action * torch.tanh(self.l3(x))
return x
class Critic(nn.Module):
"""Initialize parameters and build model.
Args:
state_size (int): Dimension of each state
action_size (int): Dimension of each action
max_action (float): highest action to take
seed (int): Random seed
h1_units (int): Number of nodes in first hidden layer
h2_units (int): Number of nodes in second hidden layer
Return:
value output of network
"""
def __init__(self, state_dim, action_dim, seed):
super(Critic, self).__init__()
self.seed = torch.manual_seed(seed)
# Q1 architecture
self.l1 = nn.Linear(state_dim + action_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, 1)
# Q2 architecture
self.l4 = nn.Linear(state_dim + action_dim, 400)
self.l5 = nn.Linear(400, 300)
self.l6 = nn.Linear(300, 1)
def forward(self, x, u):
xu = torch.cat([x, u], 1)
x1 = F.relu(self.l1(xu))
x1 = F.relu(self.l2(x1))
x1 = self.l3(x1)
x2 = F.relu(self.l4(xu))
x2 = F.relu(self.l5(x2))
x2 = self.l6(x2)
return x1, x2
def Q1(self, x, u):
xu = torch.cat([x, u], 1)
x1 = F.relu(self.l1(xu))
x1 = F.relu(self.l2(x1))
x1 = self.l3(x1)
return x1 | zachterrell57/stock-trading | DDPG Example Implementation/network.py | network.py | py | 2,616 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "torch.nn.Module",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "torch.manual_seed",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "torch.nn.Linear",
... |
70291499304 | import webapp2
import random
def rand_fortune():
fortunes = ["To avoid criticism, do nothing, say nothing, be nothing", "Error 404: Fortune not found", "Optimist believe we live in the best of worlds and pessimists fear this is true.", "Of all our human resources, the most precious is the desire to improve"]
index = random.randint(0,3)
return fortunes[index]
class MainHandler(webapp2.RequestHandler):
def get(self):
header = "<h1>Fortune Cookie</h1>"
fortune = rand_fortune()
final_fortune_sent = "<p>"'Your fortune is: ' + fortune + "</p>"
lucky_num = random.randint(1,100)
num_sent = 'Your lucky number: ' + str(lucky_num)
final_num_sent = "<p>" + num_sent + "</p>"
another_cookie = "<p><a href='.'><button>another cookie please</button></a></p>"
da_cookie = header + final_fortune_sent + final_num_sent + another_cookie
self.response.write(da_cookie)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
| freddyworldpeace/fortune-cookie | main.py | main.py | py | 1,023 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "random.randint",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "webapp2.RequestHandler",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "random.randint",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "webapp2.WSGI... |
2168304898 | import wave
import numpy as np
import scipy
from scipy.io.wavfile import read
from scipy.signal import hann
from scipy.fftpack import rfft
import matplotlib.pyplot as plt
def plotFreqSpec(filename,graphpath=None):
# read audio samples
framerate,data = read(filename)
file = wave.open(filename, 'rb')
nchannels, sampwidth, framerate, nframes = file.getparams()[0:4]
data = data.astype(np.float, copy=False)
if nchannels > 1:
data2 = np.mean(a=data, axis=1)
data = data2
windowsize = 1024
lackingFrames = nframes%windowsize
data = np.append(data,[0]*lackingFrames)
window = hann(windowsize)
data = data/(2**(sampwidth*8))
audio = data
for i in range(0,nframes//windowsize):
# apply a Hanning window
audio[(i*windowsize):((i+1)*windowsize)] = audio[(i*windowsize):((i+1)*windowsize)]*window
# fft
mags = abs(rfft(audio))
# convert to dB
mags = 20*scipy.log10(mags)
# normalise to 0 dB max
mags -= max(mags)
# plot
plt.plot(mags)
# label the axes
plt.ylabel("Magnitude (dB)")
plt.xlabel("Frequency Bin")
# set the title
plt.title("Spectrum")
if graphpath is not None:
plt.savefig("Spectrum.png")
else:
plt.show()
if __name__ == "__main__":
plotFreqSpec("./static/music/temp.wav") | Mheeh/Audio | spectrum.py | spectrum.py | py | 1,348 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "scipy.io.wavfile.read",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "wave.open",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.float",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "numpy.mean",
"li... |
42360805462 | from django.shortcuts import render, redirect, reverse
# Create your views here.
from django.views.decorators.http import require_GET
from django.contrib.auth.decorators import login_required
from goods.models import Goods
from . import models
@require_GET
@login_required
def add(req, count, goods_id):
goods = Goods.objects.get(pk=goods_id)
user = req.user
try:
shopCart = models.ShopCart.objects.get(user=user, goods=goods)
shopCart.count += int(count)
shopCart.allTotal = shopCart.count * goods.price
shopCart.save()
except:
shopCart = models.ShopCart(goods=goods, user=user)
shopCart.count = int(count)
shopCart.allTotal = shopCart.count * goods.price
shopCart.save()
return redirect(reverse('shopcart:list'))
#购物车的列表
@login_required
def list(req):
shopcarts = models.ShopCart.objects.filter(user=req.user).order_by('-addTime')
return render(req, 'shopcart/list.html', {'shopcarts': shopcarts})
#购物车的删除
def delete(req, shopcart_id):
shopCart = models.ShopCart.objects.get(pk=shopcart_id)
shopCart.delete()
return redirect(reverse('shopcart:list'))
| hwzHw/python37 | dayWeb/myshopping/shopcart/views.py | views.py | py | 1,215 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "goods.models",
"line_number": 14,
"usage_type": "name"
},
{
"api_name": "goods.models.Goods.objects.get",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "goods.models.Goods.objects",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_n... |
70005734826 | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
class TInteractObj(QObject):
SigReceivedMessFromJS = pyqtSignal(dict)
SigSendMessageToJS = pyqtSignal(str)
def __init__(self, parent = None):
super().__init__(parent)
@pyqtSlot(str,result=str)
def JSSendMessage(self, strParameter):
print('JSSendMessage(%s) from Html' %strParameter)
dict1 = {'param':strParameter,'result':''}
self.SigReceivedMessFromJS.emit(dict1)
return dict1['result']
@pyqtSlot(result=str)
def fun(self):
print('TInteractObj.fun()')
return 'hello1' | cjt24703/pyqt5- | TInteractObject.py | TInteractObject.py | py | 631 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "PyQt5.QtCore.QObject",
"line_number": 3,
"usage_type": "name"
},
{
"api_name": "PyQt5.QtCore.pyqtSignal",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "PyQt5.QtCore.pyqtSignal",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "PyQ... |
15599967327 | from django.shortcuts import render
from inicio.models import Paciente
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
def mi_vista(request):
return render(request, 'inicio/index.html')
def acerca(request):
return render(request, 'inicio/acerca.html')
class ListaPacientes(ListView):
model = Paciente
template_name = 'inicio/CBV/lista_pacientes.html'
class CrearPaciente(CreateView):
model = Paciente
template_name = 'inicio/CBV/crear_paciente.html'
success_url = reverse_lazy('lista_pacientes')
fields = ['nombre', 'apellido', 'dni', 'año_nacimiento']
class ModificarPaciente(LoginRequiredMixin, UpdateView):
model = Paciente
template_name = 'inicio/CBV/modificar_pacientes.html'
success_url = reverse_lazy('lista_pacientes')
fields = ['nombre', 'apellido', 'dni', 'año_nacimiento']
class EliminarPaciente(LoginRequiredMixin, DeleteView):
model = Paciente
template_name = 'inicio/CBV/eliminar_paciente.html'
success_url = reverse_lazy('lista_pacientes') | MatrixUHzp/web-doctor | inicio/views.py | views.py | py | 1,189 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.shortcuts.render",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "django.shortcuts.render",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "django.views.generic.list.ListView",
"line_number": 14,
"usage_type": "name"
},
{
... |
74050675304 | from copy import deepcopy
from typing import Optional, List
from types import MethodType
from collections import defaultdict
from nltk.tokenize import sent_tokenize
from nltk.corpus import stopwords
import random
import spacy
import torch
from parlai.core.agents import create_agent, create_agent_from_shared
from parlai.core.params import ParlaiParser
from parlai.core.opt import Opt
from parlai.core.message import Message
from parlai.core.agents import Agent
from parlai.core.metrics import F1Metric
from parlai.agents.rag.args import setup_rag_args
from parlai.agents.bart.bart import BartAgent
from parlai.core.metrics import normalize_answer
from parlai.tasks.wizard_of_wikipedia.agents import (
TOKEN_NOCHOSEN,
)
from parlai.tasks.wizard_of_wikipedia.agents import (
TOKEN_KNOWLEDGE,
TOKEN_END_KNOWLEDGE,
)
STOP_WORDS = stopwords.words('english')
def load_opt_from_file(opt_file):
if not opt_file.endswith('.opt'):
opt_file += '.opt'
return Opt.load(opt_file)
def wow_get_batch_context(self, batch, orig_fun=None):
"""
Set the beam context for n-gram context blocking specific for WoW data.
For WoW, we don't want to consider the knowledge in the input for the context beam
blocking. That's why we mask it out here.
"""
ctxts = orig_fun(batch)
knowledge_start_id = self.dict.txt2vec(TOKEN_KNOWLEDGE)
knowledge_end_id = self.dict.txt2vec(TOKEN_END_KNOWLEDGE)
def mask_ctxttensor_between_sublists(
ctxts: torch.Tensor, sub1: List[int], sub2: List[int]
) -> torch.Tensor:
"""
Generate a mask that masks out the context between sub1 and sub2.
"""
mask = []
for ctxt in ctxts:
mask_idxs = []
should_copy = False
idx_pointer = 0
id_to_match = sub1
for j, token in enumerate(ctxt.cpu().numpy()):
if token == id_to_match[idx_pointer]:
idx_pointer += 1
if idx_pointer == 1 and id_to_match == sub1:
mask_idxs.append([j])
elif idx_pointer >= len(id_to_match):
should_copy = id_to_match == sub1
idx_pointer = 0
id_to_match = sub2 if (id_to_match == sub1) else sub1
mask_idxs[-1].append(j)
else:
mask_idxs[-1].append(j)
elif should_copy:
mask_idxs[-1].append(j)
elif idx_pointer > 0:
idx_pointer = 0
del mask_idxs[-1]
mask.append(
[
0 if idx in [i for sl in mask_idxs for i in sl] else 1
for idx in range(len(ctxt))
]
)
return torch.LongTensor(mask).to(ctxts.device)
ctxts *= mask_ctxttensor_between_sublists(
ctxts, knowledge_start_id, knowledge_end_id
)
return ctxts
def find_supporting_sentence(question: str, answer: str, docs: List[str]) -> str:
"""
Finds the supporting sentence for the answer in the docs.
"""
# Remove the title of the documents.
for i, doc in enumerate(docs):
if ' | ' in doc:
docs[i] = '. '.join(doc.split(' | ')[1:])
concat_docs = '. '.join(docs)
sentences = sent_tokenize(concat_docs)
# Sort sentences according to recall with the answer and question.
sorted_sentences = sorted(
sentences,
key=lambda sentence: (
F1Metric._prec_recall_f1_score(
normalize_answer(answer).split(), normalize_answer(sentence).split()
)[0],
F1Metric._prec_recall_f1_score(
normalize_answer(question).split(), normalize_answer(sentence).split()
)[0],
),
reverse=True,
)
return sorted_sentences[0]
def extract_entities(
sentence, pos=('PROPN', 'NOUN'), use_named_entities=True, use_noun_chunks=True
):
global nlp
if nlp is None:
nlp = spacy.load("en_core_web_sm")
doc = nlp(sentence)
results = []
if pos:
for token in doc:
if token.pos_ in pos:
results.append(token)
if use_named_entities:
for ent in doc.ents:
results.append(ent)
if use_noun_chunks:
for chunk in doc.noun_chunks:
if chunk.text.lower() not in STOP_WORDS:
results.append(chunk)
results = list(set([r.text for r in results]))
return results
def extract_knowledge(txt: str) -> List[str]:
if not txt or not txt.split():
return []
entities = extract_entities(txt)
return [e.lower() for e in (entities if entities else txt.split())]
def knowledge_from_dialogue_response(dialogue_response: str) -> str:
"""
Get a knowledge response based on the dialogue response.
We use a random entity from the dialogue response as knowledge. If there is no
entity present, we use a random word. If there are no words present, we use
TOKEN_NOCHOSEN.
"""
knowledge_options = extract_knowledge(dialogue_response)
if not knowledge_options:
return TOKEN_NOCHOSEN
return random.choice(knowledge_options)
class StackedKnowledgeDialogueAgent(Agent):
"""
Stacked model that generates first the knowledge, and then the dialogue response.
"""
@classmethod
def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
agent = parser.add_argument_group('StackedKnowledgeDialogueAgent options')
additional_agent_parser = ParlaiParser(add_parlai_args=False)
BartAgent.add_cmdline_args(additional_agent_parser)
setup_rag_args(additional_agent_parser)
for action in additional_agent_parser._actions:
key = action.option_strings[-1]
type = action.type
for prefix in [
'krm', # knowledge response model
'drm', # dialogue response model
'drmrw', # dialogue response model rag-wiki
'drmnk', # dialogue response model no-knowledge
]:
agent.add_argument(
f'--{prefix}-{key.strip("-")}',
type=type,
required=False,
)
agent.add_argument(
'--knowledge-response-model-path',
type=str,
default=''
'wow_knowledge_response_generation_sweep_1_Tue_Aug_17_1822/9aa/model',
help='Model used to generate the knowledge response.',
)
agent.add_argument(
'--dialogue-response-model-path',
type=str,
default='',
help='Model used to generate the dialogue response.',
)
agent.add_argument(
'--dialogue-response-no-knowledge-model-path',
type=str,
default='',
help='Model used to generate the dialogue response without knowledge.',
)
agent.add_argument(
'--dialogue-response-rag-wiki-model-path',
type=str,
default='',
help='Model used to generate the dialogue response with Wiki knowledge.',
)
agent.add_argument(
'--use-supporting-sentence-as-knowledge',
type=bool,
default=False,
help='Instead of using the knowledge response directly to condition the dialogue'
' model, we search for the top supporting sentence and use this.',
)
agent.add_argument(
'--beam-filter-for-knowledge-response',
type=bool,
default=False,
help='Try to pick a beam that contains the knowledge response.',
)
agent.add_argument(
'--beam-filter-questions',
type=bool,
default=False,
help='Try to pick a beam that does not contain a question mark.',
)
agent.add_argument(
'--beam-filter-self-references',
type=bool,
default=False,
help='Try to pick a beam that does not contain self references like "I" and "me".',
)
agent.add_argument(
'--beam-disregard-knowledge-for-context-blocking',
type=bool,
default=True,
help='If True disregard the knowledge input for the context blocking.',
)
agent.add_argument(
'--add-fixed-confidence',
type=int,
default=-1,
help='Add a fixed confidence score of the knowledge response.',
)
agent.add_argument(
'--add-confidence-as-str',
type=bool,
default=False,
help='If we add a confidence score to the KRM, we add it as a str.',
)
return parser
def __init__(self, opt, shared=None):
self.id = 'StackedKnowledgeDialogueAgent'
self._construct_opts(opt)
self.knowledge_agent = None
self.dialogue_agent = None
self.dialogue_agent_no_knowledge = None
self.dialogue_agent_rag_wiki = None
if not shared:
self._init_knowledge_model()
self._init_dialogue_models()
else:
if 'knowledge_agent_share' in shared:
self.knowledge_agent = create_agent_from_shared(
shared['knowledge_agent_share']
)
if 'dialogue_agent_share' in shared:
self.dialogue_agent = create_agent_from_shared(
shared['dialogue_agent_share']
)
if 'dialogue_agent_no_knowledge_share' in shared:
self.dialogue_agent = create_agent_from_shared(
shared['dialogue_agent_no_knowledge_share']
)
if 'dialogue_agent_rag_wiki_share' in shared:
self.dialogue_agent = create_agent_from_shared(
shared['dialogue_agent_rag_wiki_share']
)
self.shared = shared
super().__init__(opt, shared)
@property
def has_no_knowledge_dialogue_model(self):
return (
self.opts['init']['dialogue_response_no_knowledge_model_path']
and self.opts['init']['dialogue_response_no_knowledge_model_path'] != 'None'
)
@property
def has_rag_wiki_dialogue_model(self):
return (
self.opts['init']['dialogue_response_rag_wiki_model_path']
and self.opts['init']['dialogue_response_rag_wiki_model_path'] != 'None'
)
def _agent_opt(
self, filename, specific_override_args, general_override_args, **kwargs
):
opt = load_opt_from_file(filename)
opt['override'] = {}
blocklist_general = ['model', 'model_file', 'init_model']
standard_override_args = {
'skip_generation': False,
'inference': 'beam',
'beam_block_ngram': 3,
'beam_context_block_ngram': -1,
'beam_size': 3,
}
general_override_args = {
**general_override_args,
**standard_override_args,
**kwargs,
}
# Remove the prefix for the model for the specific override args.
specific_override_args = {
'_'.join(k.split('_')[1:]): v for k, v in specific_override_args.items()
}
# Specific for --indexer-type.
if 'indexer_type' in specific_override_args:
# TODO: do we also need to overwrite path_to_index?
pass
override_args = {**general_override_args, **specific_override_args}
for k, v in override_args.items():
if k not in blocklist_general and k in opt:
opt['override'][k] = v
return opt
def _construct_opts(self, opt):
self.opts = {}
self.opts['init'] = opt
override_opts = defaultdict(dict)
for k, v in opt['override'].items():
if k.startswith('krm_'):
if v is not None:
override_opts['knowledge_agent'][k] = v
elif k.startswith('drm_'):
if v is not None:
override_opts['dialogue_agent'][k] = v
elif k.startswith('drmnk_'):
if v is not None:
override_opts['dialogue_agent_no_knowledge'][k] = v
elif k.startswith('drmrw_'):
if v is not None:
override_opts['dialogue_agent_rag_wiki'][k] = v
else:
override_opts['general'][k] = v
self.opts['override'] = override_opts
if opt['knowledge_response_model_path'] and opt[
'knowledge_response_model_path'
] not in ['oracle']:
self.opts['knowledge_agent'] = self._agent_opt(
filename=opt['knowledge_response_model_path'],
specific_override_args=override_opts['knowledge_agent'],
general_override_args=override_opts['general'],
)
self.opts['dialogue_agent'] = self._agent_opt(
filename=opt['dialogue_response_model_path'],
specific_override_args=override_opts['dialogue_agent'],
general_override_args=override_opts['general'],
)
if self.has_no_knowledge_dialogue_model:
self.opts['dialogue_agent_no_knowledge'] = self._agent_opt(
filename=opt['dialogue_response_no_knowledge_model_path'],
specific_override_args=override_opts['dialogue_agent_no_knowledge'],
general_override_args=override_opts['general'],
)
if self.has_rag_wiki_dialogue_model:
self.opts['dialogue_agent_rag_wiki'] = self._agent_opt(
filename=opt['dialogue_response_rag_wiki_model_path'],
specific_override_args=override_opts['dialogue_agent_rag_wiki'],
general_override_args=override_opts['general'],
)
def share(self):
shared = super().share()
shared['knowledge_agent_share'] = self.knowledge_agent.share()
shared['dialogue_agent_share'] = self.dialogue_agent.share()
if self.has_no_knowledge_dialogue_model:
shared[
'dialogue_agent_no_knowledge_share'
] = self.dialogue_agent_no_knowledge.share()
if self.has_rag_wiki_dialogue_model:
shared[
'dialogue_agent_rag_wiki_share'
] = self.dialogue_agent_rag_wiki.share()
return shared
def _init_knowledge_model(self):
# Initialize knowledge agent.
if 'knowledge_agent' in self.opts:
self.knowledge_agent = create_agent(
self.opts['knowledge_agent'], requireModelExists=True
)
print('Options for Knowledge Response Agent')
self.knowledge_agent.opt.log()
elif self.opts['init']['knowledge_response_model_path'] == 'oracle':
self.knowledge_agent = OracleKnowledgeAgent(self.opts['init'])
def _init_dialogue_models(self):
## Init dialogue models.
# Initialize dialogue agent that uses the predicted knowledge.
self.dialogue_agent = create_agent(
self.opts['dialogue_agent'], requireModelExists=True
)
# Monkey patch the get_batch_context to ignore the knowledge for
# beam-context-blocking.
if self.opts['init']['beam_disregard_knowledge_for_context_blocking']:
orig_fun = self.dialogue_agent._get_batch_context
self.dialogue_agent._get_batch_context = MethodType(
lambda self, batch: wow_get_batch_context(
self, batch, orig_fun=orig_fun
),
self.dialogue_agent,
)
print('Options for Dialogue Response Agent')
self.dialogue_agent.opt.log()
# Initialize dialogue agent that doesn't use knowledge.
if self.has_no_knowledge_dialogue_model:
self.dialogue_agent_no_knowledge = create_agent(
self.opts['dialogue_agent_no_knowledge'], requireModelExists=True
)
# Initialize dialogue agent that uses RAG with Wiki.
if self.has_rag_wiki_dialogue_model:
self.dialogue_agent_rag_wiki = create_agent(
self.opts['dialogue_agent_rag_wiki'], requireModelExists=True
)
def dialogue_reply(self, agent, observation):
return self.batch_dialogue_reply(agent, [observation])[0]
def batch_dialogue_reply(self, agent, observations):
dialogue_observations = []
# Observation for the dialogue model.
for obs in observations:
dialogue_observation = agent.observe(obs)
agent.self_observe(dialogue_observation)
dialogue_observations.append(dialogue_observation)
return agent.batch_act(dialogue_observations)
def generate_knowledge_observation(self, knowledges: List[str], observations):
# Adjust the observation texts.
knowledge_infused_observations = deepcopy(observations)
for obs, knowledge in zip(knowledge_infused_observations, knowledges):
if 'text' not in obs:
continue
text = obs.pop('text')
if self.opts['init']['add_fixed_confidence'] >= 0:
confidence = self.opts['init']['add_fixed_confidence']
if self.opts['init']['add_confidence_as_str']:
confidence = {
0: 'low',
5: 'medium',
10: 'high',
}[confidence] + ' confidence'
text += f'\n{TOKEN_KNOWLEDGE} {confidence}: {knowledge} {TOKEN_END_KNOWLEDGE}'
else:
text += f'\n{TOKEN_KNOWLEDGE} {knowledge} {TOKEN_END_KNOWLEDGE}'
obs['text'] = text
return knowledge_infused_observations
def batch_act(self, observations):
knowledge_agent_observations = [o['knowledge_agent'] for o in observations]
raw_observations = [o['raw'] for o in observations]
# Get the knowledge replies.
if self.knowledge_agent is None:
self._init_knowledge_model()
batch_reply_knowledge = self.knowledge_agent.batch_act(
knowledge_agent_observations
)
if (
'top_docs' in batch_reply_knowledge[0]
and self.opts['init']['use_supporting_sentence_as_knowledge']
):
# The knowledge agent is a rag-style model. Instead of the actual knowledge
# response, we will use the best matching sentence from the retrieved docs
# as the knowledge conditioning.
for i, reply_knowledge in enumerate(batch_reply_knowledge):
reply_knowledge['support_sentence'] = find_supporting_sentence(
question=raw_observations[i]['text'],
answer=reply_knowledge['text'],
docs=reply_knowledge['top_docs'],
)
if self.dialogue_agent is None:
self._init_dialogue_models()
if self.dialogue_agent_no_knowledge:
batch_reply_dialogue_no_knowledge = self.batch_dialogue_reply(
self.dialogue_agent_no_knowledge, raw_observations
)
if self.dialogue_agent_rag_wiki:
batch_reply_dialogue_rag_wiki = self.batch_dialogue_reply(
self.dialogue_agent_rag_wiki, raw_observations
)
knowledge_infused_observations = self.generate_knowledge_observation(
knowledges=[
reply_knowledge.get('text', '')
for reply_knowledge in batch_reply_knowledge
],
observations=raw_observations,
)
batch_reply_dialogue = self.batch_dialogue_reply(
self.dialogue_agent, knowledge_infused_observations
)
batch_reply_dialogue_knowledge_sentence = None
if (
self.opts['init']['use_supporting_sentence_as_knowledge']
and 'support_sentence' in batch_reply_knowledge[0]
):
knowledge_sentence_infused_observations = (
self.generate_knowledge_observation(
knowledges=[
reply_knowledge.get('support_sentence', '')
for reply_knowledge in batch_reply_knowledge
],
observations=raw_observations,
)
)
batch_reply_dialogue_knowledge_sentence = self.batch_dialogue_reply(
self.dialogue_agent, knowledge_sentence_infused_observations
)
for i in range(len(batch_reply_dialogue)):
if batch_reply_knowledge and len(batch_reply_knowledge) > i:
batch_reply_dialogue[i]['knowledge_response'] = batch_reply_knowledge[
i
].get('text', '')
if 'support_sentence' in batch_reply_knowledge[i]:
batch_reply_dialogue[i]['support_sentence'] = batch_reply_knowledge[
i
].get('support_sentence', '')
if (
self.dialogue_agent_no_knowledge
and batch_reply_dialogue_no_knowledge
and len(batch_reply_dialogue_no_knowledge) > i
):
batch_reply_dialogue[i][
'text_no_knowledge'
] = batch_reply_dialogue_no_knowledge[i].get('text', '')
if (
self.dialogue_agent_rag_wiki
and batch_reply_dialogue_rag_wiki
and len(batch_reply_dialogue_rag_wiki) > i
):
batch_reply_dialogue[i][
'text_rag_wiki'
] = batch_reply_dialogue_rag_wiki[i].get('text', '')
if (
batch_reply_dialogue_knowledge_sentence
and len(batch_reply_dialogue_knowledge_sentence) > i
):
batch_reply_dialogue[i][
'text_knowledge_sentence'
] = batch_reply_dialogue_knowledge_sentence[i].get('text', '')
[
self._filter_beams(
reply=reply,
filter_for_knowledge=self.opts['init'][
'beam_filter_for_knowledge_response'
],
filter_questions=self.opts['init']['beam_filter_questions'],
filter_self_references=self.opts['init']['beam_filter_self_references'],
)
for reply in batch_reply_dialogue
]
return batch_reply_dialogue
def _filter_beams(
self,
reply,
filter_for_knowledge: bool = True,
filter_questions: bool = False,
filter_self_references: bool = False,
):
knowledge = normalize_answer(reply['knowledge_response'])
self_references = [
'I live',
'I love',
' me ',
'my favorite',
'My favorite',
'do you know',
'I have',
'I like ',
'My ',
]
question_words = [
'who',
'when',
'where',
'what',
'do you',
'are you',
]
def filter_fn(text: str) -> bool:
normalized_text = normalize_answer(text)
if filter_for_knowledge and knowledge not in normalized_text:
return False
if filter_questions and (
'?' in text or any([qw in normalized_text for qw in question_words])
):
return False
if filter_self_references and any([ref in text for ref in self_references]):
return False
return True
if not (
'text' in reply
and 'beam_texts' in reply
and 'knowledge_response' in reply
and len(reply['beam_texts']) > 1
):
return
beam_texts = [
text
for text, _ in sorted(reply['beam_texts'], key=lambda x: x[1], reverse=True)
]
# print('\t' + '\n\t'.join(beam_texts[:10]))
for text in [reply['text']] + beam_texts:
if filter_fn(text):
reply.force_set('text', text)
return
def self_observe(self, self_message: Message) -> None:
# Hack: Feed back the final dialogue response to the knowledge model.
# This is why we need to make sure that --mutators flatten.
self.knowledge_agent.self_observe(self_message)
def observe(self, observation):
# Delete unused keys.
for key in ['label_candidates', 'knowledge']:
if key in observation:
del observation[key]
label_key = 'eval_labels' if 'eval_labels' in observation else 'labels'
if 'nqopen' in self.opts['init']['task'].lower():
knowledge_target = observation.get(label_key, '')
if isinstance(knowledge_target, tuple):
knowledge_target = '\t'.join(knowledge_target)
observation['knowledge_target'] = knowledge_target
observation['dialogue_response'] = ''
else:
observation['dialogue_response'] = observation.get(label_key, '')
observation['knowledge_response'] = observation.get('checked_sentence', '')
if self.knowledge_agent is None:
self._init_knowledge_model()
observations = {
'raw': deepcopy(observation),
'knowledge_agent': self.knowledge_agent.observe(observation),
}
self.observations = observations
return observations
def act(self):
"""
Call batch_act with the singleton batch.
"""
response = self.batch_act([self.observations])[0]
self.self_observe(response)
return response
class OracleKnowledgeAgent(Agent):
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'OracleKnowledgeAgent'
def get_knowledge(self, obs):
labels_kword = 'labels' if 'train' in self.opt['datatype'] else 'eval_labels'
if 'wizardofwikipedia' in self.opt['task'].lower().replace('_', ''):
return obs.get('checked_sentence', '')
if 'wizardofinternet' in self.opt['task'].lower().replace('_', ''):
knowledge = obs.get('__selected-sentences__', '')
if isinstance(knowledge, list):
knowledge = '\n'.join(knowledge)
return knowledge
elif (
'nqopen' in self.opt['task'].lower()
or 'natural_questions' in self.opt['task'].lower()
):
return obs.get(labels_kword, '')
elif 'LightTeacherPlus' in self.opt['task']:
if labels_kword not in obs or not obs[labels_kword]:
return ''
labels = obs[labels_kword]
if not isinstance(labels, str):
labels = labels[0]
return knowledge_from_dialogue_response(labels)
elif 'SummaryQA' in self.opt['task']:
return obs.get(labels_kword, '')
else:
raise NotImplementedError(f'Task "{self.opt["task"]}" is not known.')
def self_observe(self, obs):
pass
def batch_act(self, observations):
return [self.act(obs) for obs in observations]
def act(self, obs=None):
if not obs:
obs = self.observation
if obs is None:
return {'text': 'Nothing to repeat yet.'}
reply = {}
reply['id'] = self.getID()
knowledge = self.get_knowledge(obs)
if not isinstance(knowledge, str):
knowledge = random.choice(knowledge)
reply['text'] = knowledge
return Message(reply)
| facebookresearch/ParlAI | projects/k2r/stacked_agent/task/agents.py | agents.py | py | 28,080 | python | en | code | 10,365 | github-code | 36 | [
{
"api_name": "nltk.corpus.stopwords.words",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "nltk.corpus.stopwords",
"line_number": 29,
"usage_type": "name"
},
{
"api_name": "parlai.core.opt.Opt.load",
"line_number": 35,
"usage_type": "call"
},
{
"api_na... |
73484234343 | import time
import nlp_pre_processing
nlp = nlp_pre_processing.NLPPreprocessor()
# Multiprocessing
from multiprocessing import Pool
start_time = time.time()
num_partitions = 20
num_cores = 15
print(f'Partition Number: {num_partitions} - Number of Cores: {num_cores}...')
def main_process_pipeline(df, func):
df_split = np.array_split(df, num_partitions)
pool = Pool(num_cores)
df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df
def pre_process_wrapper(df):
df['full_text'] = df['full_text'].apply(lambda text: nlp.pre_processing_pipeline(text))
return df
print('Generate dump with pre-processed data...')
extraction_df = main_process_pipeline(df_sr_events_requests, pre_process_wrapper)
print(f'Pre-Processing in seconds: {(time.time() - start_time)}')
print(f'Pre-Processing in seconds: {(time.time() - start_time)}')
print('Multiprocessing data cleanup done...')
| fclesio/learning-space | Python/multiprocessing_function.py | multiprocessing_function.py | py | 932 | python | en | code | 10 | github-code | 36 | [
{
"api_name": "nlp_pre_processing.NLPPreprocessor",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "multiprocessing.Pool",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "time.... |
20752748311 | import requests
import googletrans
from pycatapi import Client
def load_random_cat():
c = Client()
cat_url = c.get_cat()
return cat_url
def load_random_joke():
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url).json()
joke = f'- {response["setup"]}\n- {response["punchline"]}\n:)'
return translate_joke(joke)
def translate_joke(text):
translator = googletrans.Translator()
result = translator.translate(text, dest="ru")
row = (f'{result.text}\nOrigin: {result.origin}').split('\n')
return row
def base_config():
return {
"cat_url": load_random_cat(),
"joke_text": load_random_joke()
} | zarex1111/WEB_Project | base_config.py | base_config.py | py | 697 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pycatapi.Client",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "googletrans.Translator",
"line_number": 21,
"usage_type": "call"
}
] |
69886479786 | import os
import unittest
import ansible
from ansiblelint import Runner, RulesCollection
from pkg_resources import parse_version
class TestTaskIncludes(unittest.TestCase):
def setUp(self):
rulesdir = os.path.join('lib', 'ansiblelint', 'rules')
self.rules = RulesCollection.create_from_directory(rulesdir)
def test_block_included_tasks(self):
filename = 'test/blockincludes.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
def test_block_included_tasks_with_rescue_and_always(self):
filename = 'test/blockincludes2.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
def test_included_tasks(self):
filename = 'test/taskincludes.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
@unittest.skipIf(parse_version(ansible.__version__) < parse_version('2.4'), "not supported with ansible < 2.4")
def test_include_tasks_2_4_style(self):
filename = 'test/taskincludes_2_4_style.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
@unittest.skipIf(parse_version(ansible.__version__) < parse_version('2.4'), "not supported with ansible < 2.4")
def test_import_tasks_2_4_style(self):
filename = 'test/taskimports.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
def test_include_tasks_with_block_include(self):
filename = 'test/include-in-block.yml'
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 3)
| dholdaway/Best-Practices_And_Examples | Ansible/test/TestTaskIncludes.py | TestTaskIncludes.py | py | 1,901 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "unittest.TestCase",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "os.path.join",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "ansiblelint.RulesColl... |
36122181612 | import os, sys
import argparse
libpath = os.path.join(os.path.dirname(__file__), '../')
sys.path.append(libpath)
import src
from src.compiler.gen_relay_ir import gen_relay_ir
from src.compiler.visualize import visualize
from src.compiler.compiler import Compiler
from src.compiler.utils import dump_params
def frontendcompile(args):
platform = args.platform
model_path = args.model_path
epoch = args.epoch
output_path = args.output_path
dump_params = args.dump_params
img_shape = args.img_shape
reconstruct_graph_name = args.reconstruct_graph_name
reconstruct_params_name = args.reconstruct_params_name
compiler_params_name = args.compiler_params_name
compiler_graph_name = args.compiler_graph_name
if not os.path.isdir(output_path):
os.mkdir(output_path)
model = gen_relay_ir(platform, model_path, img_shape, epoch)
graph, params = visualize(model)
tran_compiler = Compiler(graph, params)
# Generate Moffett IR for reconstruct
if reconstruct_graph_name and reconstruct_params_name:
tran_compiler.save(reconstruct_graph_name, reconstruct_params_name, output_path)
# Generate operation fused graph.
if compiler_graph_name and compiler_params_name:
tran_compiler.compile()
# tran_compiler.CModel_transforms()
tran_compiler.save(compiler_graph_name, compiler_params_name, output_path)
if dump_params:
dump_params(tran_compiler.params, compiler_params_name, output_path)
print('Done!')
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(usage="main.py platform model_path [optional]\ni.e.: pyhton3 main.py mxnet resnet50_v1d --epoch 159")
arg_parser.add_argument("platform", type=str, help='model platform, i.e.: mxnet, tensorflow...')
arg_parser.add_argument("model_path", type=str, help='path of model file, For mxnet model, prefix of model name\
(symbol will be loaded from prefix-symbol.json, parameters will be loaded from prefix-epoch.params.)\
For tensorflow model, *.pb')
arg_parser.add_argument("--epoch", default = 0, type=int, help='Only used for mxnet model. epoch number of mxnet model we would like to load, default: 0.')
arg_parser.add_argument("--output_path", default = "./moffett_ir", type=str, help='output directory of Moffett IR graphs and params, default: ./moffett_ir')
arg_parser.add_argument("--dump_params", default=False, type=bool, help="Whether dump params to separate files.")
arg_parser.add_argument("--img_shape", default=[224,224], nargs=2, type=int, help="The image shape of input in model, default: 224 224")
arg_parser.add_argument("--reconstruct_graph_name", default = 'IR_for_reconstruct_graph', type=str, help='file name of Moffett IR for reconstruct graph, default: IR_for_reconstruct_graph')
arg_parser.add_argument("--reconstruct_params_name", default = 'IR_for_reconstruct_params', type=str, help='file name of Moffett IR for reconstruct params, default: IR_for_reconstruct_params')
arg_parser.add_argument("--compiler_graph_name", default='IR_fused_for_CModel_graph', type=str, help='file name of Moffett IR fused for CModel graph, default: IR_fused_for_CModel_graph')
arg_parser.add_argument("--compiler_params_name", default = 'IR_fused_for_CModel_params', type=str, help='file name of Moffett IR fused for CModel params, default: IR_fused_for_CModel_params')
args = arg_parser.parse_args()
frontendcompile(args)
| LianjunW/QuantizationTools | examples/test_complier.py | test_complier.py | py | 3,582 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "sys.path.append",
"line_nu... |
17436666953 | import functools
import torch.nn as nn
import os
import sys
import time
import random
import argparse
import torch
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, norm_layer=None,
bn_eps=1e-5, bn_momentum=0.1, downsample=None, inplace=True):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes, eps=bn_eps, momentum=bn_momentum)
self.relu = nn.ReLU(inplace=inplace)
self.relu_inplace = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes, eps=bn_eps, momentum=bn_momentum)
self.downsample = downsample
self.stride = stride
self.inplace = inplace
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
if self.inplace:
out += residual
else:
out = out + residual
out = self.relu_inplace(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1,
norm_layer=None, bn_eps=1e-5, bn_momentum=0.1,
downsample=None, inplace=True):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = norm_layer(planes, eps=bn_eps, momentum=bn_momentum)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = norm_layer(planes, eps=bn_eps, momentum=bn_momentum)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
bias=False)
self.bn3 = norm_layer(planes * self.expansion, eps=bn_eps,
momentum=bn_momentum)
self.relu = nn.ReLU(inplace=inplace)
self.relu_inplace = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.inplace = inplace
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
if self.inplace:
out += residual
else:
out = out + residual
out = self.relu_inplace(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, in_channels=3, norm_layer=nn.BatchNorm2d, bn_eps=1e-5,
bn_momentum=0.1, deep_stem=False, stem_width=32, inplace=True):
self.inplanes = stem_width * 2 if deep_stem else 64
super(ResNet, self).__init__()
if deep_stem:
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels, stem_width, kernel_size=3, stride=2, padding=1,
bias=False),
norm_layer(stem_width, eps=bn_eps, momentum=bn_momentum),
nn.ReLU(inplace=inplace),
nn.Conv2d(stem_width, stem_width, kernel_size=3, stride=1,
padding=1,
bias=False),
norm_layer(stem_width, eps=bn_eps, momentum=bn_momentum),
nn.ReLU(inplace=inplace),
nn.Conv2d(stem_width, stem_width * 2, kernel_size=3, stride=1,
padding=1,
bias=False),
)
else:
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(stem_width * 2 if deep_stem else 64, eps=bn_eps,
momentum=bn_momentum)
self.relu = nn.ReLU(inplace=inplace)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, norm_layer, 64, layers[0],
inplace,
bn_eps=bn_eps, bn_momentum=bn_momentum)
self.layer2 = self._make_layer(block, norm_layer, 128, layers[1],
inplace, stride=2,
bn_eps=bn_eps, bn_momentum=bn_momentum)
self.layer3 = self._make_layer(block, norm_layer, 256, layers[2],
inplace, stride=2,
bn_eps=bn_eps, bn_momentum=bn_momentum)
self.layer4 = self._make_layer(block, norm_layer, 512, layers[3],
inplace, stride=2,
bn_eps=bn_eps, bn_momentum=bn_momentum)
def _make_layer(self, block, norm_layer, planes, blocks, inplace=True,
stride=1, bn_eps=1e-5, bn_momentum=0.1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
norm_layer(planes * block.expansion, eps=bn_eps,
momentum=bn_momentum),
)
layers = []
layers.append(block(self.inplanes, planes, stride, norm_layer, bn_eps,
bn_momentum, downsample, inplace))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes,
norm_layer=norm_layer, bn_eps=bn_eps,
bn_momentum=bn_momentum, inplace=inplace))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
blocks = []
x = self.layer1(x);
blocks.append(x)
x = self.layer2(x);
blocks.append(x)
x = self.layer3(x);
blocks.append(x)
x = self.layer4(x);
blocks.append(x)
return blocks
def load_model(model, model_file, is_restore=False):
t_start = time.time()
if model_file is None:
return model
# get the pretrained model dict
if isinstance(model_file, str):
state_dict = torch.load(model_file)
if 'model' in state_dict.keys():
state_dict = state_dict['model']
else:
state_dict = model_file
t_ioend = time.time()
# get the model dict
model_dict = model.state_dict()
# ini the corresponding layer
i = 0
j = 0
# with open('./before.txt', 'wt') as f:
# print(model_dict, file=f)
for k, v in state_dict.items():
if k in model_dict.keys():
if v.size() == model_dict[k].size():
model_dict[k] = state_dict[k]
i = i + 1
j = j + 1
print('total weight is',j)
print('using weight is',i)
# with open('./after.txt', 'wt') as f:
# print(model_dict, file=f)
model.load_state_dict(model_dict, strict=False)
ckpt_keys = set(state_dict.keys())
own_keys = set(model.state_dict().keys())
missing_keys = own_keys - ckpt_keys
unexpected_keys = ckpt_keys - own_keys
del state_dict
t_end = time.time()
print(
"Load model, Time usage:\n\tIO: {}, initialize parameters: {}".format(
t_ioend - t_start, t_end - t_ioend))
return model
def resnet18(pretrained_model=None, **kwargs):
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained_model is not None:
model = load_model(model, pretrained_model)
return model
def resnet34(pretrained_model=None, **kwargs):
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained_model is not None:
model = load_model(model, pretrained_model)
return model
def resnet50(pretrained_model=None, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained_model is not None:
model = load_model(model, pretrained_model)
return model
def resnet101(pretrained_model=None, **kwargs):
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained_model is not None:
model = load_model(model, pretrained_model)
return model
def resnet152(pretrained_model=None, **kwargs):
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained_model is not None:
model = load_model(model, pretrained_model)
return model
| xmed-lab/EPL_SemiDG | network/resnet.py | resnet.py | py | 9,203 | python | en | code | 33 | github-code | 36 | [
{
"api_name": "torch.nn.Conv2d",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "torch.nn.Module",
"line_number": 21,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_nu... |
289073657 | import pathlib
#path to the desktop
desktop = pathlib.Path("/home/symon_kipkemei")
#create a new folder folder
new_path = pathlib.Path("/home/symon_kipkemei/screenshots")
new_path.mkdir(exist_ok=True)
# list items in desktop
for filepath in desktop.iterdir():
#filter screenshots only
if filepath.suffix == ".db":
# create new path for each file
new_file_path = new_path.joinpath(filepath.name)
# move the screenshot there
filepath.replace(new_file_path)
| symonkipkemei/cnd-labs | python-101/labs/13_modules-and-automation.py | 13_modules-and-automation.py | py | 501 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pathlib.Path",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 8,
"usage_type": "call"
}
] |
21332967957 | from sostrades_core.execution_engine.sos_wrapp import SoSWrapp
from climateeconomics.core.core_land_use.land_use_v1 import LandUseV1
from sostrades_core.tools.post_processing.charts.chart_filter import ChartFilter
from sostrades_core.tools.post_processing.charts.two_axes_instanciated_chart import InstanciatedSeries,\
TwoAxesInstanciatedChart
import plotly.graph_objects as go
from sostrades_core.tools.post_processing.plotly_native_charts.instantiated_plotly_native_chart import \
InstantiatedPlotlyNativeChart
import os
import pandas as pd
from copy import deepcopy
from climateeconomics.core.core_witness.climateeco_discipline import ClimateEcoDiscipline
class LandUseV1Discipline(SoSWrapp):
''' Discipline intended to host land use pyworld3 with land use for food input from agriculture pyworld3
'''
# ontology information
_ontology_data = {
'label': 'Land Use V1 Model',
'type': 'Research',
'source': 'SoSTrades Project',
'validated': '',
'validated_by': 'SoSTrades Project',
'last_modification_date': '',
'category': '',
'definition': '',
'icon': 'fas fa-globe-europe fa-fw',
'version': '',
}
default_year_start = 2020
default_year_end = 2050
DESC_IN = {'year_start': ClimateEcoDiscipline.YEAR_START_DESC_IN,
'year_end': ClimateEcoDiscipline.YEAR_END_DESC_IN,
LandUseV1.LAND_DEMAND_DF: {'type': 'dataframe', 'unit': 'Gha',
'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_land_use'},
LandUseV1.TOTAL_FOOD_LAND_SURFACE: {'type': 'dataframe', 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_witness'},
LandUseV1.DEFORESTED_SURFACE_DF: {
'type': 'dataframe', 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_witness'},
LandUseV1.LAND_USE_CONSTRAINT_REF: {
'type': 'float', 'default': 0.1, 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_ref'}
}
DESC_OUT = {
LandUseV1.LAND_DEMAND_CONSTRAINT: {
'type': 'dataframe', 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_functions'},
LandUseV1.LAND_SURFACE_DF: {
'type': 'dataframe', 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_witness'},
LandUseV1.LAND_SURFACE_DETAIL_DF: {'type': 'dataframe', 'unit': 'Gha'},
LandUseV1.LAND_SURFACE_FOR_FOOD_DF: {
'type': 'dataframe', 'unit': 'Gha', 'visibility': SoSWrapp.SHARED_VISIBILITY, 'namespace': 'ns_witness'}
}
AGRICULTURE_CHARTS = 'Agriculture surface usage (Giga ha)'
FOREST_CHARTS = 'Forest usage (Giga ha)'
AVAILABLE_FOREST_CHARTS = 'Forests surface evolution (Giga ha)'
AVAILABLE_AGRICULTURE_CHARTS = 'Agriculture surface evolution (Giga ha)'
AGRICULTURE_FOOD_CHARTS = 'Agriculture usage for food (Giga ha)'
GLOBAL_CHARTS = 'Available land surface repartition'
def init_execution(self):
inputs = list(self.DESC_IN.keys())
param = self.get_sosdisc_inputs(inputs, in_dict=True)
self.land_use_model = LandUseV1(param)
def run(self):
#-- get inputs
inputs_dict = self.get_sosdisc_inputs()
#-- compute
land_demand_df = deepcopy(inputs_dict['land_demand_df'])
total_food_land_surface = deepcopy(
inputs_dict['total_food_land_surface'])
deforested_surface_df = deepcopy(inputs_dict['forest_surface_df'])
deforested_surface_df.index = land_demand_df['years']
self.land_use_model.compute(
land_demand_df, total_food_land_surface, deforested_surface_df)
outputs_dict = {
LandUseV1.LAND_DEMAND_CONSTRAINT: self.land_use_model.land_demand_constraint,
LandUseV1.LAND_SURFACE_DETAIL_DF: self.land_use_model.land_surface_df,
LandUseV1.LAND_SURFACE_DF: self.land_use_model.land_surface_df[[
'Agriculture (Gha)', 'Forest (Gha)']],
LandUseV1.LAND_SURFACE_FOR_FOOD_DF: self.land_use_model.land_surface_for_food_df
}
#-- store outputs
self.store_sos_outputs_values(outputs_dict)
def compute_sos_jacobian(self):
"""
Compute jacobian for each coupling variable
gradient of coupling variable to compute:
land_demand_objective_df wrt land_demand_df
"""
inputs_dict = self.get_sosdisc_inputs()
land_demand_df = inputs_dict['land_demand_df']
total_food_land_surface = inputs_dict['total_food_land_surface']
deforested_surface_df = inputs_dict['forest_surface_df']
model = self.land_use_model
# Retrieve variables
land_demand_df = model.land_demand_df
land_demand_constraint = model.land_demand_constraint
land_surface_df = model.land_surface_df
# build columns
land_demand_df_columns = list(land_demand_df)
land_demand_df_columns.remove('years')
land_demand_constraint_columns = list(land_demand_constraint)
land_demand_constraint_columns.remove('years')
land_surface_df_columns = list(land_surface_df)
land_surface_df_columns.remove('Agriculture total (Gha)')
land_surface_df_columns.remove('Food Usage (Gha)')
land_surface_df_columns.remove('Added Forest (Gha)')
land_surface_df_columns.remove('Added Agriculture (Gha)')
land_surface_df_columns.remove('Deforestation (Gha)')
for objective_column in land_demand_constraint_columns:
for demand_column in land_demand_df_columns:
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_DEMAND_CONSTRAINT, objective_column), (LandUseV1.LAND_DEMAND_DF, demand_column), model.get_derivative(objective_column, demand_column),)
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_DEMAND_CONSTRAINT, objective_column), (LandUseV1.TOTAL_FOOD_LAND_SURFACE, 'total surface (Gha)'), model.d_land_demand_constraint_d_food_land_surface(objective_column),)
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_DEMAND_CONSTRAINT, objective_column), (LandUseV1.DEFORESTED_SURFACE_DF, 'forest_surface_evol'), model.d_land_demand_constraint_d_deforestation_surface(objective_column),)
d_surface_d_population = model.d_land_surface_for_food_d_food_land_surface()
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_SURFACE_FOR_FOOD_DF, 'Agriculture total (Gha)'), (LandUseV1.TOTAL_FOOD_LAND_SURFACE, 'total surface (Gha)'), d_surface_d_population)
for objective_column in land_surface_df_columns:
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_SURFACE_DF, objective_column), (LandUseV1.TOTAL_FOOD_LAND_SURFACE, 'total surface (Gha)'), model.d_agriculture_surface_d_food_land_surface(objective_column),)
for demand_column in land_demand_df_columns:
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_SURFACE_DF, objective_column), (LandUseV1.LAND_DEMAND_DF, demand_column), model.d_constraint_d_surface(objective_column, demand_column),)
self.set_partial_derivative_for_other_types(
(LandUseV1.LAND_SURFACE_DF, objective_column), (LandUseV1.DEFORESTED_SURFACE_DF, 'forest_surface_evol'), model.d_land_surface_d_deforestation_surface(objective_column),)
def get_chart_filter_list(self):
# For the outputs, making a graph for tco vs year for each range and for specific
# value of ToT with a shift of five year between then
chart_filters = []
chart_list = [
LandUseV1Discipline.AGRICULTURE_CHARTS, LandUseV1Discipline.FOREST_CHARTS, LandUseV1Discipline.GLOBAL_CHARTS]
# First filter to deal with the view : program or actor
chart_filters.append(ChartFilter(
'Charts filter', chart_list, chart_list, 'charts'))
return chart_filters
def get_post_processing_list(self, chart_filters=None):
'''
For the outputs, making a graph for tco vs year for each range and for specific
value of ToT with a shift of five year between then
'''
instanciated_charts = []
# Overload default value with chart filter
if chart_filters is not None:
for chart_filter in chart_filters:
if chart_filter.filter_key == 'charts':
chart_list = chart_filter.selected_values
demand_df = self.get_sosdisc_inputs(LandUseV1.LAND_DEMAND_DF)
surface_df = self.get_sosdisc_outputs(LandUseV1.LAND_SURFACE_DETAIL_DF)
years = demand_df['years'].values.tolist()
if LandUseV1Discipline.FOREST_CHARTS in chart_list:
# ------------------------------------------------------------
# FOREST USAGE -> Technologies that uses forest (ManagedWood,
# UnmanagedWood..)
if demand_df is not None:
forest_surfaces = surface_df['Forest (Gha)'].values
forest_surface_series = InstanciatedSeries(
years, forest_surfaces.tolist(), 'Available surface', InstanciatedSeries.LINES_DISPLAY)
series_to_add = []
for column in list(demand_df):
if column in LandUseV1.FOREST_TECHNO:
new_series = InstanciatedSeries(
years, (demand_df[column]).values.tolist(), column.replace('(Gha)', ''), InstanciatedSeries.BAR_DISPLAY)
series_to_add.append(new_series)
new_chart = TwoAxesInstanciatedChart('years', LandUseV1Discipline.FOREST_CHARTS,
chart_name=LandUseV1Discipline.FOREST_CHARTS, stacked_bar=True)
new_chart.add_series(forest_surface_series)
for serie in series_to_add:
new_chart.add_series(serie)
instanciated_charts.append(new_chart)
if LandUseV1Discipline.AGRICULTURE_CHARTS in chart_list:
# ------------------------------------------------------------
# AGRICULTURE USAGE -> Technologies that uses agriculture land
# (CropEnergy, SolarPV..)
if demand_df is not None:
agriculture_surfaces = surface_df['Agriculture total (Gha)'].values
agriculture_surface_series = InstanciatedSeries(
years, agriculture_surfaces.tolist(), 'Total agriculture surface', InstanciatedSeries.LINES_DISPLAY)
series_to_add = []
key = 'Food Usage (Gha)'
legend = 'Food usage : Crop & lifestock'
new_series = InstanciatedSeries(
years, (surface_df[key]).values.tolist(), legend, InstanciatedSeries.BAR_DISPLAY)
series_to_add.append(new_series)
for column in list(demand_df):
if column in LandUseV1.AGRICULTURE_TECHNO:
new_series = InstanciatedSeries(
years, (demand_df[column]).values.tolist(), column.replace('(Gha)', ''), InstanciatedSeries.BAR_DISPLAY)
series_to_add.append(new_series)
new_chart = TwoAxesInstanciatedChart('years', LandUseV1Discipline.AGRICULTURE_CHARTS,
chart_name=LandUseV1Discipline.AGRICULTURE_CHARTS, stacked_bar=True)
new_chart.add_series(agriculture_surface_series)
for serie in series_to_add:
new_chart.add_series(serie)
instanciated_charts.append(new_chart)
if LandUseV1Discipline.GLOBAL_CHARTS in chart_list:
# ------------------------------------------------------------
# GLOBAL LAND USE -> Display surfaces (Ocean, Land, Forest..)
years_list = [self.get_sosdisc_inputs('year_start')]
# ------------------
# Sunburst figure for global land use. Source
# https://ourworldindata.org/land-use
for year in years_list:
# Create figure
fig = go.Figure(go.Sunburst(
labels=["Land", "Ocean", "Habitable land", "Glaciers", "Barren land",
"Agriculture", "Forest", "Shrub", "Urban", "Fresh water"],
parents=["Earth", "Earth", "Land", "Land", "Land", "Habitable land",
"Habitable land", "Habitable land", "Habitable land", "Habitable land"],
values=[14.9, 36.1, 10.5, 1.5, 2.8,
5.1, 3.9, 1.2, 0.15, 0.15],
marker=dict(colors=["#CD912A", "#1456C5", "#DBBF6A", "#D3D3D0",
"#E7C841", "#7CC873", "#1EA02F", "#5C8C56", "#B1B4AF", "#18CDFA"]),
branchvalues="total",
rotation=90,
)
)
fig.update_layout(
autosize=True,
margin=dict(t=80, l=0, r=0, b=0)
)
# Create native plotly chart
chart_name = f'Global land use (Gha) in {year}'
land_use_chart = InstantiatedPlotlyNativeChart(
fig=fig, chart_name=chart_name)
instanciated_charts.append(land_use_chart)
series_to_add = []
# ------------------
# Agriculture + forest surface are 92.03 M km^2 => 9.203 Gha.
# Source https://ourworldindata.org/land-use
earth_surface = [9.203] * len(years)
forest_surface_series = InstanciatedSeries(
years, earth_surface, 'Available surface', InstanciatedSeries.LINES_DISPLAY)
series_to_add.append(forest_surface_series)
agriculture_surface = InstanciatedSeries(
years, (surface_df['Agriculture total (Gha)']).values.tolist(), surface_df['Agriculture total (Gha)'].name.replace(' total (Gha)', ''), InstanciatedSeries.BAR_DISPLAY)
series_to_add.append(agriculture_surface)
forest_surface = InstanciatedSeries(
years, (surface_df['Forest (Gha)']).values.tolist(), surface_df['Forest (Gha)'].name.replace('(Gha)', ''), InstanciatedSeries.BAR_DISPLAY)
series_to_add.append(forest_surface)
new_chart = TwoAxesInstanciatedChart('years', LandUseV1Discipline.GLOBAL_CHARTS,
chart_name=LandUseV1Discipline.GLOBAL_CHARTS, stacked_bar=True)
for serie in series_to_add:
new_chart.add_series(serie)
instanciated_charts.append(new_chart)
return instanciated_charts
| os-climate/witness-core | climateeconomics/sos_wrapping/sos_wrapping_land_use/land_use/land_use_v1_disc.py | land_use_v1_disc.py | py | 15,085 | python | en | code | 7 | github-code | 36 | [
{
"api_name": "sostrades_core.execution_engine.sos_wrapp.SoSWrapp",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "climateeconomics.core.core_land_use.land_use_v1.LandUseV1.LAND_DEMAND_DF",
"line_number": 38,
"usage_type": "attribute"
},
{
"api_name": "climateeconomics... |
19412985681 | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
name = "This time"
urlpatterns = patterns('articles.views',
# home page
url(r'^$', 'collections', kwargs={"template_name": "home.html"}),
# inserting collections
url(r'^insert_collection.html/$', 'upload_file', kwargs={"template_name": "insert.html"}),
# Query Articles
url(r'^query.html/$', 'db_query', kwargs={"template_name": "query.html"}),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)
| jlong29/AY250 | Homework7/bibtex/urls.py | urls.py | py | 746 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.contrib.admin.autodiscover",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "django.contrib.admin",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "django.contrib.admin.site",
"line_number": 22,
"usage_type": "attribute"
},
{
... |
462199369 | # the dupe bot needs a lot of special logic so it can't really use the same code as the other bots sadly
import discord
import logging
import time
import asyncio
from enum import Enum
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from asyncio import Lock, Event, Queue
from cmd_util import *
from cooldown import CooldownHelper
class TheTyper:
def __init__(self, profile_id, url):
self.profile_id = profile_id
self.url = url
self.current_msg = None
self.event = Event()
self.lock = Lock()
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=profiles/" + self.profile_id)
self.driver = webdriver.Chrome(options=options)
self.driver.get(self.url)
async def send_message(self, msg):
async with self.lock:
self.event.clear()
self.current_msg = msg
elem = TheTyper.get_input_box(self.driver)
TheTyper.type_message(elem, msg)
TheTyper.do_send_message(elem)
await self.event.wait()
def on_message(self, msg):
if msg.content == self.current_msg:
self.current_msg = None
self.event.set()
@staticmethod
def get_input_box(driver):
while True:
try:
return driver.find_element_by_xpath("//div[contains(@class, 'slateTextArea')]")
except NoSuchElementException:
time.sleep(1)
@staticmethod
def type_message(elem, txt):
elem.click()
elem.send_keys(Keys.CONTROL, 'a')
elem.send_keys(txt)
@staticmethod
def do_send_message(elem):
elem.send_keys(Keys.RETURN)
class StealResult(Enum):
TIMEOUT = 0
NOT_ENOUGH_COINS = 1
CAUGHT = 2
TWO_MIN = 3
SMALL_AMOUNT = 4
LARGE_AMOUNT = 5
FULL_AMOUNT = 6
class TheBot(discord.Client):
T_STEAL_COOLDOWN = "Woahhh there, you need some time to plan your next hit. Wait "
T_STEAL_NOT_ENOUGH_COINS = "You need at least 250 coins to try and rob someone."
T_STEAL_CAUGHT = "You were caught **HAHAHA**\nYou paid the person you stole from **250** coins."
T_STEAL_2_MIN = "This user has already been stolen from within the last 2 minutes, give it a rest"
P_STEAL_SMALL_AMOUNT = re.compile("^You stole a small portion! 💸\nYour payout was \\*\\*([0-9,]+)\\*\\* coins.$")
P_STEAL_LARGE_AMOUNT = re.compile("^You stole a good chunk! 💰\nYour payout was \\*\\*([0-9,]+)\\*\\* coins.$")
P_STEAL_FULL_AMOUNT = re.compile("^You stole A SHIT TON! 🤑\nYour payout was \\*\\*([0-9,]+)\\*\\* coins.$")
P_GIVE_RESULT = re.compile(f"^You gave .+ \*\*[0-9,]+\*\* coins after a [0-9,]+% tax rate, now you have (-?[0-9,]+) and they've got [0-9,]+" + P_EOL)
P_GIVE_ERROR = re.compile("^You only have ([0-9,]+) coins, you can't share that many$");
T_SEARCH_OPTIONS = "Where do you want to search? Pick from the list below and type it in chat.\n"
T_SEARCH_COOLDOWN = "You've already scouted the area for coins, try again in "
def __init__(self, config_loser, config_winner):
super().__init__()
self.log = logging.getLogger("bot")
self.bot_id = config_winner["bot_id"]
self.bot_prefix = config_winner["bot_prefix"]
self.config_loser = config_loser
self.config_winner = config_winner
self.loser_id = config_loser["user_id"]
self.winner_id = config_winner["user_id"]
self.owner_id = config_winner["owner_id"]
self.typer_loser = TheTyper(config_loser["profile_id"], config_loser["type_url"])
self.typer_winner = TheTyper(config_winner["profile_id"], config_winner["type_url"])
self.typer_loser_q = Queue()
self.typer_winner_txt = Queue()
self.doing_it = False
self.steal_result = None
self.stolen_amount = 0
self.loser_balance = 0
self.cooldown_time = 0
self.search_ok = False
self.search_entered_location = False
self.current_event = Event()
self.current_handler = None
self.extended_timeout = 0
def get_prefixed_cmd(self, cmd):
return self.bot_prefix + " " + cmd
async def on_ready(self):
self.log.info(f"Logged on as {self.user}")
async def wait_for_handler(self, handler):
self.extended_timeout = 0
self.current_event.clear()
self.current_handler = handler
try:
await asyncio.wait_for(self.current_event.wait(), 20) # wait up to 20s
self.current_handler = None
except asyncio.exceptions.TimeoutError:
while True:
rem = self.extended_timeout - time.time()
if rem <= 0:
break
self.log.info(f"Waiting with extended timeout: {rem}s")
try:
await asyncio.wait_for(self.current_event.wait(), rem)
self.current_handler = None
return
except asyncio.exceptions.TimeoutError:
pass
async def synctest(self):
await self.typer_winner.lock.acquire()
await self.typer_loser.lock.acquire()
box_winner = TheTyper.get_input_box(self.typer_winner.driver)
box_loser = TheTyper.get_input_box(self.typer_loser.driver)
TheTyper.type_message(box_winner, "account 1")
TheTyper.type_message(box_loser, "account 2")
self.log.info(f"Pressing enter")
TheTyper.do_send_message(box_winner)
TheTyper.do_send_message(box_loser)
self.typer_winner.lock.release()
self.typer_loser.lock.release()
async def do_it(self, channel):
if self.doing_it:
await channel.send("you are dumb, the process is already in progress")
return
self.doing_it = True
await channel.send("gotcha, good luck")
self.log.info("1. STEAL")
while True:
result, amount = await self.steal(self.winner_id)
# result, amount = StealResult.FULL_AMOUNT, 1353345
self.log.info(f"Steal completed: result={result} amount={amount}")
if result == StealResult.NOT_ENOUGH_COINS:
self.log.info(f"Giving ourself money from winner")
await self.typer_winner.send_message(f"pls give <@!{self.loser_id}> 250")
await asyncio.sleep(1)
continue
if result == StealResult.TIMEOUT:
await asyncio.sleep(self.cooldown_time + 0.5)
continue
if result == StealResult.CAUGHT:
await asyncio.sleep(self.config_loser["cooldown"]["steal"] + 0.5)
continue
if result == StealResult.TWO_MIN:
self.log.info(f"Steal failed")
await channel.send(f"<@!{self.owner_id}> steal failed :/")
self.doing_it = False
return
if result == StealResult.SMALL_AMOUNT or result == StealResult.LARGE_AMOUNT or result == StealResult.FULL_AMOUNT:
break
self.log.info("2. THE RACE")
self.log.info(f"Stolen {amount}")
await self.typer_winner.lock.acquire()
await self.typer_loser.lock.acquire()
box_winner = TheTyper.get_input_box(self.typer_winner.driver)
box_loser = TheTyper.get_input_box(self.typer_loser.driver)
TheTyper.type_message(box_winner, "pls use reversal")
TheTyper.type_message(box_loser, f"pls give <@!{self.winner_id}> {amount+250}")
self.log.info(f"Pressing enter")
TheTyper.do_send_message(box_winner)
TheTyper.do_send_message(box_loser)
self.typer_winner.lock.release()
self.typer_loser.lock.release()
self.loser_balance = 0
await self.wait_for_handler(self.handle_race)
self.log.info("3. DEATH")
if self.loser_balance < 0:
await self.suicide()
self.log.info("DONE")
await channel.send("we completed this process i guess?")
self.doing_it = False
async def suicide(self):
first_attempt = True
self.search_ok = False
while not self.search_ok:
if not first_attempt:
await asyncio.sleep(self.config_loser["cooldown"]["search"])
first_attempt = False
self.search_entered_location = False
await self.typer_loser.send_message("pls search")
await self.wait_for_handler(self.handle_search)
self.log.info(f"A search has completed: ok={self.search_ok}")
async def steal(self, from_who):
self.steal_result = None
self.current_event.clear()
await self.typer_loser.send_message(self.get_prefixed_cmd(f"steal <@!{from_who}>"))
await self.wait_for_handler(self.handle_steal)
return self.steal_result, self.stolen_amount
async def handle_steal(self, message):
if message.channel.id != self.config_loser["type_channel_id"]:
return
c = CooldownHelper.extract_cooldown(message, TheBot.T_STEAL_COOLDOWN)
if c is not None:
self.steal_result = StealResult.TIMEOUT
self.cooldown_time = c
return True
if message.content == TheBot.T_STEAL_NOT_ENOUGH_COINS:
self.steal_result = StealResult.NOT_ENOUGH_COINS
return True
if message.content == TheBot.T_STEAL_CAUGHT:
self.steal_result = StealResult.CAUGHT
return True
if message.content == TheBot.T_STEAL_2_MIN:
self.steal_result = StealResult.TWO_MIN
return True
for s, ss in [(TheBot.P_STEAL_SMALL_AMOUNT, StealResult.SMALL_AMOUNT), (TheBot.P_STEAL_LARGE_AMOUNT, StealResult.LARGE_AMOUNT), (TheBot.P_STEAL_FULL_AMOUNT, StealResult.FULL_AMOUNT)]:
t = s.match(message.content)
if t:
self.steal_result = ss
self.stolen_amount = parse_bot_int(t.group(1))
return True
return False
async def handle_race(self, message):
if message.channel.id != self.config_loser["type_channel_id"]:
return
t = TheBot.P_GIVE_RESULT.match(message.content)
if t:
self.loser_balance = parse_bot_int(t.group(1))
return True
t = TheBot.P_GIVE_ERROR.match(message.content)
if t:
self.loser_balance = parse_bot_int(t.group(1))
return True
return False
async def handle_search(self, message):
if message.channel.id != self.config_loser["type_channel_id"]:
return
if self.search_entered_location:
self.log.info("Search msg: " + message.content)
if "what are you THINKING man that's not a valid option from the list??" in message.content:
return True
if "You got off scot-free this time, but you better pay your fine next time or else the police might getcha" in message.content:
return True
if "The police are on your ass and they're coming for you " in message.content:
self.log.info("Extended timeout for police")
self.extended_timeout = time.time() + 60
return False
if "Area searched" in message.content and ("You drowned in a river of shit, how fun!" in message.content or "You contracted dog ass disease from touching dog shit. You died." in message.content or "You got hit by a car LOL." in message.content): # You contracted dog ass disease from touching dog shit. You died.
self.search_ok = True
return True
if "Area searched" in message.content:
return True
if "The police are here, and they're after you!" in message.content:
await self.typer_loser.send_message("0gleeb57ne")
self.search_ok = True
return True
return False
c = CooldownHelper.extract_cooldown(message, TheBot.T_SEARCH_COOLDOWN)
if c is not None:
return True
preferences = ["street", "car", "dog", "purse", "pocket", "sewer", "dumpster", "coat", "attic"]
if message.content.startswith(TheBot.T_SEARCH_OPTIONS):
options, _, _ = message.content[len(TheBot.T_SEARCH_OPTIONS):].partition("\n")
options = options.split(", ")
options = [o[1:-1] for o in options if len(o) > 0 and o[0] == '`' and o[-1] == '`']
for s in preferences:
if s in options:
await self.typer_loser.send_message(s)
self.search_entered_location = True
return False
await self.typer_loser.send_message("neither")
self.search_entered_location = True
return False
return False
async def on_message(self, message):
if message.author.id == self.winner_id:
self.typer_winner.on_message(message)
if message.author.id == self.loser_id:
self.typer_loser.on_message(message)
if message.author.id == self.bot_id:
message.content = filter_out_hint(message.content)
if self.current_handler is not None:
if await self.current_handler(message):
self.current_handler = None
self.current_event.set()
if message.content.startswith("plz ") and (message.author.id == self.owner_id):
args = message.content[4:].split(" ")
if args[0] == "doit":
await self.do_it(message.channel)
if args[0] == "synctest":
await self.synctest()
if args[0] == "suicide":
await self.suicide()
import sys
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(name)s %(message)s', stream=sys.stdout)
logging.getLogger("bot").setLevel(logging.DEBUG)
from config_alt1 import config
config_winner = dict(config)
from config_alt2 import config
config_loser = dict(config)
bot = TheBot(config_loser, config_winner)
bot.run(config_winner["token"])
| Sadtrxsh/Mathboi | dupe.py | dupe.py | py | 14,259 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "asyncio.Event",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "asyncio.Lock",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "selenium.webdriver.ChromeOptions",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "selenium.... |
18617730217 | # python 3.6
# author: qcw
from requests import get, exceptions
import re
class SentiveFile(object):
"""
从可能泄露的敏感文件中发现子域名,如crossdomain.xml、robots.txt等等
"""
def __init__(self, url):
"""
:param url: 外部输入的url
:param domians:返回主程序的结果
"""
self.url = url
self.domains = set()
CROSS_DOMAIN_XML = """<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="localhost:3001" />
</cross-domain-policy>
"""
def get_sentive_message(self):
"""
files列表可从外部导入文件
爬取可能泄露信息页面中的敏感信息
:return: self.domains
"""
files = [
"/crossdomain.xml",
"/robot.txt"
]
res_access = r'<allow-access-from domain="(.*?)"'
try:
for file in files:
r = get(self.url + file)
domain = re.findall(res_access, r.text)
# ['a', 'a', 'g', 'https://sdfsjf', 'http://sdfjhksdfjhkl', 'k3elwjk'] #
if len(domain) != 0:
for i in range(len(domain)):
self.domains.add(domain[i])
except exceptions.RequestException as e:
print(e)
print(self.domains)
def get_clean(self):
"""
初清洗 暂时只褪去http://
:return:
"""
unwashed_domains = self.domains
cleaned_domains = set()
for domain in unwashed_domains:
if 'http://' in domain:
domain = domain.replace('http://', '')
if 'https://' in domain:
domain = domain.replace('https://', '')
cleaned_domains.add(domain)
self.domains = cleaned_domains
print(self.domains)
def main(url):
# 建立对象
sentive_file = SentiveFile(url)
# 获取页面内容中敏感信息
sentive_file.get_sentive_message()
# 清洗数据
sentive_file.get_clean()
if __name__ == '__main__':
main("http://www.sina.com.cn")
| b1ackc4t/getdomain | module/active/SensitiveFile.py | SensitiveFile.py | py | 2,248 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "requests.get",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "re.findall",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "requests.exceptions.RequestException",
"line_number": 47,
"usage_type": "attribute"
},
{
"api_name": "req... |
73082338983 | import numpy as np
from sklearn import metrics
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
def calculate_AUC(model_results):
'''
:param model_results: model_results=[TP, FP, TN, FN, pred, pred_prob, test_data, test_flag]
:return: auc
'''
print(">>> Calculating AUC value:")
true_positive, false_positive, true_negative, false_negative = model_results[0], model_results[1], model_results[2], model_results[3]
pred, pred_prob, test_data, test_flag = model_results[4], model_results[5], model_results[6], model_results[7]
# fpr = false_positive / (false_positive + true_negative)
# tpr = true_positive / (true_positive + false_positive)
# fpr, tpr, thresholds = metrics.roc_curve(test_flag, pred, pos_label=1)
# auc = metrics.auc(fpr, tpr)
#multi-case
# roc curve for classes
fpr = {}
tpr = {}
thresh = {}
auc = {}
n_class = 3
for i in range(n_class):
fpr[i], tpr[i], thresh[i] = roc_curve(test_flag, pred_prob[:, i], pos_label=i)
auc[i] = metrics.auc(fpr[i], tpr[i])
# print("AUC is : ", auc)
print("AUC-class-1 is : ", auc[0])
print("AUC-class-2 is : ", auc[1])
print("AUC-class-3 is : ", auc[2])
return auc | lauraqing/test_metric_evaluation_s3 | calculate_AUC.py | calculate_AUC.py | py | 1,292 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sklearn.metrics.roc_curve",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics.auc",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics",
"line_number": 31,
"usage_type": "name"
}
] |
6117512730 | from __future__ import annotations
import logging
import math
import pickle
import lpips
import omegaconf
import pytorch3d
import pytorch3d.io
import torch
from pytorch3d import transforms
from pytorch3d.ops.points_alignment import SimilarityTransform
from pytorch3d.renderer.cameras import CamerasBase
from pytorch3d.transforms import Transform3d
from pytorch3d.vis.plotly_vis import plot_scene
from visdom import Visdom
from ..nnutils.cameras import dollyParamCameras
from ..utils import metrics as metric_utils
from ..utils.align_meshes import align_depth
from ..utils.mesh import (RTs_to_transform, align_shapes, invert_RTs,
transform_cameras, transform_mesh, transform_to_RTs)
from ..utils.misc import add_suffix_to_path, apply_dict_rec, try_move_device
def find_alignment(mesh_pred, mesh_gt, pose_pred0, pose_gt0, use_icp=True, align_scale_view0=False, align_depth_kwargs={}, icp_type='g2p_uncentered',):
# First align predcam0 with gtcam0
pR,pT = pose_pred0.view(3, 4)[None, :,:3], pose_pred0.view(3, 4)[None, :,3]
gR,gT = pose_gt0.view(3, 4)[None, :,:3], pose_gt0.view(3, 4)[None, :,3]
pTr = RTs_to_transform(SimilarityTransform(pR.transpose(1,2),pT,1))
gTr = RTs_to_transform(SimilarityTransform(gR.transpose(1,2),gT,1))
if align_scale_view0:
mesh_pred_view = transform_mesh(mesh_pred, pTr)
mesh_gt_view = transform_mesh(mesh_gt, gTr)
_, scalingTr_pred2gt = align_depth(mesh_pred_view, mesh_gt_view, **align_depth_kwargs)
g2pTr = gTr.compose(scalingTr_pred2gt.inverse(), pTr.inverse())
else:
g2pTr = gTr.compose(pTr.inverse())
if use_icp:
logging.info(f'Aligning with ICP (type={icp_type})')
assert icp_type in [
'g2p_uncentered', 'g2p_centered', 'p2g_uncentered', 'p2g_centered',
'g2p_noscale_uncentered', 'g2p_noscale_centered', 'p2g_noscale_uncentered', 'p2g_noscale_centered',
]
mesh_gt = transform_mesh(mesh_gt, g2pTr)
if icp_type.endswith('_centered'):
# Centre both mesh_gt and mesh_pred to mesh_gt's centroid
# First, find mesh radius from gt mesh, and create a centering transform
verts = mesh_gt.verts_packed()
mesh_vcen = (verts.min(0)[0] + verts.max(0)[0])/2
mesh_radius = (verts-mesh_vcen).norm(dim=-1).max().item()
centering_transform = Transform3d(device=mesh_gt.device).translate(-mesh_vcen[None]).scale(1/mesh_radius)
# Then, transform accordingly.
mesh_gt = transform_mesh(mesh_gt, centering_transform)
mesh_pred = transform_mesh(mesh_pred, centering_transform)
else:
centering_transform = Transform3d(device=mesh_gt.device)
estimate_scale = 'noscale' not in icp_type
if icp_type.startswith('g2p'):
align_w2c = align_shapes(mesh_gt, mesh_pred, estimate_scale=estimate_scale, verbose=True, num_samples=100_000)
else:
align_w2c = invert_RTs(align_shapes(mesh_pred, mesh_gt, estimate_scale=estimate_scale, verbose=True, num_samples=100_000))
logging.debug(f'Alignment: {align_w2c}')
if not (1e-3 <= align_w2c.s <= 1e3):
logging.warning(f'ICP failed (scale {align_w2c.s}), using identity')
device = align_w2c.R.device
align_w2c = SimilarityTransform(
torch.eye(3, device=device, dtype=torch.float)[None],
torch.zeros(3, device=device, dtype=torch.float)[None],
torch.ones(1, device=device, dtype=torch.float),
)
tr_w2c = g2pTr.compose(centering_transform, RTs_to_transform(align_w2c), centering_transform.inverse())
else:
tr_w2c = g2pTr
align_w2c = transform_to_RTs(tr_w2c)
return align_w2c
class eval_base():
def newpath(self, path):
if path[0]=='/':
return path
else:
return f'{self.expdir}/{path}'
def get_checkpoint_path(self):
raise NotImplementedError
def load_checkpoint(self, iter):
chkpt_path = self.newpath(self.get_checkpoint_path())
if iter=='latest':
pass # No suffix
else:
chkpt_path = add_suffix_to_path(chkpt_path, f'_{iter:08d}')
loaded_data = torch.load(chkpt_path)
return loaded_data
def __init__(self, expdir, iter='latest', device='cuda') -> None:
# Load config
self.expdir = expdir
self.cfg = cfg = omegaconf.OmegaConf.load(self.newpath('.hydra/config.yaml'))
# Load input data
with open(self.newpath(cfg.init_data_path), 'rb') as handle:
self.data = data = pickle.load(handle)
self.data = apply_dict_rec(self.data, fv = lambda x: try_move_device(x, device))
# Load checkpoint
self.loaded_data = self.load_checkpoint(iter)
# Camera generators
self.pred_camera_generator: dollyParamCameras
self.gt_camera_generator = dollyParamCameras(
data.train.poses_gt, data.train.hfovs_gt, optimize_cam=False, device=device
)
self.val_camera_generator = dollyParamCameras(
data.val.poses, data.val.hfovs, optimize_cam=False, device=device
)
# Misc
self.iter = iter
self.device = device
self.aligned = False
self.align_w2c = transforms.Transform3d()
self._lpips_fn = None # populate when needed
@property
def lpips_fn(self):
if self._lpips_fn is None:
self._lpips_fn = lpips.LPIPS(net='alex').to(self.device)
return self._lpips_fn
def finished_iters(self):
return self.loaded_data["finished_iter"] + 1
def build_mesh(self):
raise NotImplementedError
@torch.no_grad()
def get_alignment(self, use_icp=True, align_scale_view0=False, align_depth_kwargs={}, icp_type='g2p_uncentered',):
if not self.aligned:
# First align predcam0 with gtcam0
pR,pT,_,_ = self.pred_camera_generator.get_RTfovF(id=0)
gR,gT,_,_ = self.gt_camera_generator.get_RTfovF(id=0)
p_pose = torch.cat([pR, pT[:,:,None]], dim=2)
g_pose = torch.cat([gR, gT[:,:,None]], dim=2)
mesh_pred = self.build_mesh().to(self.device)
mesh_gt = self.data.mesh_gt
self.align_w2c = find_alignment(mesh_pred, mesh_gt, p_pose, g_pose,
use_icp=use_icp, align_scale_view0=align_scale_view0,
icp_type=icp_type, **align_depth_kwargs)
self.aligned = True
return self.align_w2c
@torch.no_grad()
def compute_shape_metrics(self, align=True, uni_chamfer=False, **align_kwargs):
mesh_pred = self.build_mesh()
mesh_gt = self.data.mesh_gt
# Aligning pred shape to gt
if align:
align_c2w = invert_RTs(self.get_alignment(**align_kwargs))
mesh_pred = transform_mesh(mesh_pred, align_c2w)
shape_metrics = metric_utils.compare_meshes(mesh_pred, mesh_gt, align_icp=False,
num_samples=100_000, return_per_point_metrics=uni_chamfer)
if uni_chamfer:
shape_metrics, (_,_,metrics_p2g), (_,_,metrics_g2p) = shape_metrics
shape_metrics.update({
"Chamfer-L2-p2g": metrics_p2g["Chamfer-L2"].mean().item(),
"Chamfer-L2-g2p": metrics_g2p["Chamfer-L2"].mean().item(),
})
return shape_metrics
@torch.no_grad()
def compute_camera_metrics(self, align=True, **align_kwargs):
cam_pred = self.pred_camera_generator.create_cameras()
cam_gt = self.gt_camera_generator.create_cameras()
centre = self.data.mesh_centre
# Aligning cameras
if align:
align_c2w = invert_RTs(self.get_alignment(**align_kwargs))
cam_pred = transform_cameras(cam_pred, align_c2w)
camera_metrics = metric_utils.compare_cameras(cam_pred, cam_gt, centre=centre, per_camera=True)
return camera_metrics
def render(self, cameras: CamerasBase, **kwargs):
raise NotImplementedError
def output_to_rgba(self, rend_out):
raise NotImplementedError
@torch.no_grad()
def visualize(self, viz:Visdom, align=True, gt_cam=False, init_cam=True):
"""
Visualize predicted/GT cameras, pred mesh, rendered images
"""
mesh_pred = self.build_mesh()
cam_pred_list = self.pred_camera_generator.create_cameras_list()
cam_gt_list = self.gt_camera_generator.create_cameras_list()
cam_init_list = dollyParamCameras(self.data.train.poses, self.data.train.hfovs).create_cameras_list()
centre = self.data.mesh_centre
# Render training images (before aligning cameras)
rend_rgba = []
assert(len(cam_pred_list) == len(self.data.train.rgba))
for camera in cam_pred_list:
rend_out = self.render(camera)
rend_rgba.append(rend_out.rgba)
rend_rgba = torch.cat(rend_rgba, dim=0)
# Align pred cameras to gt
if align:
align_c2w = invert_RTs(self.get_alignment(align_scale_view0=True, use_icp=False))
cam_pred_list = [transform_cameras(c, align_c2w) for c in cam_pred_list]
mesh_pred = transform_mesh(mesh_pred, align_c2w)
if viz is not None:
# Visualize images
N = len(rend_rgba)
img_kwargs = dict(
nrow=round(math.sqrt(N)),
opts=dict(width = 800, height = 400, title="input | rend")
)
inp_rend_rgba = torch.cat([self.data.train.rgba,rend_rgba], dim=3)
viz.images(inp_rend_rgba[:,:3,:,:]*255, win="input | rend", **img_kwargs)
# Visualize cameras and shape
shape_trace = {'mesh_pred': mesh_pred.cpu()}
pred_camera_trace = {f'pred_cam_{i:03d}': c.to('cpu') for i,c in enumerate(cam_pred_list)}
def plot_shape_cams(strace, ctrace, win='scene'):
plotly_plot = plot_scene({
win: {**strace, **ctrace,},
},
camera_scale = 0.05,
)
viz.plotlyplot(plotly_plot, win=win)
plot_shape_cams(shape_trace, pred_camera_trace, 'pred cam scene')
if gt_cam:
gt_camera_trace = {f'gt_cam_{i:03d}': c.to('cpu') for i,c in enumerate(cam_gt_list)}
plot_shape_cams(shape_trace, gt_camera_trace, 'gt cam scene')
if init_cam:
init_camera_trace = {f'init_cam_{i:03d}': c.to('cpu') for i,c in enumerate(cam_init_list)}
plot_shape_cams(shape_trace, init_camera_trace, 'init cam scene')
return dict(
rend_rgba=rend_rgba,
)
@torch.no_grad()
def generate_360_visuals(self, out_dir_prefix='', num_frames=36, elevations=[-30,30]):
raise NotImplementedError
| shubham-goel/ds | src/eval/evaluate_base.py | evaluate_base.py | py | 11,007 | python | en | code | 68 | github-code | 36 | [
{
"api_name": "utils.mesh.RTs_to_transform",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "pytorch3d.ops.points_alignment.SimilarityTransform",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "utils.mesh.RTs_to_transform",
"line_number": 34,
"usage_ty... |
22353244515 | import hashlib
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
def _hash_list(*list_to_hash):
list_to_hash = [str(element) for element in list_to_hash]
str_concatted = "".join(list_to_hash)
sha1 = hashlib.sha1()
sha1.update(str_concatted.encode("utf8"))
return sha1.hexdigest()
def _redis_stringify_key(*args):
if len(args) == 1:
key_list = args[0]
else:
key_list = list(args)
suffix = "}:static"
if isinstance(key_list, list):
if len(key_list) >= 3:
return str(key_list[0]) + "." + _hash_list(*key_list[1:]) + suffix
if len(key_list) == 2:
return str(key_list[0]) + "." + str(key_list[1]) + suffix
return str(key_list[0]) + suffix
return str(key_list) + suffix
hash_and_concat_v3io_udf = udf(_hash_list, StringType())
hash_and_concat_redis_udf = udf(_redis_stringify_key, StringType())
| mlrun/mlrun | mlrun/datastore/spark_udf.py | spark_udf.py | py | 929 | python | en | code | 1,129 | github-code | 36 | [
{
"api_name": "hashlib.sha1",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "pyspark.sql.functions.udf",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "pyspark.sql.types.StringType",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "p... |
70152353705 | import numpy as np
from PIL import Image
IMAGE_SIZE = 1000
if __name__ == '__main__':
# Два изображения одинаковой яркости, но полностью разного цвета
img_1_1_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_1_1_data[..., 0] = 255
img_1_1 = Image.fromarray(img_1_1_data)
img_1_1.save('images/img_1_1.jpg', format='jpeg')
img_1_2_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_1_2_data[..., 2] = 255
img_1_2 = Image.fromarray(img_1_2_data)
img_1_2.save('images/img_1_2.jpg', format='jpeg')
# Два изображения одинаковой яркости, но почти одного цвета
img_2_1_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_2_1_data[..., 0] = 120
img_2_1_data[..., 1] = 121
img_2_1_data[..., 2] = 120
img_2_1 = Image.fromarray(img_2_1_data)
img_2_1.save('images/img_2_1.jpg', format='jpeg')
img_2_2_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_2_2_data[..., 0] = 120
img_2_2_data[..., 1] = 120
img_2_2_data[..., 2] = 121
img_2_2 = Image.fromarray(img_2_2_data)
img_2_2.save('images/img_2_2.jpg', format='jpeg')
# Два изображения. Одна - шахматная доска, вторая - инвертированная первая
img_3_1_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
for i in range(IMAGE_SIZE):
for j in range(IMAGE_SIZE):
if (i + j) % 2:
img_3_1_data[i, j, ...] = 255
img_3_1 = Image.fromarray(img_3_1_data)
img_3_1.save('images/img_3_1.jpg', format='jpeg')
img_3_2_data = 255 - img_3_1_data
img_3_2 = Image.fromarray(img_3_2_data)
img_3_2.save('images/img_3_2.jpg', format='jpeg')
# Два изображения. Исходное (1024 на 544), и увеличенное в 1.00098 раз изображение (1025 на 544)
s = 1.00098
img_4_1 = Image.open('images/img_4_1.jpg', formats=['jpeg'])
img_4_2 = img_4_1.resize((int(img_4_1.width * s), int(img_4_1.height * s)))
img_4_2.save('images/img_4_2.jpg', format='jpeg')
# Два изображения. Исходное (1024 на 544), и изображение (1024 на 544) цвета, как исходное в среднем
s = 1.00098
img_5_1 = Image.open('images/img_5_1.jpg', formats=['jpeg'])
img_5_2_data = np.array(img_5_1)
img_5_2_data[...] = int(img_5_2_data.mean())
img_5_2 = Image.fromarray(img_5_2_data)
img_5_2.save('images/img_5_2.jpg', format='jpeg')
# Два изображения разной яркости, но одного цвета
img_6_1_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_6_1_data[..., 0] = 50
img_6_1_data[..., 1] = 50
img_6_1_data[..., 2] = 25
img_6_1 = Image.fromarray(img_6_1_data)
img_6_1.save('images/img_6_1.jpg', format='jpeg')
img_6_2_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_6_2_data[..., 0] = 100
img_6_2_data[..., 1] = 100
img_6_2_data[..., 2] = 50
img_6_2 = Image.fromarray(img_6_2_data)
img_6_2.save('images/img_6_2.jpg', format='jpeg')
| borgishmorg/abchihba_back_end | image_generator.py | image_generator.py | py | 3,272 | python | ru | code | 0 | github-code | 36 | [
{
"api_name": "numpy.zeros",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "numpy.uint8",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "PIL.Image.fromarray",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_... |
31065215705 |
from ..utils import Object
class UpdateNewPreCheckoutQuery(Object):
"""
A new incoming pre-checkout query; for bots only. Contains full information about a checkout
Attributes:
ID (:obj:`str`): ``UpdateNewPreCheckoutQuery``
Args:
id (:obj:`int`):
Unique query identifier
sender_user_id (:obj:`int`):
Identifier of the user who sent the query
currency (:obj:`str`):
Currency for the product price
total_amount (:obj:`int`):
Total price for the product, in the smallest units of the currency
invoice_payload (:obj:`bytes`):
Invoice payload
shipping_option_id (:obj:`str`):
Identifier of a shipping option chosen by the user; may be empty if not applicable
order_info (:class:`telegram.api.types.orderInfo`):
Information about the order; may be null
Returns:
Update
Raises:
:class:`telegram.Error`
"""
ID = "updateNewPreCheckoutQuery"
def __init__(self, id, sender_user_id, currency, total_amount, invoice_payload, shipping_option_id, order_info, **kwargs):
self.id = id # int
self.sender_user_id = sender_user_id # int
self.currency = currency # str
self.total_amount = total_amount # int
self.invoice_payload = invoice_payload # bytes
self.shipping_option_id = shipping_option_id # str
self.order_info = order_info # OrderInfo
@staticmethod
def read(q: dict, *args) -> "UpdateNewPreCheckoutQuery":
id = q.get('id')
sender_user_id = q.get('sender_user_id')
currency = q.get('currency')
total_amount = q.get('total_amount')
invoice_payload = q.get('invoice_payload')
shipping_option_id = q.get('shipping_option_id')
order_info = Object.read(q.get('order_info'))
return UpdateNewPreCheckoutQuery(id, sender_user_id, currency, total_amount, invoice_payload, shipping_option_id, order_info)
| iTeam-co/pytglib | pytglib/api/types/update_new_pre_checkout_query.py | update_new_pre_checkout_query.py | py | 2,045 | python | en | code | 20 | github-code | 36 | [
{
"api_name": "utils.Object",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "utils.Object.read",
"line_number": 55,
"usage_type": "call"
},
{
"api_name": "utils.Object",
"line_number": 55,
"usage_type": "name"
}
] |
18854609090 | import cv2 # import the OpenCV module
import numpy as np # import the numpy module using the name 'np'.
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#HOMEWORK 2
# Utility functions
def show_wait(original, transformed, filename):
double = np.hstack((original,transformed)) #stacking images side-by-side
cv2.imwrite(filename, double)
def drawrectange(img, x,y,h,w):
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img,'rectangle',(x+w+10,y+h),0,0.3,(0,255,0))
return img
if __name__ == '__main__':
img1 = cv2.imread('img/1.jpg',1)
imgcopy = img1.copy()
x= 100
y=100
h=50
w=60
img1 = drawrectange(img1, x,y,h,w)
show_wait(imgcopy, img1, "result/rectangle.jpg")
img1 = cv2.imread('img/1.jpg',1)
x1 = 300
y1 = 300
x2 = 160
y2 = 150
h=y2-y1
w=x2-x1
img1 = drawrectange(img1, x1,y1,h,w)
show_wait(imgcopy, img1, "result/rectangle_2.jpg") | matitaweb/mumet2017_computer_vision_homework | HOMEWORK_03/bounding_box.py | bounding_box.py | py | 983 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "matplotlib.use",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "numpy.hstack",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "cv2.imwrite",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "cv2.rectangle",
"line_numb... |
22508968712 | import socket
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', port=6379)
hostname = socket.gethostname()
@app.route('/')
def hello():
redis.incr('hits')
return 'This is %s! There have been %s total hits.' % (
hostname,
redis.get('hits'),
)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
| GoodWriteHQ/datacenter-demo | service/app.py | app.py | py | 393 | python | en | code | 8 | github-code | 36 | [
{
"api_name": "flask.Flask",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "redis.Redis",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "socket.gethostname",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "redis.incr",
"line_number... |
27578227980 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import time,configparser
try:
from tkinter import *
except ImportError: # Python 2.x
PythonVersion = 2
from Tkinter import *
from tkFont import Font
from ttk import *
# Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancel
from tkMessageBox import *
# Usage:f=tkFileDialog.askopenfilename(initialdir='E:/Python')
# import tkFileDialog
# import tkSimpleDialog
else: # Python 3.x
PythonVersion = 3
from tkinter.font import Font
from tkinter.ttk import *
from tkinter.messagebox import *
# import tkinter.filedialog as tkFileDialog
# import tkinter.simpledialog as tkSimpleDialog #askstring()
#开始从config文件读取参数
conf = configparser.ConfigParser()
ini_path = 'config.ini'
conf.read(ini_path, encoding='utf-8')
if 'mteam' in conf.sections():
for i in conf.items('mteam'):
if 'username' in i:
mteam_username = i[1]
elif 'password' in i:
mteam_password = i[1]
elif 'login_url' in i:
mteam_login_url = i[1]
elif 'checkin_url' in i:
mteam_checkin_url = i[1]
elif 'loop' in i:
mteam_loop = i[1]
elif 'interval' in i:
mteam_interval = i[1]
elif 'last_login' in i:
mteam_last_login =i[0]
elif 'last_checkin' in i:
mteam_last_checkin =i[0]
else:
sys.exit()
if 'app' in conf.sections():
for i in conf.items('app'):
if 'default_frame' in i:
default_frame = i[1]
else:
sys.exit()
class Application_ui(Frame):
# 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。
def __init__(self, master=None):
Frame.__init__(self, master)
self.createWidgets()
self.master = master
def createWidgets(self):
self.top = self.master
self.style = Style()
#
self.style.configure('mteam_checkin_button.TButton', font=('微软雅黑', 10, "bold"))
self.mteam_checkin_button = Button(
self.top, text='mteam签到',
command=self.mteam_checkin_Cmd,
style='mteam_checkin_button.TButton'
)
self.mteam_checkin_button.place(relx=0.415, rely=0.019, relwidth=0.195, relheight=0.079)
self.style.configure('exit.TButton', font=('微软雅黑', 10, "bold"))
self.exit = Button(self.top, text='关闭', command=self.exit_Cmd, style='exit.TButton')
self.exit.place(relx=0.848, rely=0.019, relwidth=0.134, relheight=0.079)
self.style.configure('Line1.TSeparator', background='#000000')
self.Line1 = Separator(self.top, orient='horizontal', style='Line1.TSeparator')
self.Line1.place(relx=0., rely=0.115, relwidth=1, relheight=0.002)
#######################################################
#mteam签到的ui代码
self.style.configure('mteam_frame.TLabelframe', font=('微软雅黑', 10))
self.mteam_frame = Frame(self.top, style='mteam_frame.TLabelframe')
self.mteam_frame.place(relx=0., rely=0.127, relwidth=1, relheight=0.78)
self.style.configure('mteam_start.TButton', font=('微软雅黑', 10))
self.mteam_start = Button(self.mteam_frame, text='启动', command=self.mteam_start_Cmd,
style='mteam_start.TButton')
self.mteam_start.place(relx=0.015, rely=0., relwidth=0.134, relheight=0.10)
self.style.configure('mteam_stop.TButton', font=('微软雅黑', 10))
self.mteam_stop = Button(self.mteam_frame, text='停止', command=self.mteam_stop_Cmd, style='mteam_stop.TButton')
self.mteam_stop.place(relx=0.16, rely=0., relwidth=0.134, relheight=0.10)
self.style.configure('mteam_Checkbutton.TCheckbutton', font=('微软雅黑', 10))
if mteam_loop=='1':#根据config文件判断是否循环
self.mteam_checkVar = StringVar(value='1')
else:
self.mteam_checkVar = StringVar(value='0')
self.mteam_Checkbutton = Checkbutton(self.mteam_frame, text='循环', variable=self.mteam_checkVar,
style='mteam_Checkbutton.TCheckbutton')
self.mteam_Checkbutton.place(relx=0.3, rely=0., relwidth=0.134, relheight=0.1)
self.mteam_Checkbutton.bind('<Button-1>', self.mteam_checkbutton_Cmd)
self.style.configure('mteam_label.TLabel', anchor='w', font=('微软雅黑', 10))
self.mteam_label_text = StringVar()
self.mteam_label_text.set('最后签到:{}'.format(mteam_last_checkin))
self.mteam_label = Label(self.mteam_frame, textvariable=self.mteam_label_text, style='mteam_label.TLabel')
self.mteam_label.place(relx=0.45, rely=0., relwidth=0.534, relheight=0.1)
# self.style.configure('mteam_line.TSeparator', background='#000000')
# self.mteam_line = Separator(self.mteam_frame, orient='horizontal', style='mteam_line.TSeparator')
# self.mteam_line.place(relx=0.01, rely=0.08, relwidth=0.9, relheight=0.001)
self.mteam_text = Text(self.mteam_frame, font=('微软雅黑', 10))
self.mteam_text.place(relx=0.013, rely=0.11, relwidth=0.96, relheight=0.909)
self.mteam_text.insert(1.0, 'mteam\n')
self.mteam_text.insert(1.0,
'{}\n'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(time.time())))))
self.mteam_scrollbar = Scrollbar(self.mteam_text) # 把滚动条绑定到text
self.mteam_scrollbar.pack(side=RIGHT, fill=Y)
self.mteam_text['yscrollcommand'] = self.mteam_scrollbar.set
self.mteam_scrollbar['command'] = self.mteam_text.yview
############################################
self.style.configure('Line2.TSeparator', background='#000000')
self.Line2 = Separator(self.top, orient='horizontal', style='Line2.TSeparator')
self.Line2.place(relx=0., rely=0.92, relwidth=1, relheight=0.002) | ilaer/mteam_checkin | ui.py | ui.py | py | 6,048 | python | en | code | 20 | github-code | 36 | [
{
"api_name": "configparser.ConfigParser",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "time.strftime",
"line_number": 128,
"usage_type": "call"
},
{
"api_name": "time.localtime",
"line_number": 128,
"usage_type": "call"
},
{
"api_name": "time.time",
... |
33904308892 | import os
import argparse
# from icecream import ic
from misc_functions import read_name_funct
# from misc_functions import *
####################################################
def find_movie_files(movie_folders, iniID, finID, movie_path, imov_min=1, imov_max=9):
exist_movies = {}
rt_infofiles = False
# Check whether movie folders exist
for movie in movie_folders:
for iim in range(imov_min, imov_max + 1):
movID = movie + str(iim)
movreq = movie_path + movID
exist_movies[movreq] = {"found": os.path.isdir(movreq), "mov": movID}
# Check whether movie files exist, and determine min-max range of movies
IDmin = finID
IDmax = iniID
for movie_folder, movprops in exist_movies.items():
exists=movprops["found"]
if not exists:
continue
file_list = os.listdir(movie_folder)
found_movies = False
for imovie in range(iniID, finID + 1):
IDname = read_name_funct(imovie)
if os.path.isfile(movie_folder + "/info_" + IDname + ".txt"):
# Look for map files
map_files_exist = any(
f.endswith(".map") and (IDname in f) for f in file_list
)
if not map_files_exist:
print(
"Warning! Info files found for", IDname, "but no matching maps!"
)
IDmin = min(imovie, IDmin)
IDmax = max(imovie, IDmax)
found_movies = True
if os.path.isfile(movie_folder + "/rt_info_" + IDname + ".txt"):
rt_infofiles = True
if found_movies == False:
exists = False
print("Found movies for:")
for movname, movprops in exist_movies.items():
movfound = movprops["found"]
if movfound:
print(movname)
return exist_movies, IDmin, IDmax, rt_infofiles
####################################################
def read_system_arguments(arguments):
warn_frame = "Warning: you have deactivated the protection cut that leaves the last frame found untouched"
warn_clean = "Warning: you have activated the removal of .map files after their conversion to HDF5"
parser = argparse.ArgumentParser(description="TODO")
parser.add_argument(
"-ini",
"--iniID",
type=int,
default=1,
help="(Int) First movie ID to be converted (default=1)",
)
parser.add_argument(
"-fin",
"--finID",
type=int,
default=5000,
help="(Int) Last movie ID to be converted (default=5000)",
)
parser.add_argument(
"-pth",
"--path",
type=str,
default=".",
help="(String) Path to the simulation directory containing the movie folders (default='./')",
)
parser.add_argument(
"-cln",
"--clean",
dest="clean",
action="store_true",
default=False,
help="DO Clean .map files after succesfully converted to HDF5 (default=False)",
)
parser.add_argument(
"-noc",
"--no_clean",
dest="clean",
action="store_false",
default=False,
help="DO NOT clean .map files after succesfully converted to HDF5 (default=False)",
)
parser.add_argument(
"-sfe",
"--safe",
dest="safe",
action="store_true",
default=True,
help="DO skip the last found .map set of files to ensure no empty files are used (default=True)",
)
parser.add_argument(
"-nos",
"--no_safe",
dest="safe",
action="store_false",
default=True,
help="DO NOT skip the last found .map set of files. Warning: may interfere with ongoing sims (default=True)",
)
args = parser.parse_args()
# Final warnings and modifications to received arguments
if args.clean:
print(warn_clean)
if not args.safe:
print(warn_frame)
args.path = args.path + "/"
return args
####################################################
# Useful default initialisations and others
help_text = "Required parameters are:\n [1] initial movie ID to be requested\n [2] final movie ID to be requested\n [3] cleaning flag. Activate by providing 'clean'\n"
end_text = "combine_movies.py completed execution successfully :)"
####################################################
| MartinAlvarezSergio/ramses2hdf5_movies | combine_movies_functions.py | combine_movies_functions.py | py | 4,453 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.isdir",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "os.listdir",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "misc_functions.read_name_funct"... |
36337524182 | import pygame
from pygame.sprite import Sprite
class Fish(Sprite):
def __init__(self, oa_game):
super().__init__()
self.screen = oa_game.screen
self.settings = oa_game.settings
self.image = pygame.image.load('gameproject_final/images/fish.png')
self.image = pygame.transform.scale(self.image,(75,75))
self.rect = self.image.get_rect()
self.rect.x = self.rect.width
self.rect.y = self.rect.height
self.x = float(self.rect.x)
def update(self):
self.x += (self.settings.fish_speed *
self.settings.fleet_direction)
self.rect.x = self.x
def check_edges(self):
screen_rect = self.screen.get_rect()
if self.rect.right >= screen_rect.right or self.rect.left <= 0:
return True | sortzis/CIT228 | gameproject_final/fish.py | fish.py | py | 826 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.sprite.Sprite",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "pygame.image.load",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "pygame.image",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "pygame.transf... |
9766145404 | """
This script is used to compute neural network embeddings.
"""
import torch
import numpy as np
import sklearn
import pickle
import os
import json
import argparse
from pathlib import Path
from tqdm import tqdm
import librosa
from utils import extract_spectrogram
from models import AudioEncoder
def return_loaded_model(Model, checkpoint):
model = Model()
model.load_state_dict(torch.load(checkpoint, map_location=torch.device('cpu')))
model.eval()
return model
def extract_audio_embedding(model, filename):
with torch.no_grad():
try:
x = extract_spectrogram(filename)
x = scaler.transform(x)
x = torch.unsqueeze(torch.unsqueeze(torch.tensor(x), 0), 0).float()
embedding, embedding_d = model(x)
return embedding, embedding_d
except KeyboardInterrupt:
return
except Exception as e:
print(e, filename)
def extract_audio_embedding_chunks(model, filename):
with torch.no_grad():
try:
x = extract_spectrogram(filename)
x_chunks = librosa.util.frame(np.asfortranarray(x), frame_length=256, hop_length=256, axis=-1)
x_chunks = torch.tensor(x_chunks).permute(2, 0, 1)
x_chunks = torch.unsqueeze(x_chunks, 1)
embedding_chunks, embedding_d_chunks = model(x_chunks)
return embedding_chunks, embedding_d_chunks
except KeyboardInterrupt:
return
except Exception as e:
print(e, filename)
if __name__ == "__main__":
for MODEL_NAME in [
'minz_att_4h_w2v_128/audio_encoder_epoch_120',
]:
MODEL_PATH = f'./saved_models/{MODEL_NAME}.pt'
model = return_loaded_model(AudioEncoder, MODEL_PATH)
model.eval()
# GTZAN
p = Path('./data/GTZAN/genres')
filenames_gtzan = p.glob('**/*.wav')
# # US8K
# p = Path('./data/UrbanSound8K/audio')
# filenames_us8k = p.glob('**/*.wav')
#
# # NSynth
# p = Path('./data/nsynth/nsynth-train/audio_selected')
# filenames_nsynth_train = p.glob('*.wav')
# p = Path('./data/nsynth/nsynth-test/audio')
# filenames_nsynth_test = p.glob('*.wav')
#
# dataset_files = [filenames_gtzan, filenames_us8k, filenames_nsynth_train, filenames_nsynth_test]
# dataset_names = ['gtzan', 'us8k', 'nsynth/train', 'nsynth/test']
dataset_files = [filenames_gtzan]
dataset_names = ['gtzan']
for filenames, ds_name in zip(dataset_files, dataset_names):
print(f'\n {ds_name} {MODEL_NAME}')
for f in tqdm(filenames):
try:
with torch.no_grad():
model_name = MODEL_NAME.split('/')[0] + '_' + MODEL_NAME.split('_epoch_')[-1]
folder = f'./data/embeddings/{ds_name}/embeddings_{model_name}'
Path(folder).mkdir(parents=True, exist_ok=True)
embedding, embedding_d = extract_audio_embedding_chunks(model, str(f))
np.save(Path(folder, str(f.stem)+'.npy'), embedding)
except Exception as e:
print(e)
print('\n')
| andrebola/contrastive-mir-learning | encode.py | encode.py | py | 3,368 | python | en | code | 13 | github-code | 36 | [
{
"api_name": "torch.load",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "torch.device",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "torch.no_grad",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "utils.extract_spectrogram",
... |
42591855037 | from pyrailbaron.map.datamodel import Coordinate
from pyrailbaron.map.states import download_zip, extract_kml, simplify_coords
from typing import List
from pathlib import Path
from math import log, atan, cos, pi, tan, sqrt
FALSE_EASTING = 6200000
FALSE_NORTHING = 3000000
CENTRAL_MERIDIAN = -91.866667 * (pi/180)
STD_PARALLEL_1 = 49 * (pi/180)
STD_PARALLEL_2 = 77 * (pi/180)
LATITUDE_OF_ORIGIN = 63.390675 * (pi/180)
R_EARTH = 6378137
LCC_N = (
log(cos(STD_PARALLEL_1)/cos(STD_PARALLEL_2))
/ log(tan(pi/4 + STD_PARALLEL_2/2)/tan(pi/4 + STD_PARALLEL_1/2)))
LCC_F = (
cos(STD_PARALLEL_1)
* (tan(pi/4 + STD_PARALLEL_1/2)**LCC_N)
/ LCC_N )
def rho(lat: float) -> float:
return R_EARTH * LCC_F * ( tan(pi/4 + lat/2) ** (-LCC_N))
def lat_of_rho(r: float) -> float:
return 2*atan((r / (R_EARTH * LCC_F))**(-1/LCC_N)) - pi/2
RHO_AT_ORIGIN = rho(LATITUDE_OF_ORIGIN)
def invert_lcc(c: Coordinate) -> Coordinate:
x,y = c[0] - FALSE_EASTING, c[1] - FALSE_NORTHING
rho = sqrt(x**2 + (y - RHO_AT_ORIGIN)**2)
lat = lat_of_rho(rho)
lon = ( atan(x/(RHO_AT_ORIGIN-y)) / LCC_N ) + CENTRAL_MERIDIAN
lat, lon = lat * 180/pi, lon * 180/pi
return lat, lon
CANADA_URL = ('http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/2016/lpr_000b16g_e.zip')
MAX_LAT = 53
def get_canada_data(data_folder: Path | str) -> List[List[Coordinate]]:
data_path = Path(data_folder) / 'canada.gml'
download_zip(CANADA_URL, data_path, 'lpr_000b16g_e.gml')
root = extract_kml(data_path, root_tag='FeatureCollection')
borders: List[List[Coordinate]] = []
for border in root.findall('./featureMember//LinearRing/posList'):
coord_text = border.text or ''
coord_text_values = list(map(float, coord_text.split(' ')))
xy_coords: List[Coordinate] = [
(coord_text_values[2*i], coord_text_values[2*i+1])
for i in range(len(coord_text_values)//2)]
t_coords = list(map(invert_lcc, xy_coords))
coords = simplify_coords(t_coords)
if len(coords) > 20 and any(lat <= MAX_LAT for lat, _ in coords):
print(f'Adding CA border with {len(coords)} points')
cap_coords = [(min(lat, MAX_LAT), lon) for lat, lon in coords]
borders.append(cap_coords)
return borders | bmboucher/rail_baron | python/src/pyrailbaron/map/canada.py | canada.py | py | 2,330 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "math.pi",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "math.pi",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "math.pi",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "math.pi",
"line_number": 13,
"usage_t... |
17633338331 | # script part2c
# Sammy, Nikolai, Aron
# integral nummer (1), time_to_destination
import numpy as np
import roadster
import matplotlib.pyplot as plt
route_dist, route_speed = roadster.load_route('speed_elsa.npz')
delintervall = 25
l = [2**i for i in range(0,delintervall)]
trapets_list = []
for num in l:
a = roadster.time_to_destination(route_dist[-1], 'speed_elsa.npz', num)
trapets_list.append(a)
trap_list_dif = []
for i in range(len(trapets_list)-1):
trap_list_dif.append(abs(trapets_list[i+1]-trapets_list[i]))
x = np.array(l)
O = 1/(x**2) # hjälpinjer
P = 1/(x)
#plotta kurva i loglog
x_axis = range(1, len(x))
fig, ax = plt.subplots()
plt.loglog(x_axis ,trap_list_dif, label="Trapets integral 1")
ax.loglog(O, label="O(1/n^2)")
ax.loglog(P, label="O(1/n)")
plt.legend(loc="upper right")
ax.set(xlabel='Antal delinterval', ylabel='Integrationsfel', title='Konvergensstudie')
ax.grid()
fig.savefig("Konvergensstudie_2c.png")
plt.xlim(xmin=1)
plt.show()
| Nikkobrajj/roadster | script_part2c.py | script_part2c.py | py | 1,019 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "roadster.load_route",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "roadster.time_to_destination",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "matplotli... |
71765839143 | import matplotlib.pyplot as plt
import random
def roll_dice(number_of_dice: int, sides: int = 6) -> int:
"""Simulates dice throws."""
result = 0
for _ in range(number_of_dice):
result += random.randint(1, sides)
return result
def simulate_die_throws(number_of_rolls: int, amount_of_dice: int, sides:int = 6) -> dict:
"""Simulates dice throws for a certain number of times. Returns a dictionary of the distribution."""
results = {num: 0 for num in range(amount_of_dice, amount_of_dice * sides + 1)}
for _ in range(number_of_rolls):
results[roll_dice(amount_of_dice, sides)] += 1
return results
def get_probability(distribution: dict, total_throws: int) -> dict:
"""Returns a dictionary with probabilities of dice throw outcomes."""
output = distribution
for res, outcome in distribution.items():
output[res] = round((outcome / total_throws) * 100, 2)
return output
def main() -> None:
# Configuring throws
amount_of_dice = 2
sides_per_dice = 6
amount_of_throws = 100000
# Getting distribution
distribution = simulate_die_throws(amount_of_throws, amount_of_dice, sides_per_dice)
# Getting and printing probabilities
probability = get_probability(distribution, 100000)
print(probability)
# Plotting distribution
plt.bar(distribution.keys(), distribution.values())
plt.xticks([num for num in range(amount_of_dice, amount_of_dice * sides_per_dice + 1)])
plt.title(f'Distribution of dice throws (N={amount_of_throws})')
plt.xlabel('Result')
plt.ylabel('Times result occured')
plt.show()
if __name__ == '__main__':
main()
| Joey-JJ/dice_simulations | dice_simulation.py | dice_simulation.py | py | 1,664 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "random.randint",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.bar",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 40,
"usage_type": "name"
},
{
"api_name": "matplotlib.pypl... |
25412118768 | from typing import Iterable, Tuple
from ..shared.more_itertools import flat_map, count
from ..shared.solver import Solver
"""[summary]
2 thoughts on performance:
1. This *enumerates* paths, which isn't necessary.
All we need to do is count them, so just increment
a number when you get to 16,16, and forget about
holding on to the tail.
2. Adding threads should be trivial, especially
after changing the search to depth-first.
Returns:
[type]: [description]
Yields:
[type]: [description]
"""
Position = Tuple[int,int]
class Path():
head:Position
tail: 'Path'
def __init__(self, end:Position, rest:'Path' = None):
self.head = end
self.tail = rest
def to_positions(self) -> Iterable[Position]:
yield self.head
if self.tail:
yield from self.tail.to_positions()
def append(self, p:Position) -> 'Path':
return Path(p, self)
def __str__(self):
ps = list(self.to_positions())
ps.reverse()
return str(ps)
@classmethod
def zero(cls) -> 'Path':
return Path((0,0))
class Lattice():
height:int
width:int
def __init__(self,width, height):
self.width=width
self.height=height
def successor_paths(self, current:Path) -> Iterable[Path]:
if current.head[0] < self.width:
yield current.append((current.head[0] + 1, current.head[1]))
if current.head[1] < self.height:
yield current.append((current.head[0], current.head[1] + 1))
def paths(self) -> Iterable[Path]:
partials = [Path.zero()]
for _ in range(self.height + self.width):
partials = flat_map(self.successor_paths, partials)
return partials
def _solve(print = print):
side = 15
l = Lattice(side,side)
path_count = count(l.paths())
print(f"Count of paths through a {side} lattice is: {path_count}")
print('This approach doesn''t scale.')
return False
description = '''Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
'''
solver = Solver(15,
'Lattice paths',
description,
_solve
)
| bathcat/pyOiler | src/pyoiler/problems/euler015.py | euler015.py | py | 2,357 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "typing.Tuple",
"line_number": 21,
"usage_type": "name"
},
{
"api_name": "typing.Iterable",
"line_number": 30,
"usage_type": "name"
},
{
"api_name": "typing.Iterable",
"line_number": 54,
"usage_type": "name"
},
{
"api_name": "shared.more_itertools.fl... |
17353771853 | # Cam definition
from collections import namedtuple
_Cam = namedtuple("_Cam", field_names = ["xpos", "ypos", "steps", "offset", "signal_name", "horizontal", "reverse_direction", "bump_height", "follower"])
class Cam(_Cam):
def __new__(_cls, xpos, ypos, steps, offset, signal_name, horizontal=False, reverse_direction=False, bump_height=3, follower=True):
'Create new instance of Point(x, y)'
return _Cam.__new__(_cls, xpos, ypos, steps, offset, signal_name, horizontal, reverse_direction, bump_height, follower)
instruction_ready_point = 0.50 # Instruction decoder should be set up, ready for cams to use
cams = [
Cam(300, 200, [(0.0,0.02)], 1, "PC INJECTOR"),
Cam(150,300, [(0.05,0.07), (0.32, 0.06)], 0, "MEMORY DECODER INPUT HOLDOFF"),
Cam(-400, 120, [(0.02, 0.07), (0.31,0.1), (0.64,0.1), (0.95,0.03)], -1, "MEMORY RETURN", horizontal=True),
Cam(-300,100, [(0.03,0.11), (0.17,0.05), (0.31,0.1), (0.48,0.05), (0.65,0.1), (0.96,0.03)], -1, "MEMORY DECODER OUTPUT HOLDOFF", horizontal=True),
# Cam 8: Sender eject.
# Note timing hazard. We cannot raise selector and eject until
# regenerated data is written back, so we delay for a few
# seconds here. If gravity or timing changes, expect this to
# break.
Cam(600, -430, [(0.02, 0.04), (0.30,0.04)], 0, "SENDER EJECT", horizontal=True),
# Cam 5: Regenerator 1
Cam(800, 100, [(0.24,0.05), (0.56,0.05)], 0, "UPPER REGEN", horizontal=True),
# Cam 6: Split to instruction register
Cam(400,-120, [(0.18, 0.12)], 2, "TO INSTRUCTION REGISTER", horizontal=True, reverse_direction=True, bump_height=4),
# Cam 7: Instruction selector holdoff (vertical)
Cam(320, 300, [(0.04, 0.2), (0.32,0.06)], 0, "INSTRUCTION OUTPUT HOLDOFF"),
# Cam 9(?): LDN Trigger.
Cam(850, 0, [(instruction_ready_point,0.05)], 0, "LDN TRIGGER", horizontal=True, reverse_direction=False, bump_height=4),
# Cam 11(?): Instruction follower holdoff (horizontal)
Cam(1000, 100, [(0.02, 0.2), (0.15,0.25)], -1, "IP OUTPUT HOLDOFF", horizontal=True),
# Cam 12: Fires main memory injector, injecting all 8 columns. If STO is on, this diverts to the subtractor reader. If not, it
# will fall through the memory and be discarded.
Cam(0, 300, [(0.62,0.02)], 1, "MAIN INJECTOR"),
# Cam 13: Divert to subtractor reader on STO.
# Also diverts the regenerator output on STO; we must separately discard that.
Cam(1000, 0, [(0.49,0.2)], 2, "STO TRIGGER", horizontal=True, reverse_direction=True, bump_height=3.5),
# Cam 14: Divert to instruction pointer, on JRP (and JMP via the same lever).
# Cam pattern *nearly* identical to #13, please adjust to see if it works
Cam(1100, 0, [(0.5,0.2)], 2, "JRP TRIGGER", horizontal=True, reverse_direction=True),
# Cam 15: Discard of any data falling through the memory just after main inject
Cam(-500,-150, [(0.67,0.07)], 2, "DISCARD", reverse_direction=True, horizontal=True),
# Cam 16: Fires bottom regenerator (usually empty, unless STO is on)
Cam(-500,-300, [(0.87,0.02)], 0, "LOWER REGEN", horizontal=True),
# Cam 17: Reset PC on JMP
Cam(1230, 0, [(0.5,0.1)], 2, "JMP TRIGGER", horizontal=True, reverse_direction=True),
# Cam 18: Runs CMP.
# Cam pattern is identical to #9.
Cam(900,200, [(instruction_ready_point,0.05)], -1, "CMP TRIGGER", horizontal=True, reverse_direction=False),
# Cam 19: Inc PC.
Cam(-95,-450, [(0.85,0.05)], 0, "INC PC", horizontal=True, reverse_direction=False, bump_height=5, follower=False)
]
| jmacarthur/box2d-ssem | cams.py | cams.py | py | 3,563 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.namedtuple",
"line_number": 5,
"usage_type": "call"
}
] |
72555949543 | """django_sandbox URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^activity_log/', include('activity_log.urls', namespace='activity_log')),
url(r'^caption_maker/', include('caption_maker.urls', namespace='caption_maker')),
url(r'^admin/', admin.site.urls),
url(r'^numbers_quiz$', views.numbers_quiz),
url(r'nibuzhidaodeshi$', views.nibuzhidaodeshi),
url(r'^login$', views.login_user),
url(r'^logout$', views.logout_user),
url(r'^registration/', views.registration),
url(r'^$', views.home),
]
urlpatterns += staticfiles_urlpatterns()
| tedlano/django-sandbox | django_sandbox/urls.py | urls.py | py | 1,394 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "django.conf.urls.url",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "django.conf.urls.include",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "django.conf.urls.url",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "dj... |
69933322346 | #!/usr/bin/python
import cv2, time, argparse
from ptpython.repl import embed
parser = argparse.ArgumentParser(description='OpenCV Face Recognition')
parser.add_argument('-interactive', action='store_true', help='Open a console terminal for evaluation')
parser.add_argument('input', help='Input video file to process')
args = parser.parse_args()
print(args)
import mediapipe as mp
cam = cv2.VideoCapture(args.input)
pTime = time.time()
mpFaceDetection = mp.solutions.face_detection
mpDraw = mp.solutions.drawing_utils
fd = mpFaceDetection.FaceDetection()
while True:
rv, img = cam.read()
if not rv: break
hT, wT, cT = img.shape
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = fd.process(imgRGB)
if args.interactive: embed(globals(), locals())
elif results.detections:
for i, detection in enumerate(results.detections):
score = int(100*detection.score[0]) if len(detection.score) > 0 else 0
bbox = detection.location_data.relative_bounding_box
w, h = int(bbox.width*wT), int(bbox.height*hT)
x, y = int(bbox.xmin*wT), int(bbox.ymin*hT)
mpDraw.draw_detection(img, detection)
cv2.putText(img, f'[{i+1}] {score}%',
(x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(255, 0, 255),
2)
cTime = time.time()
fps = 1/(cTime - pTime)
pTime = cTime
cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
cv2.imshow('Image', img)
if args.interactive:
cv2.waitKey(1)
break
else:
if cv2.waitKey(1) == ord('q'): break
| jaysridhar/learn-opencv | face-detection/face-detect.py | face-detect.py | py | 1,773 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "cv2.VideoCapture",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "mediapipe.solutions... |
7044110193 | import imgaug as ia
import argparse
import imgaug.augmenters as iaa
from shapely.geometry import Polygon
from cvat import CvatDataset
import shapely
import numpy as np
from urllib.request import urlopen
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from PIL import Image, ImageDraw
import random
import garbage as g
from tqdm import tqdm
import albumentations as albu
import numpy as np
import cv2
import png
import os
main_folder = "/media/andreizoltan/DATA/Ice_Vision/dataset/background/only1and5/"
clear_folder = "/media/andreizoltan/DATA/Ice_Vision/dataset/background/clear-1-5/"
num = 0
def save_image(data, folder, name, image_name) :
image_name = image_name.split('.')[0]
im = Image.fromarray(data)
global num
folder_a = args.output_folder
print(folder_a+folder+"/"+image_name + "_" + str(num).zfill(4)+name)
im.save(folder_a+folder+"/"+image_name + "_" + str(num).zfill(4)+name)
if folder == "clear":
num+= 1
############################################################################################################
def label_image(label):
return "car"
def points_please(input_file):
ds = CvatDataset()
ds.load(input_file)
polygons = list()
all_polygons = list()
for image_id in ds.get_image_ids():
for polygon in ds.get_polygons(image_id):
label = label_image(polygon["label"].replace("_", "."))
polygons += [polygon["points"]]
for i in range(len(polygons)):
for j in range(len(polygons[i])):
polygons[i][j] = tuple(polygons[i][j])
all_polygons.append(polygons)
polygons = list()
return all_polygons
ww = 1200
def masks_please(points, width, height):
img = Image.new('L', (width, height), 0)
for i in range(len(points)):
f = list()
for j in range(len(points[i])):
f.append(tuple(points[i][j]))
ImageDraw.Draw(img).polygon(f, outline=255, fill=255)
mask = np.array(img)
return mask
#======================================================================================
def pol_to_dots(poly):
l = list()
x, y = poly.exterior.coords.xy
coord = [x, y]
for i in range(len(coord[0])):
xy = [coord[0][i], coord[1][i]]
dots = tuple(xy)
l.append(dots)
return l
def checked(pol):
global ww
pol = Polygon(pol)
p1 = Polygon([(0, 0), (0, 1200), (1200, 1200), (1200, 0)])
p1 = p1.intersection(pol)
if type(p1) == shapely.geometry.multipolygon.MultiPolygon:
return 0
if p1.is_empty == True:
return 0
else: return pol_to_dots(p1)
def augment_please(s_images, s_images_l, masks, points, image_name):
batches = 40
global ww
sometimes = lambda aug: iaa.Sometimes(0.5, aug)
full_list = list()
for i in range(batches):
aug = iaa.Sequential([
iaa.Affine(rotate=(-10, 10)),
iaa.CropToFixedSize(width=ww, height=ww),
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.10)))
])
aug = aug.to_deterministic()
batch_aug = aug.augment(
images=s_images, polygons=points,
return_batch=True)
batch_aug_l = aug.augment(
images=s_images_l, polygons=points,
return_batch=True)
batch_aug_masks = aug.augment(
images=masks, polygons=points,
return_batch=True)
new_images = batch_aug.images_aug
new_images_l = batch_aug_l.images_aug
new_masks = batch_aug_masks.images_aug
new_images_l = np.asarray(new_images_l)
new_images = np.asarray(new_images)
for j in range(len(new_images)):
save_image(new_images[j], "cars", ".jpg", image_name)
save_image(new_masks[j], "masks", ".bmp", image_name)
save_image(new_images_l[j], "clear", ".jpg", image_name)
new_list = list()
new_polygo = batch_aug.polygons_aug
new_polygo = np.asarray(new_polygo)
for p in new_polygo:
for polygon in p:
if checked(polygon) == 0:
continue
else:
new_list.append(checked(polygon))
full_list.append(new_list)
new_list = list()
ww = 1200
return full_list
def get_polygons(points):
full_list = list()
batch = 5
for i, image_name in enumerate(os.listdir(args.initial_folder)):
image = mpimg.imread(args.initial_folder+image_name)
image_double = mpimg.imread(args.clear_folder+image_name)
width = len(image[0])
height = len(image)
print(i, image_name)
mask = masks_please(points[i], width, height)
s_images = [image] * batch
s_images_l = [image_double] * batch
masks = [mask] * batch
points_k = [points[i]] * batch
full = augment_please(s_images, s_images_l, masks, points_k, image_name)
full_list.extend(full)
full_list = np.asarray(full_list)
POINTSS = full_list
return POINTSS
def build_parser():
parser = argparse.ArgumentParser("Add polygons according to sign class")
parser.add_argument(
"--input-file",
type=str
)
parser.add_argument(
"--output-file",
type=str
)
parser.add_argument(
"--initial-folder",
type=str
)
parser.add_argument(
"--clear-folder",
type=str
)
parser.add_argument(
"--output-folder",
type=str
)
return parser
def dump(polygons, output_file):
ds = CvatDataset()
image_id = 0
for POINTS in polygons:
ds.add_image(image_id)
for points in POINTS:
ds.add_polygon(
image_id=image_id,
points=points,
label="car",
occluded=0)
image_id += 1
print(image_id)
ds.dump(output_file)
def main(args):
points = points_please(args.input_file)
polygons = get_polygons(points)
dump(polygons, args.output_file)
if __name__ == "__main__":
parser = build_parser()
args = parser.parse_args()
main(args)
| cds-mipt/cds-dtld-utils | data_augmentation.py | data_augmentation.py | py | 6,262 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "PIL.Image.fromarray",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 28,
"usage_type": "name"
},
{
"api_name": "cvat.CvatDataset",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "PIL.Image.new",
"l... |
72673665383 | import numpy as np
from itertools import combinations
from TransitionToClosedView import *
def quick_check_zero_det(matrix: np.ndarray):
zero_line = True
for i in range(matrix.shape[1]):
for j in range(matrix.shape[0]):
if matrix.item(i, j) != 0:
zero_line = False
break
if zero_line:
return 0
zero_line = True
return 1
def make_simplex_task(transport_cost: list[list], storage: list, destination: list):
vars_count = len(storage) * len(destination)
dest_count = len(destination)
storage_count = len(storage)
if vars_count == 0:
print("wrong input data")
return
A = []
b = []
c = []
for i in range(len(storage)):
A.append(i * dest_count * [0] + [1] * dest_count + [0] * (vars_count - (i + 1) * dest_count))
b.append(storage[i])
for j in range(len(destination)):
c.append(transport_cost[i][j])
for i in range(len(destination)):
A.append(storage_count * (i * [0] + [1] + (dest_count - i - 1) * [0]))
b.append(destination[i])
return A, b, c
def find_all_matrices(A, M, N):
"""
функция для перебора наборов из N переменных по M ненулевых. Возвращает соответствующие тамим наборам вектор матриц
:param A: матрица ограничений в каноническом виде
:param M: количество строк в матрице A
:param N: количество столбцов в матрице A
:return matrices: вектор невырожденных матриц составленных из столбцов A
:return indexes: вектор с наборами индексов. В каждом наборе индексы соответствующих им столбцов расположены в том
же порядке, что и в матрице из вектора matrices
"""
start_matrix = np.matrix(A)
index_set = [i for i in range(N)]
matrices = []
indexes = []
for i in combinations(index_set, M):
g = i
new_matrix = start_matrix[:, i]
if quick_check_zero_det(new_matrix):
det = abs(np.linalg.det(new_matrix))
if det > 1e-7:
matrices.append(new_matrix)
indexes.append(i)
return matrices, indexes
def find_all_vectors(A, b, M, N):
"""
функция для поиска всех опорных векторов
:param A: матрица коэффициентов органичений в каноническом виде
:param b: вектор правой части ограничений в каноническом виде
:param M: количество строк в матрице A
:param N: количество столбцов в матрице A
:return: массив всех опорных векторов
"""
vectors = []
if M >= N:
return []
matrices, indexes = find_all_matrices(A, M, N)
for i in range(len(indexes)):
solution = np.linalg.solve(matrices[i], b)
solution[abs(solution) < 1e-15] = 0
if (len(solution[solution < 0]) != 0):
continue
if (len(solution[solution > 1e+15]) != 0):
continue
vector = [0 for i in range(N)]
for j in range(len(indexes[i])):
vector[indexes[i][j]] = solution[j]
vectors.append(vector)
return vectors
def enum_method(A, b, c, M, N, max=False):
"""
Метод перебора крайних точек
:param M: количесво ограничений
:param N: количество переменных
:param A: матрица коэффициентов ограничений
:param b: правый вектор ограничений
:param c: вектор коэффициентов целевой функции
:param max: True если нужно решать задачу максимизации вместо минимизации
:return: опорный вектор при котором достигается оптимальное решение
"""
mult = -1 if max else 1
if max:
for i in range(len(c)):
c[i] *= mult
f = open('EnumMethod.txt', 'w')
vectors = find_all_vectors(A, b, M, N)
if len(vectors) == 0:
return []
best_vector = vectors[0]
min = np.dot(best_vector, c)
i = 1
min_i = 1
vectors_min = []
for tmp in vectors:
current_val = np.dot(tmp, c)
f.write("step " + str(i) + ":\n")
f.writelines(map(lambda x: str(x) + ' ', np.matrix(tmp).tolist()[0]))
f.write("\nf(X_" + str(i) + ") =" + str(current_val) + '\n')
if current_val < min:
min = current_val
best_vector = tmp
min_i = i
vectors_min.clear()
vectors_min.append((np.array(best_vector) * mult).tolist())
elif current_val == min:
vectors_min.append((np.array(tmp) * mult).tolist())
i += 1
f.write("\nbest vector on step " + str(min_i) + ":\n")
f.writelines(
map(lambda x: str(x) + ' ', np.matrix(best_vector).tolist()[0]))
f.write("\n\nsolution:")
f.writelines(map(lambda y: str(y) + ' ', best_vector))
f.write("\nf(X) = " + str(np.dot(c, best_vector)))
mtx = np.array(vectors_min)
f.write("\nList of found optimal solutions:\n")
unique = np.unique(mtx, axis=0)
for i in unique:
line = i.tolist()
f.write(str(line) + '\n')
f.close()
return (np.array(best_vector) * mult).tolist(), min
def solve_enum(transport_cost: list[list], storage: list, destination: list):
"""
функция для решения транспортной задачи перебором опорных точек
:param transport_cost: матрица стоимостей перемещений
:param storage: вектор с количеством хранящегося на складах товара
:param destination: вектор с количеством необходимого в точках выгрузки товара
:return result_matrix: матрица оптимальных перевозок
:return best_value: сумма стоимостей оптимальных перевозок
"""
A, b, c = make_simplex_task(transport_cost, storage, destination)
# без удаления последней строки не работает
A.pop(len(A) - 1)
b.pop(len(b) - 1)
x, best_value = enum_method(A, b, c, len(A), len(A[0]))
result_matrix = np.reshape(x, (len(transport_cost), len(transport_cost[0]))).tolist()
return result_matrix, best_value
if __name__ == '__main__':
storagel = [16, 5, 15, 9]
destinationl = [12, 12, 11, 8, 11]
transport_costl = [
[3, 2, 7, 11, 11],
[2, 4, 5, 14, 8],
[9, 4, 7, 15, 11],
[2, 5, 1, 5, 3]
]
print(solve_enum(transport_costl, storagel, destinationl))
| Hembos/optimization-method | Transport task/EnumerationMethod.py | EnumerationMethod.py | py | 7,249 | python | ru | code | 0 | github-code | 36 | [
{
"api_name": "numpy.ndarray",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "numpy.matrix",
"line_number": 51,
"usage_type": "call"
},
{
"api_name": "itertools.combinations",
"line_number": 56,
"usage_type": "call"
},
{
"api_name": "numpy.linalg.de... |
27051867513 | from django.urls import path, include
from django.utils.translation import gettext_lazy as _
from .views import *
app_name = 'buildings'
urlpatterns = [
path('', BuildingListView.as_view(), name = 'building_list'),
path(_('add/'), BuildingCreateView.as_view(), name = 'building_create'),
path(_('<slug>/'), BuildingRedirectView.as_view(), name = 'building_slug'),
path(_('<slug>/login/'), BuildingLoginView.as_view(),
name = 'building_login'),
path(_('<slug>/change/'), BuildingUpdateView.as_view(),
name = 'building_change'),
path(_('<slug>/delete/'), BuildingDeleteView.as_view(),
name = 'building_delete'),
path(_('<slug>/set/add/'), PlanSetCreateView.as_view(),
name = 'planset_create'),
path('<slug:build_slug>/set/<slug:set_slug>/',
BuildingDetailView.as_view(), name = 'building_detail'),
path(_('<slug:build_slug>/set/<slug:set_slug>/change/'),
PlanSetUpdateView.as_view(), name = 'planset_change'),
path(_('<slug:build_slug>/set/<slug:set_slug>/delete/'),
PlanSetDeleteView.as_view(), name = 'planset_delete'),
path(_('<slug>/plan/add/'), PlanCreateView.as_view(),
name = 'plan_create'),
path(_('<slug:build_slug>/plan/<slug:plan_slug>/'),
PlanDetailView.as_view(), name = 'plan_detail'),
path(_('<slug:build_slug>/plan/<slug:plan_slug>/change/'),
PlanUpdateView.as_view(), name = 'plan_change'),
path(_('<slug:build_slug>/plan/<slug:plan_slug>/delete/'),
PlanDeleteView.as_view(), name = 'plan_delete'),
path(_('<slug>/station/add/'), PhotoStationCreateView.as_view(),
name = 'station_create'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/'),
StationImageListCreateView.as_view(), name = 'station_detail'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/change/'),
PhotoStationUpdateView.as_view(), name = 'station_change'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/delete/'),
PhotoStationDeleteView.as_view(), name = 'station_delete'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/3d/'),
PhotoStation3dView.as_view(), name = 'station_3d'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/image/<pk>/change'),
StationImageUpdateView.as_view(), name = 'image_change'),
path(_('<slug:build_slug>/station/<slug:stat_slug>/image/<pk>/delete'),
StationImageDeleteView.as_view(), name = 'image_delete'),
path(_('<slug>/stations/<int:year>/<int:month>/<int:day>/'),
StationImageDayArchiveView.as_view(), name = 'image_day'),
path(_('<slug>/stations/all-days/'),
StationImageDayArchiveListView.as_view(), name = 'image_day_all'),
path(_('<slug>/family/add/'), FamilyListCreateView.as_view(),
name = 'family_list_create'),
path(_('<slug:build_slug>/family/<slug:fam_slug>/change/'),
FamilyUpdateView.as_view(), name = 'family_change'),
path(_('<slug:build_slug>/family/<slug:fam_slug>/delete/'),
FamilyDeleteView.as_view(), name = 'family_delete'),
path(_('<slug:build_slug>/family/<slug:fam_slug>/elements/'),
ElementByFamilyListView.as_view(), name = 'elements_by_family'),
path(_('<slug>/element/add/'), ElementCreateView.as_view(),
name = 'element_create'),
path(_('<slug>/element/<pk>/change/'), ElementUpdateView.as_view(),
name = 'element_change'),
path(_('<slug>/element/<pk>/delete/'), ElementDeleteView.as_view(),
name = 'element_delete'),
path(_('<slug>/element/download/'), building_element_download,
name = 'element_download'),
path(_('<slug:build_slug>/journal/<int:year>/<int:month>/<int:day>/<jour_slug>/'),
JournalDetailView.as_view(), name = 'journal_detail'),
path(_('<slug:slug>/journal/all/'),
JournalListView.as_view(), name = 'journal_list'),
]
| andywar65/buildings | urls.py | urls.py | py | 3,877 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "django.urls.path",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "django.utils.translation.gettext_lazy",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "... |
74100918822 | # Authors: Chao Li, Handing Wang, Jun Zhang, Wen Yao, Tingsong Jiang
# Xidian University, China
# Defense Innovation Institute, Chinese Academy of Military Science, China
# EMAIL: lichaoedu@126.com, hdwang@xidian.edu.cn
# DATE: February 2022
# ------------------------------------------------------------------------
# This code is part of the program that produces the results in the following paper:
#
# Chao Li, Handing Wang, Jun Zhang, Wen Yao, Tingsong Jiang, An Approximated Gradient Sign Method Using Differential Evolution For Black-box Adversarial Attack, IEEE Transactions on Evolutionary Computation, 2022.
#
# You are free to use it for non-commercial purposes. However, we do not offer any forms of guanrantee or warranty associated with the code. We would appreciate your acknowledgement.
# ------------------------------------------------------------------------
import random
import torch
import copy
import numpy as np
from VGG16_Model import vgg
population_size = 50
generations = 100
F = 0.5
CR = 0.6
xmin = -1
xmax = 1
eps = 0.1
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = vgg().to(device)
model.load_state_dict(torch.load(r'C:\Users\LC\Desktop\AGSM-DE\AGSM-DE-PythonCode\vgg16_params.pkl', map_location=torch.device('cuda')))
model.eval()
def init_population(num):
population = np.zeros((population_size, num))
for i in range(population_size):
for j in range(num):
rand_value = random.random()
population[i, j] = xmin + rand_value * (xmax-xmin)
return population
def calculate_fitness(taget_image, adversarial_images, population, num, second_label, first_labels):
second_label = second_label
taget_image = taget_image.cpu().detach().numpy()
fitness = []
function_value = np.zeros(population_size)
sign_images = np.zeros((population_size, 3, 32, 32))
for i in range(population_size):
for j in range (0, num):
sign_images[i, :, :, :] += population[i, j] * (adversarial_images[j, :, :, :] - taget_image[0, :, :, :])
sign_images[i, :, :, :] = np.sign(sign_images[i, :, :, :])
for b in range(population_size):
attack_image = taget_image + eps * sign_images[b, :, :, :]
attack_image = torch.from_numpy(attack_image)
attack_image = attack_image.to(device)
outputs = model(attack_image.float())
outputs = outputs.cpu().detach().numpy()
d = outputs[0, first_labels]
c = np.min(outputs)
outputs.itemset(first_labels, c)
g = np.max(outputs)
function_value[b] = d-g
fitness.append(function_value[b])
return fitness
def mutation(subpopulation, optimization_dim):
Mpopulation=np.zeros((population_size, optimization_dim))
for i in range(population_size):
r1 = r2 = r3 = 0
while r1 == i or r2 == i or r3 == i or r2 == r1 or r3 == r1 or r3 == r2:
r1 = random.randint(0, population_size - 1)
r2 = random.randint(0, population_size - 1)
r3 = random.randint(0, population_size - 1)
Mpopulation[i] = subpopulation[r1] + F * (subpopulation[r2] - subpopulation[r3])
for j in range(0,optimization_dim):
if xmin <= Mpopulation[i, j] <= xmax:
Mpopulation[i, j] = Mpopulation[i, j]
else:
Mpopulation[i, j] = xmin + random.random() * (xmax - xmin)
return Mpopulation
def crossover(Mpopulation, subpopulation, Spopulation, index, optimization_dim):
Cpopulation = np.zeros((population_size, optimization_dim))
for i in range(population_size):
for j in range(0, optimization_dim):
rand_j = random.randint(0, optimization_dim - 1)
rand_float = random.random()
if rand_float <= CR or rand_j == j:
Cpopulation[i, j] = Mpopulation[i, j]
else:
Cpopulation[i, j] = subpopulation[i, j]
Spopulation[0:population_size, index] = Cpopulation
return Spopulation
def selection(taget_image, adversarial_images, Spopulation, population,num, second_label, first_labels, pfitness):
Cfitness = calculate_fitness(taget_image, adversarial_images, Spopulation, num, second_label, first_labels)
for i in range(population_size):
if Cfitness[i] < pfitness[i]:
population[i] = Spopulation[i]
pfitness[i] = Cfitness[i]
else:
population[i] = population[i]
pfitness[i] = pfitness[i]
return population, pfitness
def LDE(taget_image, adversarial_images, second_label, first_labels):
num = np.size(adversarial_images, 0)
population = init_population(num)
fitness = calculate_fitness(taget_image, adversarial_images, population, num, second_label, first_labels)
Best_indi_index = np.argmin(fitness)
Best_indi = population[Best_indi_index, :]
optimization_dim = 10
if num <= optimization_dim:
optimization_dim = num
index = random.sample(range(0, num), optimization_dim)
else:
index = random.sample(range(0, num), optimization_dim)
for step in range(generations):
if min(fitness) < 0:
break
Spopulation = copy.deepcopy(population)
subpopulation = copy.deepcopy(population[0:population_size, index])
Mpopulation = mutation(subpopulation, optimization_dim)
Spopulation = crossover(Mpopulation, subpopulation, Spopulation, index, optimization_dim)
population, fitness = selection(taget_image, adversarial_images, Spopulation, population, num, second_label, first_labels, fitness)
Best_indi_index = np.argmin(fitness)
Best_indi = population[Best_indi_index, :]
index = random.sample(range(0, num), optimization_dim)
attack_sign = np.zeros((1, 3, 32, 32))
taget_image = taget_image.cpu().detach().numpy()
for j in range(0, num):
attack_sign[0, :, :, :] += minindividual[j] * (adversarial_images[j, :, :, :] - taget_image[0, :, :, :])
attack_direction = np.sign(attack_sign)
final_image = taget_image + eps * attack_direction
final_image = torch.from_numpy(final_image)
final_image = final_image.float()
final_image[0, 0, :, :] = torch.clamp(final_image[0, 0, :, :], -1, 1)
final_image[0, 1, :, :] = torch.clamp(final_image[0, 1, :, :], -1, 1)
final_image[0, 2, :, :] = torch.clamp(final_image[0, 2, :, :], -1, 1)
return final_image
| HandingWangXDGroup/AGSM-DE | LSS_DE.py | LSS_DE.py | py | 6,576 | python | en | code | 9 | github-code | 36 | [
{
"api_name": "torch.device",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "torch.cuda.is_available",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "torch.cuda",
"line_number": 29,
"usage_type": "attribute"
},
{
"api_name": "VGG16_Model.vgg"... |
847509581 | #Python Image Library (PIL)
#Installation:
#Open terminal
#pip install pillow
from PIL import Image
#Open an image
mem_img = Image.open('d:/images/kids.jpg')
#fetch its attributes
#print(mem_img.size) # size of the image as a (w,h) tuple
#print(mem_img.format) #format: JPEG, PNG, ...
#print(mem_img.mode) #Color model
#Create a thumbnail
#mem_img.thumbnail((128,128)) #thumbnail will be of size near to tuple(w,h) maintaining the aspect ratio.
#mem_img.save('d:/temp/kids_thumbnail.jpg')
#Crop a region
#box = (120,950,900,2400) #x1,y1,x2,y2
#region = mem_img.crop(box)
#region.save('d:/temp/vikas.jpg')
#Rolling
w,h = mem_img.size #size of the image (5000,3954)
roll_width = w//4 #25% roll
box_1 = (0,0,roll_width,h) #(0,0,1250,3954) (x1,y1, x2,y2)
box_2 = (roll_width,0,w,h) #(1250,3950,5000,3954) (x1,y1,x2,y2)
region_1 = mem_img.crop(box_1)
region_2 = mem_img.crop(box_2)
new_box1 = (0,0, region_2.size[0], region_2.size[1])
new_box2 = (region_2.size[0],0, w,h)
mem_img.paste(region_2, new_box1)
mem_img.paste(region_1, new_box2)
mem_img.save('d:/temp/kids_rolling.jpg') | dheeraj120501/Lets-Code | 02-Languages/Python/11-PIL/handson_pil_1.py | handson_pil_1.py | py | 1,087 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "PIL.Image.open",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 10,
"usage_type": "name"
}
] |
21911933808 | #!/usr/bin/env python3
import re
import os
from os.path import join, isfile
import sys
import argparse
import requests
ENCLAVE_ENDPOINT = ""
class S3FileReader(object):
"""
Reads P3A measurements (as they are stored in the S3 bucket) from disk and
replays them to our live Nitro enclave. This object must act as an
iterator.
"""
def __init__(self, directory):
self.dir = directory
self.files = []
self.cache = []
def __iter__(self):
self.files = [join(self.dir, f) for f in os.listdir(self.dir) if
isfile(join(self.dir, f))]
self.files = sorted(self.files, reverse=True)
return self
def __next__(self):
if len(self.cache) > 0:
return self.cache.pop(0)
try:
file_content = self._read_file(self.files.pop())
except IndexError:
raise StopIteration
measurements = self._extract_p3a_measurement(file_content)
if len(measurements) > 1:
self.cache += measurements
return self.cache.pop(0)
else:
return measurements[0]
def _read_file(self, filename):
with open(filename, "r") as fd:
return fd.readlines()
def _extract_p3a_measurement(self, file_content):
measurements = []
# There may be multiple measurements per file.
for line in file_content:
m = re.search("'([^']+)'", file_content[0])
if m:
# print(m.group(1))
measurements.append(m.group(1))
return measurements
def replay_p3a_data(directory):
measurements = S3FileReader(directory)
for m in measurements:
# Add "verify=False" if the enclave is running in testing mode, and
# using self-signed certificates.
requests.post(ENCLAVE_ENDPOINT, data="[%s]" % m)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: %s DIRECTORY" % sys.argv[0], file=sys.stderr)
sys.exit(1)
replay_p3a_data(sys.argv[1])
| brave-experiments/p3a-shuffler | scripts/replay-p3a-data.py | replay-p3a-data.py | py | 2,065 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "os.listdir",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "os.path.isfile",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line_numbe... |
32220783153 | from itertools import chain
def matches_gen(data):
yield {
'team-slug' : data['event']['homeTeam']['slug'],
'eventid': data['event']['id'],
}
yield {
'team-slug' : data['event']['awayTeam']['slug'],
'eventid': data['event']['id'],
}
def goals_gen(data):
team_dict = {
1: data['event']['homeTeam'],
2: data['event']['awayTeam'],
}
for incident in data['incidents']:
if incident['incidentType'] == 'goal':
team = team_dict[incident['scoringTeam']]
yield {
'team-slug': team['slug'],
'time': incident['time'],
'eventid': data['event']['id'],
}
def goals_filter(events):
return list(chain.from_iterable(map(goals_gen, events)))
| repositoriolegal/JokerDoMilhao | Sofa/analysis/filters.py | filters.py | py | 803 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "itertools.chain.from_iterable",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "itertools.chain",
"line_number": 32,
"usage_type": "name"
}
] |
40243498393 | from api.serializers import RecipeSmallSerializer
from rest_framework import serializers
from users.models import Subscription, User
class UserShowSerializer(serializers.ModelSerializer):
"""Serializer to output user/user list."""
email = serializers.EmailField(required=True)
username = serializers.CharField(max_length=150, required=True)
first_name = serializers.CharField(max_length=150, required=True)
last_name = serializers.CharField(max_length=150, required=True)
is_subscribed = serializers.SerializerMethodField(read_only=True)
def get_is_subscribed(self, username):
user = self.context["request"].user
return (not user.is_anonymous
and Subscription.objects.filter(
user=user,
following=username
).exists())
class Meta:
model = User
fields = (
'email',
'id',
'username',
'first_name',
'last_name',
'is_subscribed',
)
class UserSerializer(serializers.ModelSerializer):
"""Basic custom user serializer with additional fields."""
email = serializers.EmailField(required=True)
username = serializers.CharField(max_length=150, required=True)
first_name = serializers.CharField(max_length=150, required=True)
last_name = serializers.CharField(max_length=150, required=True)
password = serializers.CharField(
min_length=4,
write_only=True,
required=True,
style={'input_type': 'password', 'placeholder': 'Password'}
)
class Meta:
model = User
fields = (
'email',
'username',
'first_name',
'last_name',
'password',
'role'
)
def validate_email(self, data):
if User.objects.filter(email=data).exists():
raise serializers.ValidationError(
"A user with this email is already registered."
)
return data
def validate_username(self, data):
if User.objects.filter(username=data).exists():
raise serializers.ValidationError(
"A user with this name already exists."
)
return data
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
user = super().update(instance, validated_data)
try:
user.set_password(validated_data['password'])
user.save()
except KeyError:
pass
return user
class SignupSerializer(serializers.ModelSerializer):
"""Serializer registration."""
username = serializers.CharField(max_length=150)
email = serializers.EmailField(max_length=254)
banned_names = ('me', 'admin', 'ADMIN', 'administrator', 'moderator')
class Meta:
model = User
fields = ('email', 'username',)
def validate_username(self, data):
if data in self.banned_names:
raise serializers.ValidationError(
"You can't use a name like that."
)
if User.objects.filter(username=data).exists():
raise serializers.ValidationError(
"User already exists."
)
return data
def validate_email(self, data):
if User.objects.filter(email=data).exists():
raise serializers.ValidationError(
"A user with this email is already registered."
)
return data
class TokenSerializer(serializers.Serializer):
"""TokenSerializer."""
username = serializers.CharField(max_length=150)
confirmation_code = serializers.CharField(max_length=24)
class SubShowSerializer(UserShowSerializer):
"""Serializer to output user/user list."""
email = serializers.ReadOnlyField(source='following.email')
id = serializers.ReadOnlyField(source='following.id')
username = serializers.ReadOnlyField(source='following.username')
first_name = serializers.ReadOnlyField(source='following.first_name')
last_name = serializers.ReadOnlyField(source='following.last_name')
is_subscribed = serializers.SerializerMethodField()
recipes = serializers.SerializerMethodField()
class Meta:
model = User
fields = (
'email',
'id',
'username',
'first_name',
'last_name',
'is_subscribed',
'recipes',
)
def get_is_subscribed(self, username):
"""If we request this method, we are subscribed to user"""
return True
def get_recipes(self, data):
"""Getting user recipes."""
limit = self.context.get('request').query_params.get('recipes_limit')
if not limit:
limit = 3
recipes = data.following.recipes.all()[:int(limit)]
return RecipeSmallSerializer(recipes, many=True).data
| nastyatonkova/foodgram-project-react | backend/users/serializers.py | serializers.py | py | 5,079 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "rest_framework.serializers",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "rest_framework.serializers.EmailField",
"line_number": 9,
"usage... |
26117861949 | from datetime import datetime, timezone
from unittest import TestCase
from zoneinfo import ZoneInfo
from app import chasecenter, ical
from app.tests.test_chasecenter import EXAMPLE_RAW_EVENT
EXAMPLE_EVENT = chasecenter.initialize_chase_event(EXAMPLE_RAW_EVENT)
class TestGenerateCalendar(TestCase):
def test_generate_empty(self) -> None:
cal = ical.generate_calendar([])
self.assertIn('Chase Center Events', cal)
self.assertIn('BEGIN:VCALENDAR', cal)
self.assertIn('END:VCALENDAR', cal)
def test_generate(self) -> None:
cal = ical.generate_calendar([EXAMPLE_EVENT])
self.assertIn('DTSTART:20200916T023000Z', cal)
self.assertIn('DTEND:20200916T053000Z', cal)
self.assertIn('SUMMARY:Tame Impala', cal)
self.assertIn('DESCRIPTION:example subtitle', cal)
self.assertIn('LOCATION:Chase Center\\, San Francisco', cal)
class TestDateString(TestCase):
def test_date_string(self) -> None:
dt = datetime(1998, 1, 18, 7, 30, tzinfo=timezone.utc)
formatted = ical.date_string(dt)
self.assertEqual(formatted, '19980118T073000Z')
def test_tz_date_string(self) -> None:
tz = ZoneInfo('America/Los_Angeles')
dt = datetime(1998, 1, 17, 23, 30).replace(tzinfo=tz)
formatted = ical.date_string(dt)
self.assertEqual(formatted, '19980118T073000Z')
| albertyw/chase-center-calendar | app/tests/test_ical.py | test_ical.py | py | 1,388 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "app.chasecenter.initialize_chase_event",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "app.tests.test_chasecenter.EXAMPLE_RAW_EVENT",
"line_number": 9,
"usage_type": "argument"
},
{
"api_name": "app.chasecenter",
"line_number": 9,
"usage_type": "... |
74035927782 | from __future__ import print_function, division
import torch
from torchvision import datasets, transforms
import os
import math
data_transforms = {
'train': transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = "/home/xcx/code/AI_class/Machine_l/net/data"
batch_size = 64
image_datasets = {x: datasets.CIFAR10(root=data_dir, train=(x=='train'), download=False, transform=data_transforms[x])
for x in ['train', 'val']}
dataloders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size,
shuffle=(x=='train'), num_workers=2)
for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
batch_nums = {x: int(math.ceil(dataset_sizes[x]/batch_size)) for x in ['train', 'val']}
print ('batch_size: ', batch_size, '\nbatch_nums: ', batch_nums)
print('dataset_sizes: ', dataset_sizes)
class_names = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
if __name__ == '__main__':
#train_loader = dataloders['train']
print(len(image_datasets['train']))
for index, data in enumerate(image_datasets['train']):
#inputs, labels = data
print(data)
break
| xuchaoxi/pytorch-classification | data_provider.py | data_provider.py | py | 1,588 | python | en | code | 24 | github-code | 36 | [
{
"api_name": "torchvision.transforms.Compose",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "torchvision.transforms",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "torchvision.transforms.RandomCrop",
"line_number": 10,
"usage_type": "call"
},
{
... |
13087308271 | import sql_connection as sq
import logging
def is_new_recipe(cursor, title):
"""
This function checks if the recipe title already exists in the database or not. If the recipe title does not
exist yet in the database, function returns True. If the title already exists in the database, or this an error,
function returns False.
:param cursor: Cursor object used to execute the query.
:param title: recipe title, unique
:return: True or False
"""
check_sql = "SELECT COUNT(*) FROM recipes WHERE title = %s"
check_values = (title,)
try:
cursor.execute(check_sql, check_values)
result = cursor.fetchone()[0]
return result == 0
except Exception as ex:
logging.error(f'SQL Error: is_new_recipe function: {ex}')
return False
def insert_recipe_data(cursor, scraped_data):
"""
Insert recipe data into the recipes table if the title does not already exist.
:param cursor: Cursor object used to execute the query.
:param scraped_data: A dictionary containing information about a recipe.
:return: True if the data is inserted, False if the title already exists.
"""
sql = "INSERT INTO recipes (id, link, title, num_reviews, rating, date_published) VALUES (NULL, %s, %s, %s, " \
"%s, %s) "
values = (
scraped_data.get('link'), scraped_data.get('title'), scraped_data.get('reviews'),
scraped_data.get('rating'),
scraped_data.get('published'))
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_recipe_data function: {ex}')
def insert_recipe_details(cursor, recipe_id, details):
"""
Insert recipe details into the recipe_details table.
:param cursor: Cursor object used to execute the query.
:param recipe_id: The ID of the recipe.
:param details: A dictionary containing the recipe details.
"""
sql = "INSERT INTO recipe_details (recipe_id, prep_time_mins, cook_time_mins, total_time_mins, servings) " \
"VALUES (%s, %s, %s, %s, %s)"
values = (recipe_id, details.get('Prep Time:'), details.get('Cook Time:'), details.get('Total Time:'),
details.get('Servings:'))
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_recipe_details function: {ex}')
def insert_nutrition_facts(cursor, recipe_id, nutrition):
"""
Insert nutrition facts into the nutrition_facts table.
:param cursor: Cursor object used to execute the query.
:param recipe_id: The ID of the recipe.
:param nutrition: A dictionary containing the nutrition facts.
"""
sql = "INSERT IGNORE INTO nutrition_facts (recipe_id, calories, fat_g, carbs_g, protein_g) " \
"VALUES (%s, %s, %s, %s, %s)"
values = (
recipe_id, nutrition.get('Calories'), nutrition.get('Fat'), nutrition.get('Carbs'), nutrition.get('Protein'))
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_nutrition_facts function: {ex}')
def insert_categories(cursor, recipe_id, categories):
"""
Insert categories into the categories table and the categories_recipes table.
:param cursor: Cursor object used to execute the query.
:param recipe_id: The ID of the recipe.
:param categories: A list of categories.
"""
for category in categories: # Check if category already exists in the categories table
sql = "SELECT id FROM categories WHERE category=%s"
cursor.execute(sql, (category,))
result = cursor.fetchone()
if not result: # If category doesn't exist, insert it into the categories table
sql = "INSERT INTO categories (category) VALUES (%s)"
values = (category,)
cursor.execute(sql, values)
category_id = cursor.lastrowid
else: # If category already exists, use its ID from the categories table
category_id = result[0]
sql = "INSERT INTO categories_recipes (category_id, recipe_id) VALUES (%s, %s)"
values = (category_id, recipe_id)
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_categories function: {ex}')
def insert_ingredients(cursor, recipe_id, ingredients):
"""
Insert ingredients into the ingredients table.
:param cursor: Cursor object used to execute the query.
:param recipe_id: The ID of the recipe.
:param ingredients: A list of ingredients.
"""
for ingredient in ingredients:
sql = "INSERT INTO ingredients (recipe_id, ingredient) VALUES (%s, %s)"
values = (recipe_id, ingredient)
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_ingredients function: {ex}')
def insert_instructions(cursor, recipe_id, instructions):
"""
Insert instructions into the instructions table.
:param cursor: Cursor object used to execute the query.
:param recipe_id: The ID of the recipe.
:param instructions: A dictionary containing the instructions.
"""
for step, description in instructions.items():
sql = "INSERT INTO instructions (recipe_id, step, description) VALUES (%s, %s, %s)"
values = (recipe_id, step, description)
try:
cursor.execute(sql, values)
except Exception as ex:
logging.error(f'SQL Error: insert_instructions function: {ex}')
def write_to_database(scraped_data):
"""
Write recipe data to the database.
:param scraped_data: A dictionary containing information about a recipe.
:return: None
"""
connection = sq.sql_connector()
cursor = connection.cursor()
if is_new_recipe(cursor, scraped_data['title']):
insert_recipe_data(cursor, scraped_data)
recipe_id = cursor.lastrowid
if scraped_data['details']:
details = check_keys(scraped_data['details'], ['Prep Time:', 'Cook Time:', 'Total Time:', 'Servings:'])
insert_recipe_details(cursor, recipe_id, details)
if scraped_data['nutrition']:
nutrition = check_keys(scraped_data['nutrition'], ['Calories', 'Fat', 'Carbs', 'Protein'])
insert_nutrition_facts(cursor, recipe_id, nutrition)
if scraped_data['category']:
insert_categories(cursor, recipe_id, scraped_data['category'])
if scraped_data['ingredients']:
insert_ingredients(cursor, recipe_id, scraped_data['ingredients'])
if scraped_data['instructions']:
insert_instructions(cursor, recipe_id, scraped_data['instructions'])
connection.commit()
connection.close()
def check_keys(dict_to_check, keys_to_check):
"""
Checks if a dictionary contains all the specified keys. If any of the keys are missing,
they are added to the dictionary with a value of None.
:param: dict_to_check: (dict) The dictionary to check.
keys_to_check: (list) The list of keys to check for in the dictionary.
:return: (dict) The dictionary with all the specified keys, with any missing keys added with a value of None.
"""
for key in keys_to_check:
if key not in dict_to_check:
dict_to_check[key] = None
return dict_to_check
| DarShabi/Web-Scraping-allrecipes | dump_data.py | dump_data.py | py | 7,380 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.error",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "logging.error",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "logging.error",
"line_number": 58,
"usage_type": "call"
},
{
"api_name": "logging.error",
"line_n... |
2223003364 | import collections
def longest_nonrep(s):
# len longest substr with nonrepeating characters
if s == "": return 0
d = {}
l = 0
last = 0
# use last i window to be the substring
for i in range(len(s)):
if d.get(s[i], -1) != -1: # if repeating character
last = max(last, d[s[i]]+1) # shift last
d[s[i]] = i # where last the letter s[i] was seen
l = max(l, i-last+1)
return l
def mod_longest_nonrep(s, k):
# replace k letters, find len longest substr of nonrep ch
if s == "": return 0
d = {}
l = 0
last = [0]
# same but with a queue
for i in range(len(s)):
if d.get(s[i], -1) != -1:
last.append(max(last[-1], d[s[i]]+1))
if len(last) > k+1:
last.pop(0)
d[s[i]] = i
l = max(l, i-last[0] +1)
return l
def mod_longest_rep(s, k):
# replace k letters, find len longest substr of rep ch
if s == "": return 0
d = collections.defaultdict(int)
l = 0
j = 0
ch = 0
# maintain in between j and i the substr
for i in range(len(s)):
d[s[i]] += 1 # keep track of letter freq in between j and i
ch = max(ch, d[s[i]])
# check if modified letters > k
if i - j + 1 - ch > k: # if substr not valid increment j to revalidate
d[s[j]] -= 1
j += 1
l = max(l, i - j + 1)
return l
print(longest_nonrep("abcabcbb"))
print(mod_longest_rep("aababba", 2))
print(mod_longest_nonrep("aababba", 2))
| arrws/leetcode | array/repeat_chars_substr.py | repeat_chars_substr.py | py | 1,530 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.defaultdict",
"line_number": 36,
"usage_type": "call"
}
] |
15108076525 | # -*- coding: utf-8 -*-
__author__ = 'lily'
import sys
import unittest
import time, datetime
from TestCase.webCase.case_web_all import ParametrizedTestCase,SearchTest,HomeTest,UserinfoTest
from common import report
from common import util
import xlsxwriter
from common import readYaml
import os
sys.path.append("..")
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p))
userCase = readYaml.getYam(r'E:\apiTest\YAML\web\case_user_api.yml')
searchCases = readYaml.getYam(r'E:\apiTest\YAML\web\case_search_api.yml')
getHomeCases = readYaml.getYam(r'E:\apiTest\YAML\web\case_home_api.yml')
def _report(filename):
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet("测试总况")
worksheet2 = workbook.add_worksheet("测试详情")
re = report.OperateReport(wd=workbook)
re.init(worksheet, data=util.DATA)
re.test_detail(worksheet2, data=util.INFO)
print(util.DATA,util.INFO)
util.DATA = {"title": "项目名称", "sum": 0, "pass": 0, "fail": 0, "test_date":"", "sum_time":""}
util.INFO = []
re.close()
'''运行首页的几个接口'''
def runnerCaseHome():
starttime = datetime.datetime.now()
suite = unittest.TestSuite()
for h in range(len(getHomeCases["homePage"])):
apiH = getHomeCases["homePage"][h]
suite.addTest(ParametrizedTestCase.parametrize(HomeTest, param=apiH))
unittest.TextTestRunner(verbosity=2).run(suite)
endtime = datetime.datetime.now()
util.DATA["sum_time"] = str((endtime - starttime).seconds) + "秒"
util.DATA["test_date"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
_report("..\ExcelReport\homePageAPI.xlsx")
'''运行搜索的几个借口'''
def runnerCaseSearch():
starttime = datetime.datetime.now()
suite = unittest.TestSuite()
for s in range(len(searchCases["searchAPI"])):
apiS = searchCases["searchAPI"][s]
suite.addTest(ParametrizedTestCase.parametrize(SearchTest, param=apiS))
unittest.TextTestRunner(verbosity=2).run(suite)
endtime = datetime.datetime.now()
util.DATA["sum_time"] = str((endtime - starttime).seconds) + "秒"
util.DATA["test_date"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
_report("..\ExcelReport\searchAPI.xlsx")
'''运行用户相关的几个接口'''
def runnerCaseUser():
starttime = datetime.datetime.now()
suite = unittest.TestSuite()
for u in range(len(userCase["userAPI"])):
apiS = userCase["userAPI"][u]
suite.addTest(ParametrizedTestCase.parametrize(UserinfoTest, param=apiS))
unittest.TextTestRunner(verbosity=2).run(suite)
endtime = datetime.datetime.now()
util.DATA["sum_time"] = str((endtime - starttime).seconds) + "秒"
util.DATA["test_date"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
_report("..\ExcelReport\meAndUserAPI.xlsx")
if __name__ == '__main__':
runnerCaseHome()
runnerCaseSearch()
runnerCaseUser()
pass
| hi-noikiy/apiTest | testRunner/webRunner.py | webRunner.py | py | 2,977 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.path.append",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "os.path.abspath",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_num... |
3747122457 | # Standard Library
import logging
import subprocess
logging.basicConfig(level=logging.INFO)
def create_namespace_if_not_exists(namespace_name: str) -> bool:
"""
Create a namespace if not exists
:param namespace_name:
name of the namespace you want to create
:return: bool
Returns true if namespace created else returns false
"""
created = False
# Check if the namespace already exists
check_namespace = subprocess.run(["kubectl", "get", "namespace", namespace_name], capture_output=True, text=True,
check=False)
if "NotFound" in check_namespace.stderr:
# Namespace doesn't exist, create it
create_namespace = subprocess.run(["kubectl", "create", "namespace", namespace_name], check=True)
if create_namespace.returncode == 0:
created = True
logging.info(f"Namespace {namespace_name} created. Preparing for deployment...")
else:
logging.error(f"Error reading namespace: {namespace_name}. Aborting deployment...")
else:
created = True
logging.info(f"Namespace {namespace_name} already exists. Preparing for deployment...")
return created
| abnamro/repository-scanner | deployment/resc-helm-wizard/src/resc_helm_wizard/kubernetes_utilities.py | kubernetes_utilities.py | py | 1,223 | python | en | code | 137 | github-code | 36 | [
{
"api_name": "logging.basicConfig",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "subprocess.run",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "subprocess.run",
... |
11440299116 | # _*_ coding:utf-8 _*_
"""
主界面逻辑函数
"""
import os
import exifread
import requests
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QFileDialog
from ui.main_window import Ui_Form
class MainWindow(Ui_Form, QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
self.setWindowTitle('用户识别')
# self.init_ui()
self.init_slot()
def init_slot(self):
self.pushButton.clicked.connect(self.openfile)
self.lastpushButton.clicked.connect(self.NextImBntClicked)
self.prepushButton.clicked.connect(self.PreImBntClicked)
#打开文件
def openfile(self):
#图片路径
self.download_path = QFileDialog.getExistingDirectory(self, "选择文件夹", "/")
if not self.download_path[0].strip():
pass
else:
self.lineEdit.setText(self.download_path)
#图片集合
self.ImNameSet = os.listdir(self.download_path)
self.ImNameSet.sort()
self.ImPath = self.download_path+'/'+self.ImNameSet[0]
pix = QPixmap(self.ImPath)
# 处理图片
# 规定大小
scarePixmap = pix.scaled(QSize(271, 261), aspectRatioMode=Qt.KeepAspectRatio)
self.label_3.setPixmap(scarePixmap)
#当前图片id
self.CurImId = 0
#查看当前图片属性
self.get_photo_info
#显示下一张
def NextImBntClicked(self):
# download_path = download_path
# ImNameSet = self.ImNameSet
# CurImId = self.CurImId
#图片个数
self.ImNum = len(self.ImNameSet)
if self.CurImId<self.ImNum-1:#不可循环看图
self.ImPath = os.path.join(self.download_path, self.ImNameSet[self.CurImId+1])
pix = QPixmap(self.ImPath)
scarePixmap = pix.scaled(QSize(271, 261), aspectRatioMode=Qt.KeepAspectRatio)
self.label_3.setPixmap(scarePixmap)
self.CurImId = self.CurImId+1
self.get_photo_info
#显示上一张
def PreImBntClicked(self):
# ImNameSet = self.ImNameSet
# CurImId = self.CurImId
# ImNum = len(ImNameSet)
if self.CurImId > 0: # 第一张图片没有前一张
self.ImPath = os.path.join(self.download_path, self.ImNameSet[self.CurImId - 1])
pix = QPixmap(self.ImPath)
scarePixmap = pix.scaled(QSize(271, 261), aspectRatioMode=Qt.KeepAspectRatio)
self.label_3.setPixmap(scarePixmap)
self.CurImId = self.CurImId - 1
# 显示图片属性
self.get_photo_info
# 显示图片属性的基本信息
@property
def get_photo_info(self):
f = open(self.ImPath, 'rb')
tags = exifread.process_file(f)
# 打印照片信息
# try:
print('拍摄时间:', tags['EXIF DateTimeOriginal'])
print('照片尺寸:', tags['EXIF ExifImageWidth'], tags['EXIF ExifImageLength'])
# 纬度
# lat_ref = tags["GPS GPSLatitudeRef"].printable
# lat = tags["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
# lat = float(lat[0]) + float(lat[1]) / 60 + float(lat[2]) / float(lat[3]) / 3600
# if lat_ref != "N":
# lat = lat * (-1)
# # 经度
# lon_ref = tags["GPS GPSLongitudeRef"].printable
# lon = tags["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
# lon = float(lon[0]) + float(lon[1]) / 60 + float(lon[2]) / float(lon[3]) / 3600
# if lon_ref != "E":
# lon = lon * (-1)
# except KeyError:
# return "ERROR:请确保照片包含经纬度等EXIF信息。"
# else:
# print("经纬度:", lat, lon)
# return lat, lon
# 显示图片位置信息
# def get_photo_location(self):
# self.ak = 'nYPs4LQ9a4VhVxj55AD69K6zgsRy9o4z' #替换为自己申请的密钥
# self.location = self.get_photo_info()
# url = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak={}&output=json' \
# '&coordtype=wgs84ll&location={},{}'.format(self.ak, *self.location)
# response = requests.get(url).json()
# status = response['status']
# if status == 0:
# address = response['result']['formatted_address']
# print('详细地址:', address)
# else:
# print('baidu_map error')
| a-ltj/pyqt_image | view/main.py | main.py | py | 4,659 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "ui.main_window.Ui_Form",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "PyQt5.QtWidgets.QWidget",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "PyQt5.QtWidgets.QFileDialog.getExistingDirectory",
"line_number": 34,
"usage_type": "call"... |
72748557223 | from asyncio.windows_events import NULL
from cmath import nan
from itertools import count
import os
from pathlib import Path
from importlib.resources import path
from tokenize import String
from weakref import ref
import pandas as pd
import numpy as np
import datetime
# cols_to_be_replaced = ['Kund: Namn', 'Kund: C/o', 'Kund: Telefonnr', 'Kund: Mobilnr', 'Boendetyp', 'BP']
# cols_to_be_replaced_with = ['Namn', 'CO', 'Fast telefon 1', 'Mobil 1', 'Hitta', ]
cols_to_be_replaced_with = [0, 1, 6, 7, 9, 10]
cols_to_be_replaced = [0, 6, 9, 10, 67, 68]
def Create_DF(file_path):
print('Creating data frame of file ', file_path , '...')
df = pd.read_excel(file_path)
# print(df['Bearbetning: Start'])
return df
def Save_Excel_File(df, filePath, ext, folderName, abs_path):
file_name = Path(filePath).stem + ext
file_path_to_be_saved_at = str(abs_path) + folderName + file_name
path = Path(file_path_to_be_saved_at)
path.parent.mkdir(parents=True, exist_ok=True)
df.to_excel(file_path_to_be_saved_at, index = 0)
print(file_name, " saved at ", str(abs_path) + folderName)
return file_path_to_be_saved_at
def Conact_DFs_for_ref(path_of_ref_dfs):
frames = []
for i in range(0, len(path_of_ref_dfs)):
temp_df = Create_DF(path_of_ref_dfs[i])
frames.append(temp_df)
result_df = pd.concat(frames)
print(result_df)
return result_df
def Conact_DFs(df1, df2):
frames = [df1, df2]
result_df = pd.concat(frames)
return result_df
def BJ_equals_N(df: pd.DataFrame, title, replace, nyinflyttade_df: pd.DataFrame):
# df_BI_N = df.loc[ ( df['Bor_Kvar'] == "N") ]
df_BI_N = df
if not df_BI_N.empty:
print(df_BI_N['Bor_Kvar'])
for i in df_BI_N.index:
if title == 'Har flyttat':
df_BI_N.at[i,'Log'] = title
else:
df_BI_N.at[i,'Log'] = title + df_BI_N.at[i,'Kund: Namn'] + ")"
print( df_BI_N.at[i,'Log'])
if replace == True:
cond1 = str(df_BI_N.at[i, 'Kund: Postadress'])
cond2 = str(df_BI_N.at[i, 'Kund: Postort'])
df2 = nyinflyttade_df.loc[(nyinflyttade_df['Postort'] == cond1) & (nyinflyttade_df['Boendeform'] == cond2)]
df2.drop_duplicates(df2.drop_duplicates(subset=['Postort','Boendeform'], keep='first', inplace=True))
if not df2.empty:
print(df2)
for j in range(0,6):
df_BI_N.at[i, df_BI_N.columns[ cols_to_be_replaced[j] ] ] = df2[ df2.columns[cols_to_be_replaced_with[j]] ].iat[0]
# final_df = Conact_DFs(df, df_BI_N)
# final_df = final_df[~final_df.index.duplicated(keep='last')]
return df_BI_N
else:
return df
def Handling_Duplicates(main_df: pd.DataFrame, dup_df: pd.DataFrame):
print(len(main_df))
for index, row in main_df.iterrows():
df1 = dup_df.loc[(dup_df['Kund: Postadress'] == row['Kund: Postadress']) & (dup_df['Kund: Postort'] == row['Kund: Postort'])]
dup_rows_array = []
if not df1.empty:
print (df1)
columns = df1.columns.tolist()
for i, r in df1.iterrows():
dup_row_data = ""
if not pd.isna(r['Log']):
print(str(r['Log']))
dup_rows_array.insert(0, str(r['Log']))
for c in columns:
value = str(r[c])
if(value != "nan"):
dup_row_data += value
dup_rows_array.append(dup_row_data)
print(dup_rows_array)
sorted_Log = ""
for item in dup_rows_array:
print(item)
sorted_Log = sorted_Log + '\n' + str(item)
print(sorted_Log)
print(main_df.at[index, 'Log'])
if pd.isna(row['Log']):
main_df.at[index,'Log'] = sorted_Log
print(main_df.at[index,'Log'])
elif not pd.isna(row['Log']):
print(row['Log'])
main_df.at[index,'Log'] = '\n' + main_df.at[index,'Log'] + '\n' + sorted_Log
final_df = Conact_DFs(main_df, dup_df)
final_df = final_df[~final_df.index.duplicated(keep='last')]
return final_df
def main(main_file_path, reference_files_list, nyinflyttade_file_path, ny_fil_med_avlidna_file_path, abs_path):
main_df = Create_DF(main_file_path)
print('Created data frame of ', main_file_path, ' !!!')
ref_dfs = Conact_DFs_for_ref(reference_files_list)
print('Created data frame of ', reference_files_list, ' !!!')
nyinflyttade_df = Create_DF(nyinflyttade_file_path)
print('Created data frame of ', nyinflyttade_file_path, ' !!!')
ny_fil_med_avlidna_df = Create_DF(ny_fil_med_avlidna_file_path)
print('Created data frame of ', ny_fil_med_avlidna_file_path, ' !!!')
main_df.insert(loc=len(main_df.columns), column='BP', value="")
main_df.insert(loc=len(main_df.columns), column='BQ', value="")
#sorting by Bokning: Start Column
main_df = main_df.sort_values(by=['Bokning: Start'], ascending=True)
#finding all duplicate values
dup_df_fil = main_df[main_df.duplicated(subset=['Kund: Postadress','Kund: Postort'], keep=False)].sort_values('Kund: Postadress')
#droping the first but keeping rest of the duplicates
dup_df = dup_df_fil[dup_df_fil.duplicated(subset=['Kund: Postadress','Kund: Postort']) | ~dup_df_fil.duplicated(subset=['Kund: Postadress','Kund: Postort'], keep=False)].sort_values('Kund: Postadress')
print(dup_df['Log'])
m = dup_df.Bor_Kvar == "N"
dup_df_not_whereN = dup_df[~m]
dup_df_whereN = dup_df[m]
dup_df_whereN = BJ_equals_N(dup_df_whereN, "Nyinflyttad (tidigare ägare ", True, nyinflyttade_df)
dup_df = Conact_DFs(dup_df_whereN, dup_df_not_whereN)
print(dup_df['Log'])
#droping all duplicate from original df and keeping with earliest date only
main_df.drop_duplicates(main_df.drop_duplicates(subset=['Kund: Postadress','Kund: Postort'], keep='first', inplace=True))
m = main_df.Bor_Kvar == "N"
main_df_not_whereN = main_df[~m]
main_df_whereN = main_df[m]
# print(main_df_not_whereN['Bor_Kvar'])
main_df_whereN = BJ_equals_N(main_df_whereN, "Har flyttat", False, nyinflyttade_df)
main_df = Conact_DFs(main_df_whereN, main_df_not_whereN)
# main_df = main_df[~main_df.index.duplicated(keep='last')]
main_df = Handling_Duplicates(main_df, dup_df)
print(main_df)
# saved_path = Save_Excel_File(main_df, main_file_path, '(modified).xlsx', '/output/', abs_path)
output = {'Log': []}
for i in range(1,15):
print('Checking Ufall ', i, ' ...')
output['Ufall ' + str(i)] = []
for index, row in main_df.iterrows():
########## Checking if AW = Avliden ##########
title_for_ny_fil_med_avlidna_df = ""
if(row['SPAR_Status'] == "Avliden"):
title_for_ny_fil_med_avlidna_df = "Ny ägare (tidigare ägare " + row['Kund: Namn'] + " avliden)"
cond1 = str(main_df.at[i, 'Kund: Postadress'])
cond2 = str(main_df.at[i, 'Kund: Postort'])
df2 = ny_fil_med_avlidna_df.loc[(ny_fil_med_avlidna_df['Postort'] == cond1) & (ny_fil_med_avlidna_df['Boendeform'] == cond2)]
print(df2)
df2.drop_duplicates(df2.drop_duplicates(subset=['Postort','Boendeform'], keep='first', inplace=True))
if not df2.empty:
print(df2)
for j in range(0,6):
main_df.at[i, main_df.columns[ cols_to_be_replaced[j] ] ] = df2[ df2.columns[cols_to_be_replaced_with[j]] ].iat[0]
strr = ''
if( not (row['Bearbetning: Start'] ) is np.nan):
strr = (row['Bearbetning: Start'] ) + ', '
if( not (row['Bearbetning: Utfall']) is np.nan):
if(strr != None):
strr = strr + (row['Bearbetning: Utfall']) + ', '
else:
strr = (row['Bearbetning: Utfall']) + ', '
if( not (row['Resurs: Namn']) is np.nan):
if(strr != None):
strr = strr + (row['Resurs: Namn']) + ', '
else:
strr = (row['Resurs: Namn']) + ', '
if( not (row['Resurs: Notering']) is np.nan):
if(strr != None):
strr = strr + (row['Resurs: Notering'])
else:
strr = (row['Resurs: Notering'])
AE_value = []
print('saving value ', strr, ' in column Ufall 1...')
output['Ufall 1'].append(strr)
print('saved!!!')
print('Adding in Log...')
print(strr)
AE_value.append(strr)
print('Added!!!!')
k = 2
temp = ref_dfs.loc[row['Kund: Namn'] == ref_dfs['Kund: Namn']]
for ind, row2 in temp.iterrows():
if (row['Kund: Postadress'] == row2['Kund: Postadress']):
strr_ref = ''
if( not (row2['Bearbetning: Start'] ) is np.nan):
strr_ref = (row2['Bearbetning: Start'] ) + ', '
if( not (row2['Projekt: Namn']) is np.nan):
if(strr_ref != None):
strr_ref = strr_ref + (row2['Projekt: Namn']) + ', '
else:
strr_ref = (row2['Projekt: Namn']) + ', '
if( not (row2['Bearbetning: Utfall']) is np.nan):
if(strr_ref != None):
strr_ref = strr_ref + (row2['Bearbetning: Utfall']) + ', '
else:
strr_ref = (row2['Bearbetning: Utfall']) + ', '
if( not (row2['Resurs: Namn']) is np.nan):
if(strr_ref != None):
strr_ref = strr_ref + (row2['Resurs: Namn']) + ', '
else:
strr_ref = (row2['Resurs: Namn']) + ', '
if( not (row2['Resurs: Notering']) is np.nan):
if(strr_ref != None):
strr_ref = strr_ref + (row2['Resurs: Notering'])
else:
strr_ref = (row2['Resurs: Notering'])
print('saving value ', strr_ref, 'in Ufall ', str(k), ' ...')
output['Ufall ' + str(k)].append(strr_ref)
print('saved!!!')
print('Adding in Log...')
AE_value.append(strr_ref)
print('Added!!!!')
k += 1
AE_value = sorted(AE_value, reverse=True ,key=lambda x: datetime.datetime.strptime(x.split(',')[0], '%Y-%m-%d %H:%M'))
if not pd.isna(row['Log']):
print(row['Log'])
AE_value.insert(0, str(row['Log']))
if title_for_ny_fil_med_avlidna_df:
print(title_for_ny_fil_med_avlidna_df)
AE_value.insert(0, title_for_ny_fil_med_avlidna_df)
sorted_Log = ""
print(sorted_Log)
for item in AE_value:
print(item)
sorted_Log = sorted_Log + '\n' + item
print(row['Bor_Kvar'])
output['Log'].append(sorted_Log)
print(output['Log'][-1])
for rem in range(k, 15):
output['Ufall ' + str(rem)].append("")
print('Optimizing file....')
outputdf = pd.DataFrame(data=output)
outputdf = outputdf.replace(np.nan,"")
main_df['Log'] = np.nan
main_df["Log"] = outputdf["Log"]
# print(main_df.loc[])
for i in range(1, 15):
main_df['Ufall ' + str(i)] = output['Ufall ' + str(i)]
print('Optimzation Completed')
main_df = main_df
m = main_df.Bor_Kvar == "N"
main_df_not_whereN = main_df[~m]
main_df_whereN = main_df[m]
for index, row in main_df_not_whereN.iterrows():
if (not pd.isna(row['Log'])) and ('Har flyttat' in row['Log']):
print(row['Bor_Kvar'])
print(row['Log'])
text = str(row['Log'])
x = text.replace("Har flyttat", "")
row['Log'] = x
main_df = Conact_DFs(main_df_not_whereN, main_df_whereN)
print('Saving file...')
saved_path = Save_Excel_File(main_df, main_file_path, '(modified).xlsx', '/output/', abs_path)
print('file saved at ', saved_path)
print('Finished!!!!')
def Start_Editing(main_file_path, reference_file1, reference_file2, Nyinflyttade_folder_path, Ny_fil_med_avlidna_folder_path):
print('Started!!!!!')
abs_path = Path(main_file_path).parent
ref_file_list = []
ref_file_list.append(reference_file1)
ref_file_list.append(reference_file2)
print(ref_file_list)
main(main_file_path, ref_file_list, Nyinflyttade_folder_path, Ny_fil_med_avlidna_folder_path, abs_path)
# main_file_path = "E:\Freelance/teodor\Main\Input_output/attachments/Alla orginalbokningar _ info från Bisnode.xlsx"
# ref_file_list = [ "E:\Freelance/teodor\Main\Input_output/attachments/cross senast utfall (samtliga) 48228st (1).xlsx", "E:\Freelance/teodor\Main\Input_output/attachments/retention senast utfall (samtliga) 33113st (1).xlsx"]
# nyinflyttade_file_path ="E:\Freelance/teodor\Main\Input_output/attachments/Nyinflyttade _ Kollad av Team Africa.xlsx"
# ny_fil_med_avlidna_file_path = "E:\Freelance/teodor\Main\Input_output/attachments/Ny fil med avlidna (ej kollad av Team Africa).xlsx"
# abs_path = Path(main_file_path).parent
# main(main_file_path, ref_file_list, nyinflyttade_file_path, ny_fil_med_avlidna_file_path, abs_path) | Farazzaidi22/TeodorProject | Main/Source Code/script.py | script.py | py | 13,948 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_excel",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "importlib.resources.path",
"line_number": 32,
"usage_type": "name"
},
{
"api_name": "pathlib.Path"... |
22525078962 | from . import user
from ..models.user import User, Contact
from flask import render_template, flash, redirect, request, url_for
from flask_login import login_required, current_user
from ..forms.profile import PhotoForm, EditProfileForm
from ..forms.activity import ContactForm
import os
from ..extentions import avatarUser, db
from ..tools.photo import resize, resize_fix_width
from ..tools.string_tools import get_rnd_filename_w_ext
from ..tools.permissions import only_user_id
@user.route('/modify_avatar', methods=['GET', 'POST'])
@login_required
def modify_avatar():
"""
提交新头像:
删除原头像
resize新头像
保存新头像(in file & database)
:return:
"""
form = PhotoForm()
if form.validate_on_submit():
if current_user.avatar:
os.remove(avatarUser.path(filename=current_user.avatar))
image = form.avatar.data
imagename = get_rnd_filename_w_ext(image.filename)
imagepath = avatarUser.path(filename=imagename)
resize_fix_width(image, imagepath)
current_user.avatar = imagename
db.session.add(current_user)
return redirect(url_for('.profile', id=current_user.id))
return render_template('modify_avatar.html', form=form)
@user.route('/profile/<int:id>')
def profile(id):
user = User.get_user(id)
return render_template('profile.html', user = user)
@user.route('/profile/me')
@login_required
def profile_me():
return redirect(url_for('.profile', id=current_user.id))
@user.route('/profile/details/<int:id>')
def profile_details(id):
user = User.query.get_or_404(id)
return render_template('profile_details.html', user = user)
@user.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm()
if request.method == 'GET':
form.username.data = current_user.username
form.gender.data = current_user.gender
form.birthday.data = current_user.birthday
form.about_me.data = current_user.about_me
form.name.data = current_user.name
form.phone.data = current_user.phone
form.id_number.data = current_user.id_number
form.address.data = current_user.address
if form.validate_on_submit():
current_user.username = form.username.data
current_user.gender = form.gender.data
current_user.birthday = form.birthday.data
current_user.about_me = form.about_me.data
current_user.phone = form.phone.data
current_user.name = form.name.data
current_user.id_number = form.id_number.data
current_user.address = form.address.data
db.session.add(current_user)
flash('个人资料编辑成功')
return redirect(url_for('user.profile_details', id=current_user.id))
return render_template('edit_profile.html', form=form)
'''
---------------------关注-----------------------------
'''
@user.route('/followers/<int:id>')
def followers(id):
page = request.args.get('page', 1, type=int)
user = User.query.get_or_404(id)
pagination, users = user.fans_list(page)
return render_template('follower.html',
users=users,
user=user,
pagination=pagination)
#我关注的人
@user.route('/followed/<int:id>')
def followed(id):
page = request.args.get('page', 1, type=int)
user = User.query.get_or_404(id)
pagination, users = user.follow_list(page)
return render_template('followed.html',
users=users,
user=user,
pagination=pagination)
@user.route('/follow/<int:id>')
@login_required
def follow(id):
user = User.query.get_or_404(id)
current_user.follow(user)
flash('关注成功')
return redirect(url_for('.profile', id=id))
@user.route('/unfollow/<int:id>')
@login_required
def unfollow(id):
user = User.query.get_or_404(id)
current_user.unfollow(user)
flash('取消关注成功')
return redirect(url_for('.profile', id=id))
#-------------团队-------------
@user.route('/teams/my/<int:id>')
def my_teams(id):
user = User.query.get_or_404(id)
teams = user.leader_teams
return render_template('my_teams.html',
user=user,
teams=teams)
@user.route('/teams/joined/<int:id>')
def joined_teams(id):
user = User.query.get_or_404(id)
teams = user.teams_joined
return render_template('teams_joined.html',
user=user,
teams=teams)
#---------------活动-------------------
@user.route('/activities/joined/<int:id>')
def activities_joined(id):
user = User.query.get_or_404(id)
activities = user.activities_join()
return render_template('activities_join.html',
user=user,
activities=activities)
@user.route('/activities/joined/unpay')
@login_required
def activities_joined_unpay():
activities = current_user.activities_join_unpay()
return render_template('activities_join.html',
user=current_user,
activities=activities)
@user.route('/activities/follow/<int:id>')
def activities_follow(id):
user = User.query.get_or_404(id)
activities = user.activities_follow()
return render_template('activities_followed.html',
user=user,
activities=activities)
"""
出行人
"""
@user.route('/modify_contacts', methods=['GET', 'POST'])
@user.route('/modify_contacts/<int:id>', methods=['GET', 'POST'])
@login_required
def modify_contacts(id=0):
if id:
contact = Contact.query.get_or_404(id)
only_user_id(contact.user_id) # permission
form = ContactForm()
contacts = Contact.query.filter_by(user_id=current_user.id).all()
if id and request.method == 'GET':
form.real_name.data = contact.name
form.phone.data = contact.phone
form.gender.data = contact.gender
form.age.data = contact.age
form.identity.data = contact.identity
form.province.data = contact.province
if form.validate_on_submit():
if not id:
contact = Contact()
contact.user_id = current_user.id
contact.name = form.real_name.data
contact.identity = form.identity.data
contact.gender = form.gender.data
contact.province = form.province.data
contact.age = form.age.data
contact.phone = form.phone.data
db.session.add(contact)
flash('编辑成功')
return redirect(url_for('.modify_contacts'))
return render_template('modify_contacts.html',
form=form,
contacts=contacts,
user=current_user)
| Honglin-Li/TravelPlatform | app/user/view_profile.py | view_profile.py | py | 7,125 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "forms.profile.PhotoForm",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "flask_login.current_user.avatar",
"line_number": 26,
"usage_type": "attribute"
},
{
"api_name": "flask_login.current_user",
"line_number": 26,
"usage_type": "name"
},
{
... |
17864613680 | import traceback
import copy
from compare_reports import Comparison
import sources
import warnings
import asyncio
import inspect
import arrow
import ast
import sys
import time
import pandas as pd
from pprint import pprint
from string import ascii_lowercase
import gspread
import gspread_formatting
from oauth2client.service_account import ServiceAccountCredentials
from openpyxl import load_workbook
import datetime
import xlsxwriter
from gspread_formatting import *
######### Globals
warnings.filterwarnings("ignore")
true = True
false = False
semaphore = 1
days_summary_dict = {"interval": "day", "comparisons": []}
weeks_summary_dict = {"interval": "week", "comparisons": []}
months_summary_dict = {"interval": "month", "comparisons": []}
total_matches = 0
total_edw3_mismatches = 0
total_edw2_mismatches = 0
total_edw2_orphans = 0
total_edw3_orphans = 0
g_utils = gspread.utils
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("../creds.json", scope)
client = gspread.authorize(creds)
summary_sheet_names = [
'month_summary',
'week_summary',
'day_summary'
]
inverted_summary_sheet_names = [
'month_summary_inverted',
'week_summary_inverted',
'day_summary_inverted'
]
weeks_comp = []
days_comp = []
months_comp = []
myinterval = 0
arrow_formats = {
"mm_dd_yyyy": "%m/%d/%Y",
"yyyymmdd": "%Y%m%d"
}
##################
def generate_dates(starting_date, ending_date, interval='day'):
result = {"dates": [],
"interval": interval}
for r in arrow.Arrow.range(interval, starting_date, ending_date):
result["dates"].append(r.format('MM/DD/YYYY'))
# check if the last week covers to the last day of the month
last_date = result["dates"][-1]
start = arrow.get(starting_date)
end = arrow.get(ending_date)
date_split = last_date.split("/")
# If the last day is not == to the last day of the range,
missing_days = (arrow.get(int(date_split[2]), int(date_split[0]), int(date_split[1])).is_between(start, end))
if missing_days:
# add the remaining days for the range
result["dates"].append(ending_date.strftime('%m/%d/%Y'))
return result
def check_replace(request_object, dates_hash, interval, date_idx, date_format=None):
# extrapolate format info
if date_format is None:
date_format = {
"filter_format": "mm_dd_yyyy",
"dimension_format": "yyyymmdd",
"date_col_name": "DATE"
}
column_name = date_format["date_col_name"]
filter_field = "dim_date-%s" % date_format["filter_format"]
dimension_field = "dim_date-%s" % date_format["dimension_format"]
filter_format = arrow_formats[date_format["filter_format"]]
# create a fresh filter
start = dates_hash["dates"][date_idx]
valid_start = start.split('/')
valid_start = arrow.get(int(valid_start[2]), int(valid_start[0]), int(valid_start[1]))
new_start = valid_start.strftime(filter_format)
if interval != 'day':
end = dates_hash["dates"][date_idx + 1]
valid_end = end.split('/')
valid_end = arrow.get(int(valid_end[2]), int(valid_end[0]), int(valid_end[1]))
new_end = valid_end.strftime(filter_format)
if interval == 'day':
replacement_filter = {
"field": filter_field,
"op": "eq",
"values": [
new_start
]
}
elif interval == 'week':
# 1st iteration specification
if date_idx == 0:
replacement_filter = {
"field": filter_field,
"op": "between",
"values": [
new_start,
new_end
]
}
else:
split_start = start.split('/')
shiftable_date_obj = arrow.get(int(split_start[2]), int(split_start[0]), int(split_start[1]))
modified_start = shiftable_date_obj.shift(days=+1).strftime(filter_format)
replacement_filter = {
"field": filter_field,
"op": "between",
"values": [
modified_start,
new_end
]
}
elif interval == 'month':
split_end = end.split('/')
shiftable_date_obj = arrow.get(int(split_end[2]), int(split_end[0]), int(split_end[1]))
modified_end = shiftable_date_obj.shift(days=-1).strftime(filter_format)
# last iteration specification
if date_idx == len(dates_hash["dates"]) - 2:
replacement_filter = {
"field": filter_field,
"op": "between",
"values": [
new_start,
new_end
]
}
else:
replacement_filter = {
"field": filter_field,
"op": "between",
"values": [
new_start,
modified_end
]
}
replacement_date_dim = {
"id": dimension_field,
"name": column_name,
"alias": "date"
}
# Look in the filters
dim_name = 'dim_date'
for report_name in request_object:
for col_idx, col_obj in enumerate(request_object[report_name]["cols"]):
if 'prepared_id' in col_obj:
continue
if dim_name in col_obj["id"]:
# print("Deleting - Dimension - ", col_obj)
# print("Replacement - Dimension - ", replacement_date_dim)
del request_object[report_name]["cols"][col_idx]
request_object[report_name]["cols"].append(replacement_date_dim)
# Replace Filter
for filter_idx, filter_obj in enumerate(request_object[report_name]["filters"]):
if dim_name in filter_obj["field"]:
# print("Deleting - Filter - ", filter_obj)
# print("Replacement - Filter - ", replacement_filter)
del request_object[report_name]["filters"][filter_idx]
# Replace the Deleted (if found) filter
request_object[report_name]["filters"].append(replacement_filter)
# print("new object --- ", json.dumps(request_object))
def simple_comparison(edw2_ro, edw3_ro):
edw2_url = 'https://picker-dev.avantlink.com/rpt'
edw3_url = 'https://picker-shard.avantlink.com/rpt'
Comparison(sources.PickerReport(picker_url=edw3_url,
report_name="edw3_report_name",
request_object=edw3_ro),
sources.PickerReport(picker_url=edw2_url,
report_name="edw2_report_name",
request_object=edw2_ro)
)
async def run_comparison(dates_hash, date_idx, edw2_request_object, edw3_request_object,
side_by_side=None,
interval="day", report_name="custom_comparison",
output_xlsx=False, cascade=False, cascade_start_date=None, cascade_end_date=None,
picker_address=None):
if date_idx == len(dates_hash["dates"]) - 1 and interval != 'day':
print('hitting end condition \n \n \n')
return
start = dates_hash["dates"][date_idx]
split_start = start.split('/')
shiftable_start_date_obj = arrow.get(int(split_start[2]), int(split_start[0]), int(split_start[1]))
end = dates_hash["dates"][date_idx]
try:
end = dates_hash["dates"][date_idx + 1]
except IndexError:
pass
split_end = end.split('/')
shiftable_end_date_obj = arrow.get(int(split_end[2]), int(split_end[0]), int(split_end[1]))
async with sem:
if side_by_side:
check_replace(edw2_request_object, dates_hash, interval, date_idx, side_by_side["date_format"])
check_replace(edw3_request_object, dates_hash, interval, date_idx, side_by_side["date_format"])
else:
check_replace(edw2_request_object, dates_hash, interval, date_idx)
check_replace(edw3_request_object, dates_hash, interval, date_idx)
if interval == 'day':
edw2_report_name = report_name + "__" + start + "_edw2"
edw3_report_name = report_name + "__" + start + "_edw3"
elif interval == 'week':
if date_idx == 0:
edw2_report_name = report_name + "__" + start + "--" + end + "__" + interval + "_edw2"
edw3_report_name = report_name + "__" + start + "--" + end + "__" + interval + "_edw3"
else:
modified_start = shiftable_start_date_obj.shift(days=+1).strftime('%m/%d/%Y')
edw2_report_name = report_name + "__" + modified_start + "--" + end + "__" + interval + "_edw2" + "--"
edw3_report_name = report_name + "__" + modified_start + "--" + end + "__" + interval + "_edw3"
elif interval == 'month':
if date_idx == len(dates_hash["dates"]) - 2:
edw2_report_name = report_name + "__" + start + "--" + end + "__" + interval + "_edw2" + "--"
edw3_report_name = report_name + "__" + start + "--" + end + "__" + interval + "_edw3"
else:
modified_end = shiftable_end_date_obj.shift(days=-1).strftime('%m/%d/%Y')
edw2_report_name = report_name + "__" + start + "--" + modified_end + "__" + interval + "_edw2" + "--"
edw3_report_name = report_name + "__" + start + "--" + modified_end + "__" + interval + "_edw3"
edw2_url = 'https://picker-dev.avantlink.com/rpt'
edw3_url = 'https://picker-shard.avantlink.com/rpt'
report_a_address = edw3_url
report_b_address = edw2_url
if picker_address == "edw3":
report_a_address = edw3_url
report_b_address = edw3_url
if picker_address == "edw2":
report_a_address = edw2_url
report_b_address = edw2_url
if side_by_side:
comparison = Comparison(sources.PickerReport(picker_url=report_a_address,
report_name=edw3_report_name,
currency=side_by_side["currency"],
request_object=edw3_request_object),
sources.PickerReport(picker_url=report_b_address,
report_name=edw2_report_name,
currency=side_by_side["currency"],
request_object=edw2_request_object)
)
else:
comparison = Comparison(sources.PickerReport(picker_url=report_a_address,
report_name=edw3_report_name,
request_object=edw3_request_object),
sources.PickerReport(picker_url=report_b_address,
report_name=edw2_report_name,
request_object=edw2_request_object)
)
comparison_start_date = start
comparison_end_date = end
try:
comparison_start_date = modified_start
except UnboundLocalError:
pass
try:
comparison_end_date = modified_end
except UnboundLocalError:
pass
if interval == 'day':
comparison_end_date = comparison_start_date
comparison.set_outputs(output_xlsx=output_xlsx, interval=interval, simple_report_name=report_name,
comparison_start_date=comparison_start_date, comparison_end_date=comparison_end_date,
cascade=cascade,
# side_by_side=side_by_side,
cascade_start_date=cascade_start_date, cascade_end_date=cascade_end_date)
await comparison.run_and_barf()
return comparison
async def loop_reports(dates_hash, edw2_request_object, edw3_request_object,
semaphore=3, interval="day",
output_xlsx=False, report_name='custom_comparison', side_by_side=None,
cascade=False,
cascade_start_date=None, cascade_end_date=None, picker_address=None):
global sem
sem = asyncio.Semaphore(semaphore)
futures = []
for date_idx, date in enumerate(dates_hash["dates"]):
if date_idx == len(dates_hash["dates"]) - 1 and interval != 'day':
break
edw2_request_copy = copy.deepcopy(edw2_request_object)
edw3_request_copy = copy.deepcopy(edw3_request_object)
futures.append(run_comparison(dates_hash, date_idx, edw2_request_copy, edw3_request_copy, interval=interval,
output_xlsx=output_xlsx, report_name=report_name,
cascade=cascade,
side_by_side=side_by_side,
cascade_start_date=cascade_start_date, cascade_end_date=cascade_end_date,
picker_address=picker_address))
result = await asyncio.gather(*futures)
return result
async def cascade_months(start, end, edw2_request_object, edw3_request_object, cascade_name, side_by_side=None):
interval = 'month'
split_start = start.split('/')
split_end = end.split('/')
start_date = datetime.datetime(int(split_start[2]), int(split_start[0]), int(split_start[1]))
end_date = datetime.datetime(int(split_end[2]), int(split_end[0]), int(split_end[1]))
months_hash = generate_dates(start_date, end_date, interval)
edw2_request_copy = copy.deepcopy(edw2_request_object)
edw3_request_copy = copy.deepcopy(edw3_request_object)
# print('EDW2 - RO === \n ', edw2_request_copy, '\n')
# print('EDW3 - RO === \n ', edw3_request_copy, '\n')
result = await loop_reports(months_hash, edw2_request_copy, edw3_request_copy, semaphore=3, interval="month",
output_xlsx=True, report_name=cascade_name, side_by_side=side_by_side,
cascade=True, cascade_start_date=start, cascade_end_date=end)
for month_comparison in result:
months_comp.append(month_comparison.simple_difference_comparison)
print("appending month sbs, " , len(months_comp))
await cascade_weeks(
month_comparison.comparison_start_date,
month_comparison.comparison_end_date,
edw2_request_object,
edw3_request_object,
cascade_name,
side_by_side=side_by_side
)
months_summary_dict["comparisons"].extend(result)
print("months summary list length -- ", len(months_summary_dict["comparisons"]))
print("weeks summary list length -- ", len(weeks_summary_dict["comparisons"]))
print("days summary list length -- ", len(days_summary_dict["comparisons"]))
summaries = [days_summary_dict, weeks_summary_dict, months_summary_dict]
await write_summary(summaries, cascade_name)
if side_by_side:
await write_side_by_side(cascade_name)
async def cascade_weeks(start, end, edw2_request_object, edw3_request_object, cascade_name,
side_by_side=None):
interval = 'week'
split_start = start.split('/')
split_end = end.split('/')
start_date = datetime.datetime(int(split_start[2]), int(split_start[0]), int(split_start[1]))
end_date = datetime.datetime(int(split_end[2]), int(split_end[0]), int(split_end[1]))
weeks_hash = generate_dates(start_date, end_date, interval)
edw2_request_copy = copy.deepcopy(edw2_request_object)
edw3_request_copy = copy.deepcopy(edw3_request_object)
result = await loop_reports(weeks_hash, edw2_request_copy, edw3_request_copy, semaphore=3, interval="week",
output_xlsx=True, report_name=cascade_name, side_by_side=side_by_side,
cascade=True, cascade_start_date=start, cascade_end_date=end)
for week_comparison in result:
weeks_comp.append(week_comparison.side_by_side)
print("appending week sbs, ", len(weeks_comp))
await cascade_days(
week_comparison.comparison_start_date,
week_comparison.comparison_end_date,
edw2_request_object,
edw3_request_object,
cascade_name,
side_by_side=side_by_side
)
weeks_summary_dict["comparisons"].extend(result)
async def cascade_days(start, end, edw2_request_object, edw3_request_object, cascade_name,
side_by_side=None):
interval = 'day'
split_start = start.split('/')
split_end = end.split('/')
start_date = datetime.datetime(int(split_start[2]), int(split_start[0]), int(split_start[1]))
end_date = datetime.datetime(int(split_end[2]), int(split_end[0]), int(split_end[1]))
days_hash = generate_dates(start_date, end_date, interval)
edw2_request_copy = copy.deepcopy(edw2_request_object)
edw3_request_copy = copy.deepcopy(edw3_request_object)
result = await loop_reports(days_hash, edw2_request_copy, edw3_request_copy, semaphore=3, interval="day",
output_xlsx=True, report_name=cascade_name, side_by_side=side_by_side,
cascade=True, cascade_start_date=start, cascade_end_date=end)
days_summary_dict["comparisons"].extend(result)
if side_by_side:
for day_comparison in result:
days_comp.append(day_comparison.side_by_side)
print("appending days sbs, ", len(days_comp))
async def write_summary(list_of_comparison_dicts, cascade_name):
xlsx_name = './validation_outputs/xlsx/cascade/' + cascade_name + '/' + cascade_name + '_summary' '.xlsx'
wb = xlsxwriter.Workbook(xlsx_name)
format_r = wb.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
format_g = wb.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
for sum_idx, summary_dict in enumerate(list_of_comparison_dicts):
summary_name = summary_dict["interval"] + "_summary"
summary = wb.add_worksheet(summary_name)
inverted_summary = wb.add_worksheet(summary_name + '_inverted')
header_row = 0
col = 1
header_col = 0
row = 1
for comp_idx, comparison in enumerate(list_of_comparison_dicts[sum_idx]["comparisons"]):
if comparison is None or comparison.passing_records is None:
# FIXME @le: instead of leaving passing_records to None when the load fails, it would be ideal to have it set to 0 or have some indication of an error
continue
output_string = {
"passing_records": len(comparison.passing_records),
"edw2_mismatches": len(comparison.edw2_mismatches),
"edw3_mismatches": len(comparison.edw3_mismatches),
"edw2_orphans": len(comparison.edw2_mismatches),
"edw3_orphans": len(comparison.edw3_orphans)
}
summary.write(header_row, col + 2,
list_of_comparison_dicts[sum_idx]["comparisons"][comp_idx].comparison_start_date)
inverted_summary.write(row + 2, header_col,
list_of_comparison_dicts[sum_idx]["comparisons"][comp_idx].comparison_start_date)
if len(comparison.edw3_orphans) or \
len(comparison.edw2_orphans) or \
len(comparison.edw2_mismatches) or \
len(comparison.edw3_mismatches):
cell_format = format_r
else:
cell_format = format_g
#
summary.write(1, comp_idx + 3, str(output_string), cell_format)
inverted_summary.write(comp_idx + 3, 1, str(output_string), cell_format)
col += 1
row += 1
summary.write(1, 0, list_of_comparison_dicts[0]["comparisons"][0].simple_report_name)
#
summary.write(1, 1,
str(list_of_comparison_dicts[0]["comparisons"][0].reports[0].request_object))
summary.write(1, 2,
str(list_of_comparison_dicts[0]["comparisons"][0].reports[1].request_object))
inverted_summary.write(0, 1, str(list_of_comparison_dicts[0]["comparisons"][0].simple_report_name))
# Write RO #1
inverted_summary.write(1, 1,
str(list_of_comparison_dicts[0]["comparisons"][0].reports[0].request_object))
# Write RO #2
inverted_summary.write(2, 1,
str(list_of_comparison_dicts[0]["comparisons"][0].reports[1].request_object))
print("summary has been added -- ", summary_name)
wb.close()
def upload_summary(cascade_name):
summary_directory = './validation_outputs/xlsx/cascade/' + cascade_name + '/' + cascade_name + '_summary' + '.xlsx'
summary_sheet_names = [
'month_summary',
'week_summary',
'day_summary'
]
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sheet = client.open("AvantLink Regression Validation Summary") # Open the spreadhseet
######
gsheet_month = sheet.worksheet("month_summary")
gsheet_week = sheet.worksheet("week_summary")
gsheet_day = sheet.worksheet("day_summary")
gsheet_month_inverted = sheet.worksheet("month_summary_inverted")
gsheet_week_inverted = sheet.worksheet("week_summary_inverted")
gsheet_day_inverted = sheet.worksheet("day_summary_inverted")
base = ['Report Name', 'EDW2 Req Obj.', 'EDW3 Req Obj.', 'Run Date', '']
start_date = datetime.datetime(2020, 1, 1)
end_date = datetime.datetime(2021, 12, 31)
months_dates = base.copy()
months_dates.extend(generate_dates(start_date, end_date, "month")["dates"])
weeks_dates = base.copy()
weeks_dates.extend(generate_dates(start_date, end_date, "week")["dates"])
days_dates = base.copy()
days_dates.extend(generate_dates(start_date, end_date, "day")["dates"])
# Write uninverted summaries to gSheets
# gsheet_month.insert_row(months_dates)
# gsheet_week.insert_row(weeks_dates)
# gsheet_day.insert_row(days_dates)
# write inverted summary to gsheet
days_dates.reverse()
weeks_dates.reverse()
months_dates.reverse()
data = load_workbook(summary_directory)
# Iterate through the data of each local spreadsheet summary
for sheet_name in summary_sheet_names:
row_list = data[sheet_name].iter_rows(values_only=True)
for row_idx, row in enumerate(row_list):
if row_idx == 0:
pass
else:
current_date = arrow.utcnow().format()
current_gsheet = sheet.worksheet(sheet_name)
current_row_local = list(row)
current_row_local.insert(3, current_date)
current_row_local.insert(4, '')
new_gsheet_row = current_gsheet.insert_row(current_row_local)
async def write_side_by_side(cascade_name):
print("Lengths within Side_by_side(),", len(months_comp), len(weeks_comp), len(days_comp))
list_of_comparison_dicts = [
{'interval': 'month', 'dataframe_set_list': months_comp},
{'interval': 'day', 'dataframe_set_list': days_comp},
{'interval': 'week', 'dataframe_set_list': weeks_comp}
]
# months_comp list[{}]
xlsx_name = './validation_outputs/xlsx/cascade/' + cascade_name + '/' + \
cascade_name + '_difference_summary' '.xlsx'
storage = {"month": [], "week": [], "day": []}
for idx_1, interval_obj in enumerate(list_of_comparison_dicts):
SBS_gathered = {
"merge": [],
# "mismatches_combined": [],
# "edw2_raw": [],
# "edw3_raw": [],
# "orphans_merged": [],
# "matches": [],
# "edw2_mismatches": [],
# "edw3_mismatches": [],
# "edw2_orphans": [],
# "edw3_orphans": []
}
for sbs_set in interval_obj["dataframe_set_list"]:
try:
# FIXME
for key in sbs_set:
SBS_gathered[key].append(sbs_set[key])
except KeyError:
pass
for list_key in SBS_gathered.keys():
# print('DFLIST === , ', df_list)
# print("length == ", len(SBS_gathered[list_key]), list_of_comparison_dicts[idx_1]["interval"])
result = pd.concat(SBS_gathered[list_key], ignore_index=True)
sheet_name = list_of_comparison_dicts[idx_1]["interval"] + "_" + list_key
storage[list_of_comparison_dicts[idx_1]["interval"]].append({"dataframe": result, "sheet_name": sheet_name})
with pd.ExcelWriter(xlsx_name) as writer:
for interval in storage:
for idx, sheet in enumerate(storage[interval]):
storage[interval][idx]["dataframe"].to_excel(writer, sheet_name=storage[interval][idx]["sheet_name"])
def run_cascade(start_date, end_date, edw2_request_object, edw3_request_object,
report_name="custom_comparison", side_by_side=None):
loop = asyncio.new_event_loop()
sem = None
try:
loop.run_until_complete(
cascade_months(
start_date,
end_date,
edw2_request_object,
edw3_request_object,
report_name,
side_by_side=side_by_side
))
except KeyboardInterrupt:
pass
finally:
loop.close()
pass
| CodeBlackwell/Incomparable | DataValidation/sources/semaphore_methods.py | semaphore_methods.py | py | 26,468 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "warnings.filterwarnings",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "gspread.utils",
"line_number": 39,
"usage_type": "attribute"
},
{
"api_name": "oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name",
"line_number": 42,... |
1749907675 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function,
unicode_literals, division)
from itertools import chain
from namedlist import namedtuple, NO_DEFAULT
from six import iteritems, iterkeys
from .api import kv_format_pairs
def _validate_filters(fields, filters):
for field in iterkeys(filters):
if field in fields:
continue
raise TypeError(("extra filter for unexpected filter '{0}'"
.format(field)))
return filters.copy()
class KvFormatter(object):
"""Predefine a list of fields with optional default values and filters.
The resulting object allows to reuse the field names for formatting
purpose when called.
"""
def __init__(self, field_names, default=NO_DEFAULT, filters=None):
self.args_tuple = namedtuple('_ArgsTuple', field_names, default)
self.fields = self.args_tuple._fields
self.filters = (_validate_filters(self.fields, filters)
if filters else {})
def pairs(self, *args, **kwargs):
items = dict((k, self.filters.get(k, lambda a: a)(v))
for k, v in chain(zip(self.fields, args),
iteritems(kwargs)))
return zip(self.fields, self.args_tuple(**items))
def __call__(self, *args, **kwargs):
return kv_format_pairs(self.pairs(*args, **kwargs))
| eisensheng/kaviar | kaviar/functools.py | functools.py | py | 1,432 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "six.iterkeys",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "namedlist.NO_DEFAULT",
"line_number": 27,
"usage_type": "name"
},
{
"api_name": "namedlist.namedtuple",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "itertools.chai... |
4185172909 | from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
| jetbrains-academy/pycharm-courses | DjangoTutorial_v3.5/lesson1/task1/blog/models.py | models.py | py | 476 | python | en | code | 232 | github-code | 36 | [
{
"api_name": "django.db.models.Model",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "django.db.models",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "django.db.models.ForeignKey",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": ... |
73335955623 | from unittest import TestCase
from adsws.api.discoverer import affinity
from flask.ext.restful import Resource
import flask
from flask_restful import Resource, Api
import mock
class SetCookieView(Resource):
"""
Returns a good HTTP answer with a coockie set in the headers
"""
storage = None
@affinity.affinity_decorator(storage, name="sroute")
def get(self):
return {}, 200, {'Set-Cookie': 'sroute=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; Path=/; HttpOnly'}
class DontSetCookieView(Resource):
"""
Returns a good HTTP answer without any coockie set in the headers
"""
storage = None
@affinity.affinity_decorator(storage, name="sroute")
def get(self):
return {}, 200, {}
class AffinityRouteTestCase(TestCase):
"""
Tests solr route decorator
"""
def setUp(self):
super(self.__class__, self).setUp()
app = flask.Flask(__name__)
api = Api(app)
api.add_resource(SetCookieView, '/set_cookie')
api.add_resource(DontSetCookieView, '/dont_set_cookie')
self.app = app.test_client()
def tearDown(self):
super(self.__class__, self).tearDown()
def test_set_cookie(self):
"""
Test that the cookie is set
"""
affinity._get_route = mock.Mock(return_value="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
affinity._set_route = mock.Mock()
rv = self.app.get('/set_cookie', headers=[['Authorization', "Bearer:TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"]])
self.assertIn('Set-Cookie', rv.headers)
self.assertEquals(rv.headers['Set-Cookie'], 'sroute=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; Path=/; HttpOnly')
affinity._get_route.assert_called_once()
affinity._set_route.assert_called_once()
def test_set_cookie(self):
"""
Test that no cookie is set
"""
affinity._get_route = mock.Mock(return_value=None)
affinity._set_route = mock.Mock()
rv = self.app.get('/dont_set_cookie', headers=[['Authorization', "Bearer:TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"]])
self.assertNotIn('Set-Cookie', rv.headers)
affinity._get_route.assert_called_once()
affinity._set_route.assert_not_called()
| adsabs/adsws | adsws/tests/test_affinity.py | test_affinity.py | py | 2,266 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "flask_restful.Resource",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "adsws.api.discoverer.affinity.affinity_decorator",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "adsws.api.discoverer.affinity",
"line_number": 13,
"usage_type": "... |
938525732 | from torch.utils.data import DataLoader
import logging
import formatter as form
from dataset import dataset_list
logger = logging.getLogger(__name__)
collate_fn = {}
formatter = {}
def init_formatter(config, task_list, *args, **params):
for task in task_list:
formatter[task] = form.init_formatter(config, task, *args, **params)
def train_collate_fn(data):
return formatter["train"].process(data, config, "train")
def valid_collate_fn(data):
return formatter["valid"].process(data, config, "valid")
def test_collate_fn(data):
return formatter["test"].process(data, config, "test")
if task == "train":
collate_fn[task] = train_collate_fn
elif task == "valid":
collate_fn[task] = valid_collate_fn
else:
collate_fn[task] = test_collate_fn
def init_one_dataset(config, mode, *args, **params):
temp_mode = mode
if mode != "train":
try:
config.get("data", "%s_dataset_type" % temp_mode)
except Exception as e:
logger.warning(
"[reader] %s_dataset_type has not been defined in config file, use [dataset] train_dataset_type instead." % temp_mode)
temp_mode = "train"
which = config.get("data", "%s_dataset_type" % temp_mode)
if which in dataset_list:
dataset = dataset_list[which](config, mode, *args, **params)
batch_size = config.getint("train", "batch_size")
shuffle = config.getboolean("train", "shuffle")
reader_num = config.getint("train", "reader_num")
drop_last = True
if mode in ["valid", "test"]:
if mode == "test":
drop_last = False
try:
batch_size = config.getint("eval", "batch_size")
except Exception as e:
logger.warning("[eval] batch size has not been defined in config file, use [train] batch_size instead.")
try:
shuffle = config.getboolean("eval", "shuffle")
except Exception as e:
shuffle = False
logger.warning("[eval] shuffle has not been defined in config file, use false as default.")
try:
reader_num = config.getint("eval", "reader_num")
except Exception as e:
logger.warning("[eval] reader num has not been defined in config file, use [train] reader num instead.")
dataloader = DataLoader(dataset=dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=reader_num,
collate_fn=collate_fn[mode],
drop_last=drop_last)
return dataloader
else:
logger.error("There is no dataset called %s, check your config." % which)
raise NotImplementedError
def init_test_dataset(config, *args, **params):
init_formatter(config, ["test"], *args, **params)
test_dataset = init_one_dataset(config, "test", *args, **params)
return test_dataset
def init_dataset(config, *args, **params):
init_formatter(config, ["train", "valid"], *args, **params)
train_dataset = init_one_dataset(config, "train", *args, **params)
valid_dataset = init_one_dataset(config, "valid", *args, **params)
return train_dataset, valid_dataset
if __name__ == "__main__":
pass
| china-ai-law-challenge/CAIL2020 | sfks/baseline/reader/reader.py | reader.py | py | 3,478 | python | en | code | 150 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "formatter.init_formatter",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "dataset.dataset_list",
"line_number": 45,
"usage_type": "name"
},
{
"api_name": "datase... |
17013150761 | # -*- coding: UTF-8 -*-
from __future__ import absolute_import, division, print_function
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # 这一行注释掉就是使用cpu,不注释就是使用gpu
import pathlib
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
import json
from keras.models import load_model
from keras.utils import CustomObjectScope
from keras.initializers import glorot_uniform
dataLocation = '../results/'
resultSaveLocation = '../RESULTS/DeepLearning_val'
if not os.path.exists(resultSaveLocation):
os.makedirs(resultSaveLocation)
data2 = pd.read_csv(dataLocation + 'nanorod_smote_dupshu.csv')
data2VariableNames = data2.columns.tolist()
feaColums = data2VariableNames[1:4]
indSmote = data2VariableNames[-1]
label_one = data2VariableNames[-2]
lr = 0.001
dense_size = 64
validation_split = 0.2
resultSaveLocation = resultSaveLocation + '/' + str(lr) + '/' + str(dense_size) + '/' + label_one + '/'
if not os.path.exists(resultSaveLocation):
os.makedirs(resultSaveLocation)
data2Del = data2.drop_duplicates(subset=feaColums,keep='first',inplace=False)
ind_smote = data2Del[indSmote]
X = np.array(data2Del[feaColums])
Y = np.array(data2Del[label_one])
Y = np.reshape(Y,[-1,1])
nfold = 10
kf = KFold(n_splits=nfold, shuffle = False, random_state=1)
ss = StandardScaler( )
inputsize = X.shape[1]
def build_model ():
model = keras.Sequential([
layers.Dense(dense_size, activation=tf.nn.relu, input_shape=[inputsize]),
layers.Dense(dense_size, activation=tf.nn.relu),
layers.Dense(1)
])
optimizer = tf.keras.optimizers.RMSprop(lr)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae', 'mse'])
return model
model = build_model( )
model.summary( )
nfold_train_data = []
nfold_train_Y = []
nfold_test_data = []
nfold_test_Y = []
nfold_test_ind = []
for train, test in kf.split(X):
train_X = X[train]
train_Y = Y[train]
test_X = X[test]
test_Y = Y[test]
# train_ind = ind_smote[train]
test_ind = ind_smote[test]
train_X = ss.fit_transform(train_X)
test_X = ss.transform(test_X)
nfold_train_data.append(train_X)
nfold_train_Y.append(train_Y)
nfold_test_data.append(test_X)
nfold_test_Y.append(test_Y)
nfold_test_ind.append(test_ind)
# Display training progress by printing a single dot for each completed epoch
class PrintDot(keras.callbacks.Callback):
def on_epoch_end (self, epoch, logs):
if epoch % 100 == 0: print('')
print('.', end='')
EPOCHS = 1000
Ytest =[]
Yhat = []
import matplotlib.pyplot as plt
def plot_history (history,ncv):
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.figure( )
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [MPG]')
plt.plot(hist['epoch'], hist['mean_absolute_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_absolute_error'],
label='Val Error')
plt.legend( )
plt.ylim([0, 5])
plt.savefig(resultSaveLocation + str(EPOCHS) +'_'+ str(ncv+1) +'_' + str(validation_split) + '_mae.pdf')
plt.figure( )
plt.xlabel('Epoch')
plt.ylabel('Mean Square Error [$MPG^2$]')
plt.plot(hist['epoch'], hist['mean_squared_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_squared_error'],
label='Val Error')
plt.legend( )
plt.ylim([0, 20])
plt.savefig(resultSaveLocation + str(EPOCHS) +'_'+ str(i+1) +'_'+ str(validation_split) + '_mse.pdf')
loss_cv = []
mae_cv = []
mse_cv = []
ind_cv = []
r2_cv = []
for i in range(nfold):
X = nfold_train_data[i]
Y = nfold_train_Y[i]
Xt = nfold_test_data[i]
Yt = nfold_test_Y[i]
ind_test = nfold_test_ind[i]
model = build_model( )
history = model.fit(
X, Y,
epochs=EPOCHS, validation_split=validation_split, verbose=0,
callbacks=[PrintDot( )])
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
print(hist.tail())
plot_history(history,i)
# The patience parameter is the amount of epochs to check for improvement
# early_stop = keras.callbacks.EarlyStopping(monitor='val_loss' , patience=10)
loss, mae, mse = model.evaluate(Xt, Yt, verbose=0)
print("Testing set Mean Abs Error: {:5.2f} MPG".format(mae))
loss_cv.append(loss)
mae_cv.append(mae)
mse_cv.append(mse)
# test_predictions = model.predict(nfold_test_data[i]).flatten()
Yhati = model.predict(Xt)
model.save(resultSaveLocation+label_one+ str(EPOCHS) + '_' + str(validation_split) + '_CV' + str(i) + '_model.h5')
r2 = r2_score(Yhati , Yt)
r2_cv.append(r2)
Ytest.append(Yt.flatten())
Yhat.append(Yhati.flatten())
ind_cv.append(np.array(ind_test))
Ytestj = [list(str(iitem) for iitem in item) for item in Ytest]
Yhatj = [list(str(iitem) for iitem in item) for item in Yhat]
indj = [list(str(iitem) for iitem in item) for item in ind_cv]
results = {'Ytest':Ytestj,'Yhat':Yhatj,'ind_smote':indj}
with open(resultSaveLocation + label_one + str(EPOCHS) + '_' + str(validation_split) + '_results.json', 'w') as f:
json.dump(results, f)
loss_cv.append(str(np.mean(loss_cv)) + '+-' + str(np.std(loss_cv)))
mae_cv.append(str(np.mean(mae_cv)) + '+-' + str(np.std(mae_cv)))
mse_cv.append(str(np.mean(mse_cv)) + '+-' + str(np.std(mse_cv)))
r2_cv.append(str(np.mean(r2_cv)) + '+-' + str(np.std(r2_cv)))
measures = np.concatenate((np.reshape(loss_cv,(-1,1)),np.reshape(mae_cv,(-1,1)),np.reshape(mse_cv,(-1,1)),np.reshape(r2_cv,(-1,1))),axis=1)
measures = pd.DataFrame(measures)
measures.columns = ['loss','mae','mse','r2']
measures.to_csv(resultSaveLocation+label_one+ str(EPOCHS) + '_' + str(validation_split) +'_measures.csv')
Ytests = Ytest[0]
Yhats = Yhat[0]
inds = ind_cv[0]
for i in range(nfold-1):
Ytests = np.concatenate((Ytests,Ytest[i+1]),axis=0)
Yhats = np.concatenate((Yhats,Yhat[i+1]),axis=0)
inds = np.concatenate((inds,ind_cv[i+1]),axis=0)
resultsY = np.concatenate((np.reshape(Ytests,(-1,1)),np.reshape(Yhats,(-1,1)),np.reshape(inds,(-1,1))),axis=1)
resultsY = pd.DataFrame(resultsY)
resultsY.columns = ['Ytest','Yhat','ind_smote']
resultsY.to_csv(resultSaveLocation+ str(EPOCHS) + '_' + str(validation_split) +'_resultsY.csv')
import utils.myplots as myplots
myplots.scatterresults(Ytests, Yhats,'Deep Learning',str(EPOCHS) +'_' + str(validation_split) + '_' + label_one, resultSaveLocation)
| jiali1025/SMOTE-REG | code/nano_dl_keras_smote.py | nano_dl_keras_smote.py | py | 6,754 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.environ",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "os.environ",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "os.path.exists",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_numb... |
70718371624 | import os
import sys
import cv2
import subprocess
from tkinter import Tk, Frame, Button, Label, Entry
from tkinter import filedialog, colorchooser
from math import sqrt
from mosaic import MosaicGenerator
class Window(Frame):
"""
The tkinter window and logic
"""
def __init__(self, parent):
"""
:param parent: the tkinter parent
"""
self.parent = parent
super(Window, self).__init__(parent)
self.ridge_color = (0, 0, 0)
self.initUI()
def initUI(self):
"""
Inits the tkinter-elements in a grid form
"""
#TODO: Naming rows....
# ----------1. Row---------- #
filepath_label = Label(self, text="Image file path:")
filepath_label.grid(row=0, column=0, rowspan=1, sticky="w")
self.path_entry = Entry(self, width=30)
self.path_entry.grid(row=0, column=1, rowspan=1, columnspan=2, sticky="w")
choose_btn = Button(self, text="Load Image", command=self.fileDialog)
choose_btn.grid(row=0, column=3, rowspan=1, columnspan=1)
# ----------2.Row---------- #
tilenum_label = Label(self, text="Number of Mosaic Tiles:")
tilenum_label.grid(row=1, column=0, rowspan=1, columnspan=1, sticky="w")
self.tilenum_entry = Entry(self)
self.tilenum_entry.insert(0, "100000")
self.tilenum_entry.grid(row=1, column=1, rowspan=1, columnspan=1)
self.pixel_label = Label(self, text="")
self.pixel_label.grid(row=1, column=2, rowspan=1, columnspan=1)
# ----------3.Row---------- #
colorrand_label = Label(self, text="Color randomization (0.01 = 1%):")
colorrand_label.grid(row=2, column=0, rowspan=1, columnspan=1, sticky="e")
self.colorrand_factor = Entry(self)
self.colorrand_factor.insert(0, "0.00")
self.colorrand_factor.grid(row=2, column=1, rowspan=1, columnspan=1)
# ----------4.Row---------- #
intensity_label = Label(self, text="Color Intensity:")
intensity_label.grid(row=3, column=0, rowspan=1, columnspan=1, sticky="w")
self.intensity_factor_entry = Entry(self)
self.intensity_factor_entry.insert(0, "1.0")
self.intensity_factor_entry.grid(row=3, column=1, rowspan=1, columnspan=1)
# ----------5.Row---------- #
ridgeclr_label = Label(self, text="Color of Tile outline:")
ridgeclr_label.grid(row=4, column=0, rowspan=1, columnspan=1, sticky="w")
self.ridgeclr_display = Label(self, bg='#%02x%02x%02x' % self.ridge_color, width=10) # Converts RGB to HEX
self.ridgeclr_display.grid(row=4, column=1, rowspan=1, columnspan=1, sticky="w")
ridgeclr_button = Button(self, text="Choose Color", command=self.colorChooser)
ridgeclr_button.grid(row=4, column=2, rowspan=1, columnspan=1)
# ----------6.Row---------- #
create_btn = Button(self, text="Create Mosaic", command=self.createMosaic)
create_btn.grid(row=5, column=0, rowspan=1, columnspan=1)
self.loading_label = Label(self, text="")
self.loading_label.grid(row=5, column=1, rowspan=1, columnspan=1)
# ----------7. Row---------- #
self.preview_btn = Button(self, text="Preview Image", command=self.prevImage, state="disabled")
self.preview_btn.grid(row=6, column=1, rowspan=1, columnspan=1)
self.save_btn = Button(self, text="Save Image", command=self.saveImage, state="disabled")
self.save_btn.grid(row=6, column=2, rowspan=1, columnspan=1)
def fileDialog(self):
"""
Opens a file dialog to choose a image to convert to a mosaic
"""
filepath = filedialog.askopenfilename(title="Select file", filetypes=[("Image files", ".jpg .png")])
self.path_entry.delete(0, 'end')
self.path_entry.insert(0, filepath)
self.img = cv2.imread(filepath)
# get dimensions of the image
self.x_size = self.img.shape[1]
self.y_size = self.img.shape[0]
self.pixel_label['text'] = str(self.x_size) + "x" + str(self.y_size) \
+ " = " + str(self.x_size * self.y_size) + " Pixels"
def colorChooser(self):
"""
Opens a color chooser dialog and sets the ridge_color
"""
openclr = self.ridge_color
selected_color = colorchooser.askcolor(self.ridge_color)
if selected_color[0]:
self.ridge_color = tuple([int(x) for x in selected_color[0]])
self.ridgeclr_display['bg'] = '#%02x%02x%02x' % self.ridge_color
def createMosaic(self):
"""
Creates a mosaic for the choosen image
"""
tilenum_str = self.tilenum_entry.get()
filepath_str = self.path_entry.get()
if not isint(tilenum_str):
self.loading_label['text'] = 'Tilenum not an integer'
return
if not os.path.isfile(filepath_str):
self.loading_label['text'] = 'Invalid filepath'
return
self.save_btn['state'] = 'normal'
self.save_btn.update()
self.preview_btn['state'] = 'normal'
self.preview_btn.update()
self.loading_label['text'] = "Loading..."
self.loading_label.update()
rand_factor = float(self.colorrand_factor.get())
intensity_factor = float(self.intensity_factor_entry.get())
mosaic = MosaicGenerator(self.x_size, self.y_size, int(tilenum_str), rand_factor=rand_factor,
intensity_factor=intensity_factor, ridge_color=self.ridge_color)
mosaic.calculateMosaic()
self.loading_label['text'] = "Save image"
self.loading_label.update()
mosaic.saveTempImage(self.img, "temp.jpg")
self.save_btn['state'] = 'normal'
self.preview_btn['state'] = 'normal'
self.loading_label['text'] = "Done!"
self.loading_label.update()
def showCanny(self):
grayscale = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(grayscale, int(self.mintreshold_entry.get()), int(self.maxtreshold_entry.get()))
cv2.imshow("Edges", cv2.resize(edges, (800, 600)))
def saveImage(self):
"""
Opens a save file dialog to save the mosaic
"""
save_path = filedialog.asksaveasfilename(title="Save Image", filetypes=[(".jpg", ".jpg")])
temp_file = open('temp.jpg', 'rb')
save_file = open(save_path + '.jpg', 'wb')
save_file.write(temp_file.read())
save_file.close()
temp_file.close()
self.loading_label['text'] = "Image saved!"
def prevImage(self):
"""
Opens a image viewer to preview the generated mosaic
"""
imageViewerFromCommandLine = {'linux': 'xdg-open',
'win32': 'explorer',
'darwin': 'open'}[sys.platform]
subprocess.run([imageViewerFromCommandLine, 'temp.jpg'])
def dist(p1, p2):
return sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def isint(s):
"""
Checks if string s is a integer
:param s: string to check
:return: True if s is a string, False otherwise
"""
try:
int(s)
return True
except ValueError:
return False
if __name__ == '__main__':
root = Tk(className=' Mosaic Generator')
main = Window(root)
main.pack(fill="both", expand=True)
root.mainloop()
# Remove temp file
if os.path.isfile('temp.jpg'):
os.remove('temp.jpg') | LFruth/MosaicGenerator | MosaicGenerator.py | MosaicGenerator.py | py | 7,563 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tkinter.Frame",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "tkinter.Label",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "tkinter.Entry",
"line_number": 37,
"usage_type": "call"
},
{
"api_name": "tkinter.Button",
"line_... |
37021411015 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_scatter as scatter
from modules.utils import MergeLayer_output, Feat_Process_Layer
from modules.embedding_module import get_embedding_module
from modules.time_encoding import TimeEncode
from model.gsn import Graph_sampling_network
from model.gpn import Graph_pruning_network
class TGAT(torch.nn.Module):
def __init__(self, config, embedding_module_type="graph_attention"):
super().__init__()
self.cfg = config
self.nodes_dim = self.cfg.input_dim
self.edge_dim = self.cfg.input_dim
self.dims = self.cfg.hidden_dim
self.n_heads = self.cfg.n_heads
self.dropout = self.cfg.drop_out
self.n_layers = self.cfg.n_layer
self.mode = self.cfg.mode
self.time_encoder = TimeEncode(dimension=self.dims)
self.embedding_module_type = embedding_module_type
self.embedding_module = get_embedding_module(module_type=embedding_module_type,
time_encoder=self.time_encoder,
n_layers=self.n_layers,
node_features_dims=self.dims,
edge_features_dims=self.dims,
time_features_dim=self.dims,
hidden_dim=self.dims,
n_heads=self.n_heads, dropout=self.dropout)
self.node_preocess_fn = Feat_Process_Layer(self.nodes_dim, self.dims)
self.edge_preocess_fn = Feat_Process_Layer(self.edge_dim, self.dims)
self.affinity_score = MergeLayer_output(self.dims, self.dims, drop_out=0.2)
self.predictor = nn.Sequential(nn.Linear(self.dims, self.dims)) # output layer
self.gsn = Graph_sampling_network(self.dims, self.cfg.batch_size, mask_ratio=self.cfg.prior_ratio)
self.edge_precom = Graph_pruning_network(self.edge_dim, self.dims, self.dropout)
def forward(self, src_org_edge_feat, src_edge_to_time, src_center_node_idx, src_neigh_edge, src_node_features):
# apply tgat
source_node_embedding, src_edge_feat = self.compute_temporal_embeddings(src_neigh_edge, src_edge_to_time,
src_org_edge_feat, src_node_features)
loclsrc_node_embedding = source_node_embedding[src_center_node_idx, :]
score = self.affinity_score(loclsrc_node_embedding, loclsrc_node_embedding)
return score
def forward_gsn(self, src_org_edge_feat, src_edge_to_time, src_center_node_idx, src_neigh_edge, src_node_features,
init_edge_index, batch_idx, step=0):
# apply tgat
source_node_embedding, src_edge_feat = self.compute_temporal_embeddings(src_neigh_edge, src_edge_to_time,
src_org_edge_feat, src_node_features)
loclsrc_node_embedding = source_node_embedding[src_center_node_idx,:]
source_node_embedding_clone = source_node_embedding
src_edge_feat_clone = src_edge_feat
time_encodding = self.time_encoder(src_edge_to_time)
src_edge_probs, src_edge_mask = self.gsn.forward(source_node_embedding_clone, src_neigh_edge, time_encodding,
src_edge_feat_clone, batch_idx, src_center_node_idx)
gsn_node_embedding, _ = self.compute_temporal_embeddings(src_neigh_edge, src_edge_to_time,
src_org_edge_feat, src_node_features,
None, src_edge_probs)
gsnsrc_node_embedding = gsn_node_embedding[src_center_node_idx, :]
unique_edge_label = self.Merge_same_edge(init_edge_index, src_edge_mask)
temp_edge_label = unique_edge_label.long()
edge_logit = self.edge_precom(src_org_edge_feat)
loss_edge_pred = self.edge_precom.loss(edge_logit.reshape([-1, 2]), temp_edge_label)
loss_sparse = self.gsn.sparse_loss(src_edge_probs)
loss_mi = self.ddgcl(loclsrc_node_embedding, gsnsrc_node_embedding)
max_probs = torch.max(src_edge_probs)
min_probs = torch.min(src_edge_probs)
return {'loss': loss_mi, 'loss_sparse': loss_sparse, 'loss_edge_pred':loss_edge_pred,
'edge_index': src_neigh_edge, 'edge_probs': src_edge_probs,
'max_probs':max_probs, 'min_probs':min_probs}
def compute_temporal_embeddings(self, neigh_edge, edge_to_time, edge_feat, node_feat, edge_mask=None, sample_ratio=None):
node_feat = self.node_preocess_fn(node_feat)
edge_feat = self.edge_preocess_fn(edge_feat)
node_embedding = self.embedding_module.compute_embedding(neigh_edge, edge_to_time,
edge_feat, node_feat, edge_mask, sample_ratio)
return node_embedding, edge_feat
def ddgcl(self, x1, x2):
x1 = self.predictor(x1)
l_pos = torch.sigmoid(torch.sum(x1 * x2, dim=-1)).reshape([-1, 1])
l_neg = torch.sigmoid(torch.sum(torch.einsum('nc,kc->nkc', x1, x2), dim=-1))
matrix = torch.diag_embed(torch.diag(l_neg))
l_neg = l_neg - matrix
label1 = torch.ones_like(l_pos)
label2 = torch.zeros_like(l_neg)
logits = torch.cat([l_pos, l_neg], dim=1).reshape([-1])
labels = torch.cat([label1, label2], dim=1).reshape([-1])
loss_bce = torch.nn.BCELoss()
loss = loss_bce(logits, labels)
return loss
def Merge_same_edge(self, init_edge_index, src_edge_mask):
output, _ = scatter.scatter_max(src_edge_mask, init_edge_index, dim=0)
output = output[init_edge_index]
return output | EdisonLeeeee/STEP | src/model/tgat.py | tgat.py | py | 5,947 | python | en | code | 6 | github-code | 36 | [
{
"api_name": "torch.nn",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "modules.time_encoding.TimeEncode",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "modules.embedding_module.get_embedding_module",
"line_number": 29,
"usage_type": "call"
... |
7946726176 | import torch.nn as nn
import torch
class BasicBlock(nn.Module): # 18-layers、34-layers
exception = 1
def __init__(self, in_channels, out_channles, stride=1, downsample=None, **kwargs):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channles,
kernel_size=3, stride=stride, padding=1, bias=False)
self.b1 = nn.BatchNorm2d(out_channles)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(in_channels=out_channles, out_channels=out_channles,
kernel_size=3, stride=1, padding=1, bias=False)
self.b2 = nn.BatchNorm2d(out_channles)
self.downsample = downsample
def forward(self, x):
identify = x
if self.downsample is not None:
identify = self.downsample(x)
out = self.conv1(x)
out = self.b1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.b2(out)
out += identify
out = self.relu(out)
return out
class Bottleneck(nn.Module): # 具体操作和ResNet网络一致,不过卷积换成了层卷积
exception = 4
def __init__(self, in_channel, out_channel, stride=1, downsample=None,
groups=1, width_per_group=64):
super(Bottleneck, self).__init__()
width = int(out_channel * (width_per_group / 64.)) * groups
self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=width,
kernel_size=1, stride=1, bias=False) # squeeze channels
self.bn1 = nn.BatchNorm2d(width)
self.conv2 = nn.Conv2d(in_channels=width, out_channels=width, groups=groups,
kernel_size=3, stride=stride, bias=False, padding=1)
self.bn2 = nn.BatchNorm2d(width)
self.conv3 = nn.Conv2d(in_channels=width, out_channels=out_channel*self.exception,
kernel_size=1, stride=1, bias=False) # unsqueeze channels
self.bn3 = nn.BatchNorm2d(out_channel*self.exception)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, x):
identity = x
if self.downsample is not None:
identity = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, block_num, num_class=1000, include_top=True, group=1, wid_per_group=64):
super(ResNet, self).__init__()
self.group = group
self.wid_per_group = wid_per_group
self.include_top = include_top
self.in_channel = 64
self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7,
stride=2, padding=3, bias=False)
self.b1 = nn.BatchNorm2d(self.in_channel)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self.make_layer(block, 64, block_num[0])
self.layer2 = self.make_layer(block, 128, block_num[1], stride=2)
self.layer3 = self.make_layer(block, 256, block_num[2], stride=2)
self.layer4 = self.make_layer(block, 512, block_num[3], stride=2)
if self.include_top:
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512*block.exception, num_class)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
def make_layer(self, block, channel, block_num, stride=1):
downsample = None
if stride != 1 or self.in_channel != channel*block.exception:
downsample = nn.Sequential(
nn.Conv2d(self.in_channel, channel*block.exception,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(channel*block.exception))
layer = []
layer.append(block(self.in_channel, channel, downsample=downsample, stride=stride,
groups=self.group, width_per_group=self.wid_per_group))
self.in_channel = channel*block.exception
for _ in range(1, block_num):
layer.append(block(self.in_channel, channel,
groups=self.group, width_per_group=self.wid_per_group))
return nn.Sequential(*layer)
def forward(self, x):
x = self.conv1(x)
x = self.b1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
if self.include_top:
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def Resnext50(num_class=1000, include_top=True):
group = 32
wid_per_group = 4
return ResNet(Bottleneck, [3, 4, 6, 3],
num_class=num_class,
include_top=include_top,
group=group,
wid_per_group=wid_per_group
)
| yedupeng/Artificial_Model | ResNext/ResNext_Model.py | ResNext_Model.py | py | 5,475 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "torch.nn.Module",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "torch.nn.Conv2d",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_numbe... |
73894836904 | # -*- coding: utf-8
"""
File containing ConfigObject.
"""
from __future__ import division, print_function, unicode_literals
### Logging ###
import logging
_logger = logging.getLogger("ConfigUtils")
###############
import os
import sys
from ast import literal_eval
try:
import configparser
except ImportError:
# python2 fallback
import ConfigParser as configparser
from gi.repository import Gio
from Onboard.Exceptions import SchemaError
from Onboard.utils import pack_name_value_list, unpack_name_value_list, \
unicode_str
_CAN_SET_HOOK = "_can_set_" # return true if value is valid
_GSETTINGS_GET_HOOK = "_gsettings_get_" # retrieve from gsettings
_GSETTINGS_SET_HOOK = "_gsettings_set_" # store into gsettings
_POST_NOTIFY_HOOK = "_post_notify_" # runs after all listeners notified
_NOTIFY_CALLBACKS = "_{}_notify_callbacks" # name of list of callbacka
class ConfigObject(object):
"""
Class for a configuration object with multiple key-value tuples.
It aims to unify the handling of python properties, gsettings keys,
system default keys and command line options.
Python properties and notification functions are created
automagically for all keys added in _init_keys().
"""
def __init__(self, parent = None, schema = ""):
self.parent = parent # parent ConfigObject
self.children = [] # child config objects; not necessarily
# reflecting the gsettings hierarchy
self.schema = schema # schema-path to the gsettings object
self.gskeys = {} # key-value objects {property name, GSKey()}
self.sysdef_section = None # system defaults section name
self.system_defaults = {} # system defaults {property name, value}
# add keys in here
self._init_keys()
# check if the gsettings schema is installed
if not self.schema in Gio.Settings.list_schemas():
raise SchemaError(_("gsettings schema for '{}' is not installed").
format(self.schema))
# create gsettings object and its python properties
self.settings = Gio.Settings.new(self.schema)
for gskey in list(self.gskeys.values()):
gskey.settings = self.settings
self._setup_property(gskey)
# check hook function names
self.check_hooks()
def _init_keys(self):
""" overload this and use add_key() to add key-value tuples """
pass
def add_key(self, key, default, prop = None, sysdef = None,
writable = True):
""" Convenience function to create and add a new GSKey. """
gskey = GSKey(None, key, default, prop, sysdef, writable)
self.gskeys[gskey.prop] = gskey
return gskey
def find_key(self, key):
""" Search for key (gsettings name) """
for gskey in self.gskeys.values():
if gskey.key == key:
return gskey
return None
def get_root(self):
""" Return the root config object """
co = self
while co:
if co.parent is None:
return co
co = co.parent
def check_hooks(self):
"""
Simple runtime plausibility check for all overloaded hook functions.
Does the property part of the function name reference an existing
config property?
"""
prefixes = [_CAN_SET_HOOK,
_GSETTINGS_GET_HOOK,
_GSETTINGS_SET_HOOK,
_POST_NOTIFY_HOOK]
for member in dir(self):
for prefix in prefixes:
if member.startswith(prefix):
prop = member[len(prefix):]
if not prop in self.gskeys:
# no need for translation
raise NameError(
"'{}' looks like a ConfigObject hook function, but "
"'{}' is not a known property of '{}'"
.format(member, prop, str(self)))
def disconnect_notifications(self):
""" Recursively remove all callbacks from all notification lists. """
for gskey in list(self.gskeys.values()):
prop = gskey.prop
setattr(type(self), _NOTIFY_CALLBACKS.format(prop), [])
for child in self.children:
child.disconnect_notifications()
def _setup_property(self, gskey):
""" Setup python property and notification callback """
prop = gskey.prop
# list of callbacks
setattr(type(self), _NOTIFY_CALLBACKS.format(prop), [])
# method to add callback
def _notify_add(self, callback, _prop=prop):
""" method to add a callback to this property """
getattr(self, _NOTIFY_CALLBACKS.format(prop)).append(callback)
setattr(type(self), prop+'_notify_add', _notify_add)
# method to remove a callback
def _notify_remove(self, callback, _prop=prop):
""" method to remove a callback from this property """
try:
getattr(self, _NOTIFY_CALLBACKS.format(prop)).remove(callback)
except ValueError:
pass
setattr(type(self), prop+'_notify_remove', _notify_remove)
# gsettings callback
def _notify_changed_cb(self, settings, key, _gskey=gskey, _prop=prop):
""" call back function for change notification """
# get-gsettings hook, for reading values from gsettings
# in non-standard ways, i.e. convert data types.
if hasattr(self, _GSETTINGS_GET_HOOK +_prop):
value = getattr(self, _GSETTINGS_GET_HOOK +_prop)(_gskey)
else:
value = _gskey.gsettings_get()
# Can-set hook, for value validation.
if not hasattr(self, _CAN_SET_HOOK + _prop) or \
getattr(self, _CAN_SET_HOOK + _prop)(value):
if _gskey.value != value:
_gskey.value = value
if False:
# asynchronous callbacks
def notify(callbacks, value):
for callback in callbacks:
callback(value)
GObject.idle_add(notify,
getattr(self, _NOTIFY_CALLBACKS.format(prop)),
value)
else:
for callback in getattr(self, _NOTIFY_CALLBACKS.format(prop)):
callback(value)
# Post-notification hook for anything that properties
# need to do after all listeners have been notified.
if hasattr(self, _POST_NOTIFY_HOOK + _prop):
getattr(self, _POST_NOTIFY_HOOK + _prop)()
setattr(type(self), '_'+prop+'_changed_cb', _notify_changed_cb)
# connect callback function to gsettings
if gskey.settings:
gskey.settings.connect("changed::"+gskey.key,
getattr(self, '_'+prop+'_changed_cb'))
# getter function
def get_value(self, _gskey = gskey, _prop = prop):
""" property getter """
return _gskey.value
# setter function
def set_value(self, value, save = True, _gskey = gskey, _prop = prop):
""" property setter """
# can-set hook, for value validation
if not hasattr(self, _CAN_SET_HOOK +_prop) or \
getattr(self, _CAN_SET_HOOK +_prop)(value):
if save:
# save to gsettings
if hasattr(self, _GSETTINGS_SET_HOOK + _prop):
# gsettings-set hook, custom value setter
getattr(self, _GSETTINGS_SET_HOOK +_prop)(_gskey, value)
else:
#if value != _gskey.gsettings_get():
if value != _gskey.value:
_gskey.gsettings_set(value)
_gskey.value = value
# create propery
if not hasattr(self, 'get_'+prop): # allow overloading
setattr(type(self), 'get_'+prop, get_value)
if not hasattr(self, 'set_'+prop): # allow overloading
setattr(type(self), 'set_'+prop, set_value)
setattr(type(self), prop,
property(getattr(type(self), 'get_'+prop),
getattr(type(self), 'set_'+prop)))
def init_properties(self, options):
""" initialize the values of all properties """
# start from hard coded defaults, then try gsettings
self.init_from_gsettings()
# let system defaults override gsettings
if self.use_system_defaults:
self.init_from_system_defaults()
self.use_system_defaults = False # write to gsettings
# let command line options override everything
for gskey in list(self.gskeys.values()):
if hasattr(options, gskey.prop): # command line option there?
value = getattr(options, gskey.prop)
if not value is None:
gskey.value = value
def init_from_gsettings(self):
""" init propertiy values from gsettings """
for prop, gskey in list(self.gskeys.items()):
gskey.value = gskey.default
if hasattr(self, _GSETTINGS_GET_HOOK + prop):
gskey.value = getattr(self, _GSETTINGS_GET_HOOK + prop)(gskey)
else:
gskey.value = gskey.gsettings_get()
for child in self.children:
child.init_from_gsettings()
def init_from_system_defaults(self):
""" fill property values with system defaults """
for prop, value in list(self.system_defaults.items()):
setattr(self, prop, value) # write to gsettings
for child in self.children:
child.init_from_system_defaults()
def on_properties_initialized(self):
for child in self.children:
child.on_properties_initialized()
@staticmethod
def _get_user_sys_filename_gs(gskey, final_fallback, \
user_filename_func = None,
system_filename_func = None):
""" Convenience function, takes filename from gskey. """
return ConfigObject._get_user_sys_filename(gskey.value, gskey.key,
final_fallback,
user_filename_func,
system_filename_func)
@staticmethod
def _get_user_sys_filename(filename, description, \
final_fallback = None,
user_filename_func = None,
system_filename_func = None):
"""
Checks a filenames validity and if necessary expands it to a
fully qualified path pointing to either the user or system directory.
User directory has precedence over the system one.
"""
filepath = filename
if filename and not os.path.exists(filename):
# assume filename is just a basename instead of a full file path
_logger.debug(_("{description} '{filename}' not found yet, "
"retrying in default paths") \
.format(description=description, filename=filename))
if user_filename_func:
filepath = user_filename_func(filename)
if not os.path.exists(filepath):
filepath = ""
if not filepath and system_filename_func:
filepath = system_filename_func(filename)
if not os.path.exists(filepath):
filepath = ""
if not filepath:
_logger.info(_("unable to locate '{filename}', "
"loading default {description} instead") \
.format(description=description, filename=filename))
if not filepath and not final_fallback is None:
filepath = final_fallback
if not os.path.exists(filepath):
_logger.error(_("failed to find {description} '{filename}'") \
.format(description=description, filename=filename))
filepath = ""
else:
_logger.debug(_("{description} '{filepath}' found.") \
.format(description=description, filepath=filepath))
return filepath
@staticmethod
def get_unpacked_string_list(gskey, type_spec):
""" Store dictionary in a gsettings list key """
_list = gskey.settings.get_strv(gskey.key)
return ConfigObject.unpack_string_list(_list, type_spec)
@staticmethod
def set_packed_string_list(gskey, value):
""" Store dictionary in a gsettings list key """
_list = ConfigObject.pack_string_list(value)
gskey.settings.set_strv(gskey.key, _list)
@staticmethod
def pack_string_list(value):
""" very crude hard coded behavior, fixme as needed """
if type(value) == dict:
_dict = value
if value:
# has collection interface?
key, _val = _dict.items()[0]
if not hasattr(_val, "__iter__"):
_dict = dict([key, [value]] for key, value in _dict.items())
return ConfigObject._dict_to_list(_dict)
assert(False) # unsupported python type
@staticmethod
def unpack_string_list(_list, type_spec):
""" very crude hard coded behavior, fixme as needed """
if type_spec == "a{ss}":
_dict = ConfigObject._list_to_dict(_list, str, num_values = 1)
return dict([key, value[0]] for key, value in _dict.items())
if type_spec == "a{s[ss]}":
return ConfigObject._list_to_dict(_list, str, num_values = 2)
if type_spec == "a{i[ss]}":
return ConfigObject._list_to_dict(_list, int, num_values = 2)
assert(False) # unsupported type_spec
@staticmethod
def _dict_to_list(_dict):
""" Store dictionary in a gsettings list key """
return pack_name_value_list(_dict)
@staticmethod
def _list_to_dict(_list, key_type = str, num_values = 2):
""" Get dictionary from a gsettings list key """
if sys.version_info.major == 2:
_list = [x.decode("utf-8") for x in _list] # translate to unicode
return unpack_name_value_list(_list, key_type=key_type,
num_values = num_values)
def load_system_defaults(self, paths):
"""
System default settings can be optionally provided for distribution
specific customization or branding.
They are stored in simple ini-style files, residing in a small choice
of directories. The last setting found in the list of paths wins.
"""
_logger.info(_("Looking for system defaults in {paths}") \
.format(paths=paths))
filename = None
parser = configparser.SafeConfigParser()
try:
filename = parser.read(paths)
except configparser.ParsingError as ex:
_logger.error(_("Failed to read system defaults. " + \
unicode_str(ex)))
if not filename:
_logger.info(_("No system defaults found."))
else:
_logger.info(_("Loading system defaults from {filename}") \
.format(filename=filename))
self._read_sysdef_section(parser)
def _read_sysdef_section(self, parser):
"""
Read this instances (and its childrens) system defaults section.
"""
for child in self.children:
child._read_sysdef_section(parser)
self.system_defaults = {}
if self.sysdef_section and \
parser.has_section(self.sysdef_section):
items = parser.items(self.sysdef_section)
if sys.version_info.major == 2:
items = [(key, val.decode("UTF-8")) for key, val in items]
# convert ini file strings to property values
sysdef_gskeys = dict((k.sysdef, k) for k in list(self.gskeys.values()))
for sysdef, value in items:
_logger.info(_("Found system default '[{}] {}={}'") \
.format(self.sysdef_section, sysdef, value))
gskey = sysdef_gskeys.get(sysdef, None)
value = self._convert_sysdef_key(gskey, sysdef, value)
if not value is None:
prop = gskey.prop if gskey else sysdef.replace("-", "_")
self.system_defaults[prop] = value
def _convert_sysdef_key(self, gskey, sysdef, value):
"""
Convert a system default string to a property value.
Sysdef strings -> values of type of gskey's default value.
"""
if gskey is None:
_logger.warning(_("System defaults: Unknown key '{}' "
"in section '{}'") \
.format(sysdef, self.sysdef_section))
else:
_type = type(gskey.default)
str_type = str if sys.version_info.major >= 3 \
else unicode
if _type == str_type and value[0] != '"':
value = '"' + value + '"'
try:
value = literal_eval(value)
except (ValueError, SyntaxError) as ex:
_logger.warning(_("System defaults: Invalid value"
" for key '{}' in section '{}'"
"\n {}").format(sysdef,
self.sysdef_section, ex))
return None # skip key
return value
class GSKey:
"""
Class for a key-value tuple for ConfigObject.
It associates python properties with gsettings keys,
system default keys and command line options.
"""
def __init__(self, settings, key, default, prop, sysdef, writable):
if prop is None:
prop = key.replace("-","_")
if sysdef is None:
sysdef = key
self.settings = settings # gsettings object
self.key = key # gsettings key name
self.sysdef = sysdef # system default name
self.prop = prop # python property name
self.default = default # hard coded default, determines type
self.value = default # current property value
self.writable = writable # If False, never write the key to gsettings
# even on accident.
def is_default(self):
return self.value == self.default
def gsettings_get(self):
""" Get value from gsettings. """
value = self.default
try:
# Bug in Gio, gir1.2-glib-2.0, Oneiric
# Onboard is accumultating open file handles
# at "/home/<user>/.config/dconf/<user>' when
# reading from gsettings before writing.
# Check with:
# lsof -w -p $( pgrep gio-test ) -Fn |sort|uniq -c|sort -n|tail
#value = self.settings[self.key]
_type = type(self.default)
if _type == str:
value = self.settings.get_string(self.key)
elif _type == int:
value = self.settings.get_int(self.key)
elif _type == float:
value = self.settings.get_double(self.key)
else:
value = self.settings[self.key]
except KeyError as ex:
_logger.error(_("Failed to get gsettings value. ") + \
unicode_str(ex))
return value
def gsettings_set(self, value):
""" Send value to gsettings. """
if self.writable:
self.settings[self.key] = value
def gsettings_apply(self):
""" Send current value to gsettings. """
if self.writable:
self.settings[self.key] = self.value
| thnguyn2/ECE_527_MP | mp4/SD_card/partition1/usr/share/pyshared/Onboard/ConfigUtils.py | ConfigUtils.py | py | 20,458 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "gi.repository.Gio.Settings.list_schemas",
"line_number": 56,
"usage_type": "call"
},
{
"api_name": "gi.repository.Gio.Settings",
"line_number": 56,
"usage_type": "attribute"
},
... |
9016676437 | #!/usr/bin/env python3
import sys, datetime, threading, time, shutil, hashlib
from Key import Key
from Display import Display
from Simulation import Simulation
class Main:
def __init__(self):
self.cuteloading = None
self.asynckey = None
try:
sys.stdout.write(Display.screen(True) + Display.cursor(False))
sys.stdout.flush()
width, height = shutil.get_terminal_size((80, 20))
self.key = Key()
self.asynckey = threading.Thread(target=self.key.storechar, args=(), daemon=False)
self.asynckey.start()
self.time = time.time()
self.cuteloading = threading.Thread(target=Display.startloading, args=(width,), daemon=False)
self.cuteloading.start()
Display.setdisplay(width - 1, height)
self.now = datetime.datetime.now()
Display.setstring("This is a test string!\nAnd this is as well!\n\nOk...")
Display.stoploading(self.cuteloading)
self.key.settrackkeys(True)
self.main()
finally:
Display.stoploading(self.cuteloading)
Key.close()
self.asynckey.join()
sys.stdout.write(Display.screen(False) + Display.cursor(True))
sys.stdout.flush()
def main(self):
self.sim = Simulation.fromfile("test.sim")
self.display()
while True:
new_time = time.time()
time.sleep(max(0, 0.01 - new_time + self.time))
self.time = new_time
char = self.key.asyncgetchar()
if not char:
continue
if char in ["\x1b", "\x03", "\t", "x"]:
break
def display(self):
Display.clear()
string = self.sim.getstring()
# assert False, string
Display.setstring(string)
display = Display.outputdisplay()
sys.stdout.write(display)
sys.stdout.flush()
if __name__ == "__main__":
Main()
| Mieschendahl/MAPF | MAPF.py | MAPF.py | py | 2,019 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.stdout.write",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "sys.stdout",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "Display.Display.screen",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "Display.Displ... |
43162890839 | # ResNet:提出了层间残差跳连,引入了前方信息,缓解梯度消失,使神经网络增加层数成为可能。
# 单纯堆叠神经网络层数,会使神经网络模型退化,以至于后面的特征丢失了前面特征的原本模样
# 用一根跳连线将前面的特征直接接到后边,使输出结果包含了堆叠卷积的非线性输出和跳过两层堆叠卷积直接连接过来的恒等映射x,
# 让它们对应的元素相加,有效缓解了神经网络模型堆叠导致的退化,使得神经网络可以向着更深层级发展。
# ResNet中的“+” 与InceptionNet中的“+” 不同的。
# Inception中的“+”是沿深度方向叠加,相当于千层蛋糕增加层数
# ResNet块中的“+”是两路特征图对应元素相加,相当于两个矩阵对应元素做加法
# ResNet块中有两种情况:
# 1)用实线表示:两层堆叠卷积不改变特征图的维度,也就是特征图的个数高、宽、深度都相同,可以直接相加。
# 2)用虚线表示:两层堆叠卷积改变了特征图的维度,需要借助1*1的卷积来调整x的维度,是w_{x}与F_{x}的维度一致。
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, Dropout, Dense, Flatten
from tensorflow.keras.models import Model
# import numpy as np
import os
import matplotlib.pyplot as plt
cifar = tf.keras.datasets.cifar10
(x_train, y_train), (x_test, y_test) = cifar.load_data()
x_train, x_test = x_train/255.0, x_test/255.0
class ResnetBlock(Model):
def __init__(self, filters, strides=1, residual_path=False):
super(ResnetBlock, self).__init__()
self.filters = filters
self.strides = strides
self.residual_path = residual_path
self.l1_c = Conv2D(filters, kernel_size=(3, 3), strides=strides, padding='same', use_bias=False)
self.l1_b = BatchNormalization()
self.l1_a = Activation('relu')
self.l2_c = Conv2D(filters, kernel_size=(3, 3), strides=1, padding='same', use_bias=False)
self.l2_b = BatchNormalization()
#residual_path为True时,对输入进行下采样,即用1*1的卷积核做卷积操作,保证x能和F(x)维度相同,顺利相加
if residual_path:
self.down_c = Conv2D(filters, kernel_size=(1, 1), strides=strides, padding='same', use_bias=False)
self.down_b = BatchNormalization()
self.l2_a = Activation('relu')
def call(self, inputs):
residual = inputs
# 将输入通过卷积、BN层、激活层、计算F(x)
x = self.l1_c(inputs)
x = self.l1_b(x)
x = self.l1_a(x)
x = self.l2_c(x)
y = self.l2_b(x)
if self.residual_path:
residual = self.down_c(inputs)
residual = self.down_b(residual)
out = self.l2_a(y + residual) # 最后输出的是两部分的和,即F(x)+x或F(x)+W(x),再过激活函数
return out
class ResNet18(Model):
def __init__(self, block_list, initial_filters=64): # block_list表示每个block有几个卷积核
super(ResNet18, self).__init__()
self.block_num = len(block_list) # 共有几个block
self.block_list = block_list
self.out_filters = initial_filters
self.init_c = Conv2D(self.out_filters, kernel_size=(3, 3), strides=1, padding='same', use_bias=False, kernel_initializer='he_normal')
self.init_b = BatchNormalization()
self.init_a = Activation('relu')
self.blocks = tf.keras.models.Sequential()
# 构建ResNet网络结构
for block_id in range(len(block_list)): # 第几个resnet block
for layer_id in range(block_list[block_id]): # 第几个卷积层
if block_id != 0 and layer_id == 0: # 对除第一个block以外的每个block的输入进行下采样
block = ResnetBlock(self.out_filters, strides=2, residual_path=True)
else:
block = ResnetBlock(self.out_filters, residual_path=False)
self.blocks.add(block) # 将构建好的block加入resnet
self.out_filters *= 2
self.p1 = tf.keras.layers.GlobalAvgPool2D()
self.f1 = tf.keras.layers.Dense(10)
def call(self, inputs):
x = self.init_c(inputs)
x = self.init_b(x)
x = self.init_a(x)
x = self.blocks(x)
x = self.p1(x)
y = self.f1(x)
return y
model = ResNet18([2, 2, 2, 2])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
checkpoint_save_path = './checkpoint/cifar.ckpt'
if os.path.exists(checkpoint_save_path):
print('------------------Loading Model-------------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=32,
epochs=5,
validation_data=(x_test, y_test),
validation_freq=1,
callbacks=[cp_callback])
model.summary()
with open('./weights.txt', 'w') as f:
for weight in model.trainable_weights:
f.write(str(weight.name) + '\n')
f.write(str(weight.shape) + '\n')
f.write(str(weight.numpy()) + '\n')
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.subplot(1, 2, 1)
plt.plot(acc, label='Train ACC')
plt.plot(val_acc, label='Test ACC')
plt.title('Train AND Test ACC')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(loss, label='Train loss')
plt.plot(val_loss, label='Test loss')
plt.title('Train AND Test Loss')
plt.legend()
plt.show()
| Demonya/tensorflow_basic | P5/P5.15:ResNet.py | P5.15:ResNet.py | py | 6,041 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tensorflow.keras",
"line_number": 20,
"usage_type": "attribute"
},
{
"api_name": "tensorflow.keras.models.Model",
"line_number": 24,
"usage_type": "name"
},
{
"api_name": "tensorflow.keras.layers.Conv2D",
"line_number": 31,
"usage_type": "call"
},
{
... |
8384706762 | """Functions for application
"""
import collections
import base64
import skbio
import pandas as pd
from io import StringIO
def parse_sequences(seq_lines, consensus_sequence):
msa = skbio.alignment.TabularMSA.read(seq_lines,
constructor=skbio.sequence.DNA)
seqs, names = zip(*[(str(seq), seq.metadata['id']) for seq in msa])
conservation = msa.conservation()
names = list(names)
seqs = list(seqs)
if consensus_sequence:
names.insert(0, 'Consensus Sequence')
seqs.insert(0, str(msa.consensus()))
return names, seqs, conservation
def alignment_layout(seqs, layout_type,
letter_colors, reference_layout,
base_dic):
'''Get layout for alignment'''
letter_colors['-'] = '#444'
text_values = list(seqs[0])
block_values = [[0]*len(text_values)]
if layout_type == 'Letters':
text_colors = pd.Series(text_values).replace(letter_colors).tolist()
block_colors = [[0.00, '#FFF'],
[1.00, '#FFF']]
block_values *= len(seqs)
elif layout_type == 'Blocks':
text_colors = '#000'
text_values = list(''.join(seqs))
block_colors = [[0.00, '#F4F0E4'],
[0.1, '#F4F0E4'],
[0.1, letter_colors['C']],
[0.26, letter_colors['C']],
[0.26, letter_colors['G']],
[0.51, letter_colors['G']],
[0.51, letter_colors['T']],
[0.76, letter_colors['T']],
[0.76, letter_colors['A']],
[1.00, letter_colors['A']]]
for seq in seqs[1:]:
seq_series = pd.Series(list(seq))
if layout_type == 'Letters':
text_colors.extend(seq_series.replace(letter_colors).tolist())
if reference_layout:
seq_series.where(seq_series != pd.Series(list(seqs[0])), '.',
inplace=True)
text_values.extend(seq_series.tolist())
elif layout_type == 'Blocks':
if reference_layout:
seq_series.where(seq_series != pd.Series(list(seqs[0])), 0,
inplace=True)
seq_series.replace(base_dic, inplace=True)
block_values.append(seq_series.tolist())
if not reference_layout and layout_type == 'Blocks':
block_values[0] = \
pd.Series(list(seqs[0])).replace(base_dic).tolist()
return text_values, text_colors, block_values, block_colors
def get_msa_order(reference_name, names, seqs):
"""Order sequences"""
seq_dic = collections.OrderedDict(zip(names, seqs))
seq_dic.move_to_end(reference_name)
return zip(*list(seq_dic.items())[::-1])
def get_dimensions(seqs):
'''Function for getting figure get_dimensions'''
n_seqs, sequence_length = len(seqs), len(seqs[0])
y = [[i]*sequence_length for i in range(n_seqs)]
y = [item for sublist in y for item in sublist]
x = list(range(sequence_length))*n_seqs
return x, y, n_seqs, sequence_length
def parse_seq_object(seq_object):
'''Parse the object that is read in by Dash. This would ultimately use
skbio hoewever that causes Heroku to fail currently'''
try:
_, content_string = seq_object.split(',')
decoded = base64.b64decode(content_string)
seq_lines = StringIO(decoded.decode('utf-8'))
return seq_lines
except AttributeError:
pass
| johnchase/dash-alignment-viewer | webapp/util.py | util.py | py | 3,587 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "skbio.alignment.TabularMSA.read",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "skbio.alignment",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "skbio.sequence",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name... |
12833767605 | from functools import reduce
with open("input.txt", "r") as f:
inputs = f.read().splitlines()
def accScore(acc, inputs):
return acc + [
ord(a) - ord('A') + 27 if ord(a) < ord('a') else ord(a) - ord('a') + 1
for a in inputs[0] if all(a in line for line in inputs[1:])
][0]
score1 = reduce(accScore, [[line[:len(line) // 2], line[len(line) // 2:]] for line in inputs], 0)
print("Total score #1: {}".format(score1))
score2 = reduce(accScore, [inputs[i:i + 3] for i in range(0, len(inputs), 3)], 0)
print("Total score #2: {}".format(score2))
| efoncubierta/advent-of-code | 2022/day03/main.py | main.py | py | 570 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "functools.reduce",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "functools.reduce",
"line_number": 15,
"usage_type": "call"
}
] |
6504272930 | import sys
from io import StringIO
text_input1 = """4 6"""
text_input2 = """3 2"""
sys.stdin = StringIO(text_input1)
# sys.stdin = StringIO(text_input2)
r, c = [int(x) for x in input().split()]
matrix = []
for n in range(r):
current_row = []
for m in range(c):
current_sequence = chr(97 + n) + chr(97 + n + m) + chr(97 + n)
current_row.append(current_sequence)
matrix.append(current_row)
[print(' '.join(seq for seq in row)) for row in matrix]
| gyurel/Python-Advanced-Course | exercises_multidimensional_lists/matrix_of_palindromes.py | matrix_of_palindromes.py | py | 479 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.stdin",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "io.StringIO",
"line_number": 8,
"usage_type": "call"
}
] |
15339693534 | from functools import partial
def parse(s: str, ind: int = 0):
return_index = ind != 0
result = []
ind += 1 # First character is "["
while s[ind] != "]":
if s[ind] == ",":
ind += 1
elif s[ind] == "[":
sub_result, ind = parse(s, ind)
result.append(sub_result)
else: # Parse a number
end = ind
while s[end] in "0123456789":
end += 1
sub_packet = s[ind:end]
result.append(int(sub_packet))
ind += len(sub_packet)
ind += 1
return result, ind if return_index else result
def leq(pair_1, pair_2):
return compare(pair_1, pair_2) in {0, 1}
def compare(pair_1, pair_2):
for a, b in zip(pair_1, pair_2):
if isinstance(a, int) and isinstance(b, int):
res = 1 if a < b else (-1 if a > b else 0)
elif isinstance(a, int) and isinstance(b, list):
res = compare([a], b)
elif isinstance(a, list) and isinstance(b, int):
res = compare(a, [b])
else:
res = compare(a, b)
if res != 0:
return res
if len(pair_1) < len(pair_2):
return 1
elif len(pair_1) > len(pair_2):
return -1
else:
return 0
def main(data, part):
if part == "a":
pairs = data.split("\n\n")
result = sum(
j * leq(*map(parse, pair.split("\n"))) for j, pair in enumerate(pairs, 1)
)
else:
packets = data.replace("\n\n", "\n").split("\n")
packets = list(map(parse, packets))
split_1 = sum(map(partial(leq, pair_2=[[2]]), packets))
split_2 = sum(map(partial(leq, pair_2=[[6]]), packets))
result = (split_1 + 1) * (split_2 + 2)
return result
| martinsbruveris/advent-of-code | aoc/aoc_2022/day_13.py | day_13.py | py | 1,783 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "functools.partial",
"line_number": 58,
"usage_type": "call"
},
{
"api_name": "functools.partial",
"line_number": 59,
"usage_type": "call"
}
] |
38250977833 | from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import TodoSerializer
from .models import Todo
# Create your views here.
@api_view(['GET'])
def index(request):
return Response('hello')
@api_view(['GET'])
def todo_lists(request):
todos = Todo.objects.all()
serializer = TodoSerializer(todos, many=True)
return Response(serializer.data)
@api_view(['GET'])
def todo_detail(request, id):
todo = Todo.objects.get(pk=id)
serializer = TodoSerializer(todo, many=False)
return Response(serializer.data)
@api_view(['POST'])
def add_todo(request):
serializer = TodoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['PUT'])
def update_todo(request, id):
todo = Todo.objects.get(pk=id)
serializer = TodoSerializer(instance=todo, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def delete_todo(request, id):
todo = Todo.objects.get(pk=id)
todo.delete()
return Response('Successfully deleted') | SergeJohn/todo-app | backend/api/views.py | views.py | py | 1,251 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "rest_framework.response.Response",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "rest_framework.decorators.api_view",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "models.Todo.objects.all",
"line_number": 17,
"usage_type": "call"
}... |
44140383131 | import logging as log
from os import getenv, listdir
import discord
from discord.ext import commands
from discord import ExtensionAlreadyLoaded
from dotenv import load_dotenv
# -------------------------> Globals
load_dotenv()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=getenv('PREFIX'), intents=intents)
# -------------------------> Logging
log.basicConfig(
level=log.INFO,
format='%(asctime)s [%(levelname)8s] @ %(name)-18s: %(message)s',
datefmt='%d/%m/%y %H:%M:%S',
filename='storage/discord.log',
filemode='w',
encoding='utf-8'
)
# Hide info logs that the discord module sents
log.getLogger('discord').setLevel('WARNING')
# Logs command calls
@bot.before_invoke
async def logging(ctx: commands.Context):
if not ctx.invoked_subcommand:
commandlog = log.getLogger('command.invoke')
if log.root.level != log.DEBUG:
commandlog.info(f"{ctx.author.name.ljust(16,' ')} | called: {str(ctx.command)}")
else:
commandlog.debug(f"{ctx.author.name.ljust(16,' ')} | called: {str(ctx.command).ljust(12,' ')} | with: {ctx.message.content}")
# -------------------------> Main
if __name__ == '__main__':
# Start all extensions
for ext in ['packages.' + file[:-3] for file in listdir('src/packages') if file[-3:] == '.py']:
try:
bot.load_extension(ext)
except ExtensionAlreadyLoaded as err:
log.warning(err)
except Exception as err:
log.warning(err)
bot.run(getenv('TOKEN'))
| juliavdkris/dotobot | src/main.py | main.py | py | 1,451 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "dotenv.load_dotenv",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "discord.Intents.all",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "discord.Intents",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "discord.e... |
14889874420 | from __future__ import print_function
from operator import itemgetter
import collections
import os.path
import re
import sys
# Avoid endlessly adding to the path if this module is imported multiple
# times, e.g. in an interactive session
regpath = os.path.join(sys.path[0], "registry")
if sys.path[1] != regpath:
sys.path.insert(1, regpath)
import reg
AEP_EXTENSIONS = [
'GL_KHR_blend_equation_advanced',
'GL_KHR_debug',
'GL_KHR_texture_compression_astc_ldr',
'GL_OES_sample_shading',
'GL_OES_sample_variables',
'GL_OES_shader_image_atomic',
'GL_OES_shader_multisample_interpolation',
'GL_OES_texture_stencil8',
'GL_OES_texture_storage_multisample_2d_array',
'GL_EXT_copy_image',
'GL_EXT_draw_buffers_indexed',
'GL_EXT_geometry_shader',
'GL_EXT_gpu_shader5',
'GL_EXT_primitive_bounding_box',
'GL_EXT_shader_io_blocks',
'GL_EXT_tessellation_shader',
'GL_EXT_texture_border_clamp',
'GL_EXT_texture_buffer',
'GL_EXT_texture_cube_map_array',
'GL_EXT_texture_sRGB_decode']
def nonestr(s):
return s if s else ""
def parseProto(elem):
type = nonestr(elem.text)
name = None
for subelem in elem:
text = nonestr(subelem.text)
if subelem.tag == 'name':
name = text
else:
type += text
type += nonestr(subelem.tail)
return (type.strip(), name)
def parseParam(elem):
name = elem.find('name').text
declaration = ''.join(elem.itertext())
return (name, declaration)
# Format a list of (type, declaration) tuples as a C-style parameter list
def fmtParams(params):
if not params:
return 'void'
return ', '.join(p[1] for p in params)
# Format a list of (type, declaration) tuples as a C-style argument list
def fmtArgs(params):
return ', '.join(p[0] for p in params)
def overrideSymbolName(sym, apiname):
# The wrapper intercepts various glGet and glGetString functions and
# (sometimes) calls the generated thunk which dispatches to the
# driver's implementation
wrapped_get_syms = {
'gles1' : [
'glGetString'
],
'gles2' : [
'glGetString',
'glGetStringi',
'glGetBooleanv',
'glGetFloatv',
'glGetIntegerv',
'glGetInteger64v',
],
}
if sym in wrapped_get_syms.get(apiname):
return '__' + sym
else:
return sym
# Generate API trampoline templates:
# <rtype> API_ENTRY(<name>)(<params>) {
# CALL_GL_API(<name>, <args>);
# // or
# CALL_GL_API_RETURN(<name>, <args>);
# }
class TrampolineGen(reg.OutputGenerator):
def __init__(self):
reg.OutputGenerator.__init__(self, sys.stderr, sys.stderr, None)
def genCmd(self, cmd, name):
if re.search('Win32', name):
return
reg.OutputGenerator.genCmd(self, cmd, name)
rtype, fname = parseProto(cmd.elem.find('proto'))
params = [parseParam(p) for p in cmd.elem.findall('param')]
call = 'CALL_GL_API' if rtype == 'void' else 'CALL_GL_API_RETURN'
print('%s API_ENTRY(%s)(%s) {\n'
' %s(%s%s%s);\n'
'}'
% (rtype, overrideSymbolName(fname, self.genOpts.apiname),
fmtParams(params), call, fname,
', ' if len(params) > 0 else '',
fmtArgs(params)),
file=self.outFile)
# Collect all API prototypes across all families, remove duplicates,
# emit to entries.in and enums.in files.
class ApiGenerator(reg.OutputGenerator):
def __init__(self):
reg.OutputGenerator.__init__(self, sys.stderr, sys.stderr, None)
self.cmds = []
self.enums = collections.OrderedDict()
def genCmd(self, cmd, name):
if re.search('Win32', name):
return
reg.OutputGenerator.genCmd(self, cmd, name)
rtype, fname = parseProto(cmd.elem.find('proto'))
params = [parseParam(p) for p in cmd.elem.findall('param')]
self.cmds.append({'rtype': rtype, 'name': fname, 'params': params})
def genEnum(self, enuminfo, name):
reg.OutputGenerator.genEnum(self, enuminfo, name)
value = enuminfo.elem.get('value')
# Skip bitmask enums. Pattern matches:
# - GL_DEPTH_BUFFER_BIT
# - GL_MAP_INVALIDATE_BUFFER_BIT_EXT
# - GL_COLOR_BUFFER_BIT1_QCOM
# but not
# - GL_DEPTH_BITS
# - GL_QUERY_COUNTER_BITS_EXT
#
# TODO: Assuming a naming pattern and using a regex is what the
# old glenumsgen script did. But the registry XML knows which enums are
# parts of bitmask groups, so we should just use that. I'm not sure how
# to get the information out though, and it's not critical right now,
# so leaving for later.
if re.search('_BIT($|\d*_)', name):
return
if re.search('D3D|WIN32', name):
return
# Skip non-hex values (GL_TRUE, GL_FALSE, header guard junk)
if not re.search('0x[0-9A-Fa-f]+', value):
return
# Append 'u' or 'ull' type suffix if present
type = enuminfo.elem.get('type')
if type and type != 'i':
value += type
if value not in self.enums:
self.enums[value] = name
def finish(self):
# sort by function name, remove duplicates
self.cmds.sort(key=itemgetter('name'))
cmds = []
for cmd in self.cmds:
if len(cmds) == 0 or cmd != cmds[-1]:
cmds.append(cmd)
self.cmds = cmds
# Write entries.in
def writeEntries(self, outfile):
for cmd in self.cmds:
print('GL_ENTRY(%s, %s, %s)'
% (cmd['rtype'], cmd['name'], fmtParams(cmd['params'])),
file=outfile)
# Write enums.in
def writeEnums(self, outfile):
for enum in self.enums.iteritems():
print('GL_ENUM(%s,%s)' % (enum[0], enum[1]), file=outfile)
# Generate .spec entries for use by legacy 'gen' script
class SpecGenerator(reg.OutputGenerator):
def __init__(self):
reg.OutputGenerator.__init__(self, sys.stderr, sys.stderr, None)
def genCmd(self, cmd, name):
reg.OutputGenerator.genCmd(self, cmd, name)
rtype, fname = parseProto(cmd.elem.find('proto'))
params = [parseParam(p) for p in cmd.elem.findall('param')]
print('%s %s ( %s )' % (rtype, fname, fmtParams(params)),
file=self.outFile)
if __name__ == '__main__':
registry = reg.Registry()
registry.loadFile('registry/gl.xml')
registry.setGenerator(TrampolineGen())
TRAMPOLINE_OPTIONS = [
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common',
filename = '../../libs/GLES_CM/gl_api.in'),
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common',
emitversions = None,
defaultExtensions = 'gles1',
filename = '../../libs/GLES_CM/glext_api.in'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
filename = '../../libs/GLES2/gl2_api.in'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
emitversions = None,
defaultExtensions = 'gles2',
filename = '../../libs/GLES2/gl2ext_api.in')]
for opts in TRAMPOLINE_OPTIONS:
registry.apiGen(opts)
# Generate a GLESv1_CM entries separately to avoid extra driver loading time
apigen = ApiGenerator()
registry.setGenerator(apigen)
API_OPTIONS = [
# Generate non-extension versions of each API first, then extensions,
# so that if an extension enum was later standardized, we see the non-
# suffixed version first.
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common'),
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common',
emitversions = None,
defaultExtensions = 'gles1')]
for opts in API_OPTIONS:
registry.apiGen(opts)
apigen.finish()
with open('../../libs/entries_gles1.in', 'w') as f:
apigen.writeEntries(f)
apigen = ApiGenerator()
registry.setGenerator(apigen)
API_OPTIONS = [
# Generate non-extension versions of each API first, then extensions,
# so that if an extension enum was later standardized, we see the non-
# suffixed version first.
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common'),
reg.GeneratorOptions(
apiname = 'gles1',
profile = 'common',
emitversions = None,
defaultExtensions = 'gles1'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
emitversions = None,
defaultExtensions = 'gles2')]
for opts in API_OPTIONS:
registry.apiGen(opts)
apigen.finish()
with open('../../libs/entries.in', 'w') as f:
apigen.writeEntries(f)
with open('../../libs/enums.in', 'w') as f:
apigen.writeEnums(f)
registry.setGenerator(SpecGenerator())
SPEC_OPTIONS = [
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
versions = '3\.1',
filename = '../glgen/specs/gles11/GLES31.spec'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
emitversions = None,
defaultExtensions = None,
addExtensions = '^({})$'.format('|'.join(AEP_EXTENSIONS)),
filename = '../glgen/specs/gles11/GLES31Ext.spec'),
reg.GeneratorOptions(
apiname = 'gles2',
profile = 'common',
versions = '3\.2',
filename = '../glgen/specs/gles11/GLES32.spec')]
# SpecGenerator creates a good starting point, but the CFunc.java parser is
# so terrible that the .spec file needs a lot of manual massaging before
# it works. Commenting this out to avoid accidentally overwriting all the
# manual modifications.
#
# Eventually this script should generate the Java and JNI code directly,
# skipping the intermediate .spec step, and obsoleting the existing
# ../glgen system.
#
# for opts in SPEC_OPTIONS:
# registry.apiGen(opts)
| AndroidBBQ/android10 | frameworks/native/opengl/tools/glgen2/glgen.py | glgen.py | py | 11,061 | python | en | code | 176 | github-code | 36 | [
{
"api_name": "os.path.path.join",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path.path",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "os.path",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "sys.path",
"line_numb... |
28481602613 | # Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask, render_template,request, redirect, url_for,session
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient("mongodb+srv://arsal0344:03444800061@cluster0.u6h8hwf.mongodb.net/?retryWrites=true&w=majority")
db = client.mentoria
collection = db.users
app.secret_key = 'admin4321'
try:
client.admin.command('ping')
print("Connected to MongoDB!")
except Exception as e:
print("Unable to connnect to MongoDB:", e)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/quiz')
def quiz():
return render_template('quiz.html')
# fulldata=[]
@app.route('/submitData',methods=['post'])
def submitData():
data = request.get_json()
# fulldata.append(data)
session['key'] = data
# result = collection.insert_one({'name': data['name'],'email':data['email'],'phone':data['phone']})
return render_template('quiz.html',modal=True)
@app.route('/mcqs')
def mcqs():
return render_template('mcqs.html')
@app.route('/mcqsData',methods=['post'])
def mcqsData():
data = request.get_json()
data.append(session.get('key'))
answers = data[:-1]
result = collection.insert_one({'answers':answers,'info':data[-1]})
return 'done'
@app.route('/end')
def end():
return render_template('end.html')
@app.route('/admin4321')
def admin():
solution = ['option2','option2','option3','option1','option3','option3','option3','option2','option4','option3',
'option3','option4','option4','option2','option2','option3','option2','option3','option4','option3',
'option3','option4','option1','option2','option2','option3','option4','option3','option3','option4',
'option2','option2','option3','option2','option4','option3','option2','option4','option3','option1']
last = []
data = list(collection.find())
quantitative = iq = physics = chemistry = 0
for i in range(len(data)):
info = data[i]['info']
info['answers'] = []
for j in range(40):
if data[i]['answers'][j]['value'] == solution[j]:
info['answers'].append(True)
if j<10 : quantitative = quantitative+1
elif j<20: iq = iq+1
elif j<30: physics = physics+1
else: chemistry = chemistry+1
else:
info['answers'].append(False)
info["quantitative"] = quantitative
info["iq"] = iq
info["physics"] = physics
info["chemistry"] = chemistry
info["total"] = quantitative+iq+physics+chemistry
last.append(info)
quantitative = iq = physics = chemistry = 0
print(last)
return render_template('admin.html',data=last)
if __name__ == '__main__':
app.run(debug=True)
| SHnice/MentoriaPakistan | index.py | index.py | py | 2,889 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.Flask",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "pymongo.MongoClient",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "flask.render_template",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "flask.render_temp... |
36567731753 | from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('django_mfa', '0002_auto_20160706_1421'),
]
operations = [
migrations.AlterField(
model_name='UserRecoveryCodes',
name='secret_code',
field=models.CharField(max_length=16),
),
]
| MicroPyramid/django-mfa | django_mfa/migrations/0003_change_secret_code_max_length.py | 0003_change_secret_code_max_length.py | py | 418 | python | en | code | 176 | github-code | 36 | [
{
"api_name": "django.db.migrations.Migration",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "django.db.migrations",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "django.db.migrations.AlterField",
"line_number": 14,
"usage_type": "call"
},
{... |
39479689036 | from django.core.management.base import BaseCommand, CommandError
from cards.models import Card
from cards.models import PhysicalCard
from decks.models import Deck, DeckCard, Tournament, TournamentDeck, DeckCluster, DeckClusterDeck
import re
from optparse import make_option
from datetime import datetime, timedelta
import codecs
import sys
out = sys.stdout
class Command(BaseCommand):
help = 'Generate a deck in a document to be fed into Lucene or Mahout.'
option_list = BaseCommand.option_list + (
make_option('--input',
dest='input',
type='string',
default='./hierarchical_clusters.csv',
help='The csv file that Orange will output. Expected to have deck id as first column, cluster as last column.'),
)
def handle(self, *args, **options):
line_re = re.compile(r'^deck_([0-9]+),.+,C(luster )?([0-9]+)$')
filein = codecs.open(options['input'], 'r', 'utf-8')
for line in filein:
lmatch = line_re.search(line)
if lmatch:
key = lmatch.group(3)
distance = 1.0
deck_id = lmatch.group(1)
dc = DeckCluster.objects.filter(formatname='Modern', clusterkey=int(key)).first()
if dc is None:
dc = DeckCluster(formatname='Modern', clusterkey=int(key), name='Cluster {}'.format(str(key)))
dc.save()
out.write('Created new DeckCluster for Key {}\n'.format(str(key)))
dc = DeckCluster.objects.filter(formatname='Modern', clusterkey=int(key)).first()
deck_obj = Deck.objects.get(pk=int(deck_id))
dcd = DeckClusterDeck(deckcluster=dc, distance=float(distance), deck=deck_obj)
dcd.save()
out.write('Key {}, dist {}, deck id {}\n'.format(str(key), str(distance), str(deck_id)))
filein.close()
| jcrickmer/mtgdbpy | decks/management/commands/loaddeckhierarchicalclusters.py | loaddeckhierarchicalclusters.py | py | 1,967 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.stdout",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "django.core.management.base.BaseCommand",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "django.core.management.base.BaseCommand.option_list",
"line_number": 21,
"usage_t... |
36477035716 | import os
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from catVdog.models import IMG
from Include.cnn.predict import predict
# Create your views here.
# 添加 index 函数,返回 index.html 页面
def index(request):
return render(request, 'index.html')
@csrf_exempt
def uploadImg(request):
for file in os.listdir("E:/PycharmProjects/CatVsDog/media/img/"):
targetFile = os.path.join("E:/PycharmProjects/CatVsDog/media/img/", file)
if os.path.isfile(targetFile):
os.remove(targetFile)
if request.method == 'POST':
new_img = IMG(
img=request.FILES.get('img'),
name=request.FILES.get('img').name
)
new_img.save()
return render(request, 'uploadimg.html')
def result (request):
result = predict()
return render(request, 'result.html', {"data": result})
| Missyanc/CatVsDog | catVdog/views.py | views.py | py | 927 | python | en | code | 97 | github-code | 36 | [
{
"api_name": "django.shortcuts.render",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.listdir",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_n... |
25111441493 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
__author__ = 'hendro'
from tornado.web import RequestHandler
from library.AutoVivification import AutoVivification
from library.helpers import send_request, is_engine_activated, load_engine_db
from config import USERNAME, PASSWORD, APP_NAME, DB_PATH
import requests
class BaseHandler(RequestHandler):
scrapyd_api_url = "http://engine.lintas.me:6800"
def set_default_headers(self):
self.set_header("Server", "LintasEngineServer/0.1")
def get_current_user(self):
return self.get_secure_cookie("username")
class LoginHandler(BaseHandler):
def get(self):
if self.get_current_user():
self.redirect('/engine/console/home')
return
self.render('views/page_login.html')
def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == USERNAME and password == PASSWORD:
self.set_secure_cookie("username", USERNAME, expires_days=5)
self.redirect("/engine/console/home")
class LogoutHandler(BaseHandler):
def get(self):
if not self.get_current_user():
self.redirect('/engine/console/login')
return
self.clear_cookie("username")
self.redirect('/engine/console/login')
class HomeHandler(BaseHandler):
def get(self):
user = self.get_current_user()
if not user:
self.redirect("/engine/console/login")
return
engine_config = load_engine_db(DB_PATH)
engines = engine_config['engine']
try:
post_to_lintas = engine_config['post_to_lintas']
except KeyError:
post_to_lintas = "No"
engine_count = len(engines)
engine_list = AutoVivification()
for engine in engines:
engine_list[engine]['status'] = "ACTIVE" if is_engine_activated(engine.lower()) else "INACTIVE"
engine_list[engine]['cmd'] = engines[engine]['cmd']
engine_list[engine]['minute_run_at'] = engines[engine]['run_at'][0]
engine_list[engine]['hour_run_at'] = engines[engine]['run_at'][1]
try:
running_project = "text-primary|" + send_request("%s/listprojects.json" % self.scrapyd_api_url)['projects'][0]
running_spider = "text-primary|" + send_request("%s/listspiders.json?project=%s" % (self.scrapyd_api_url, running_project.split('|')[1]))['spiders'][0]
project_version = "text-primary|" + send_request("%s/listversions.json?project=%s" % (self.scrapyd_api_url, running_project.split('|')[1]))['versions'][0]
except requests.ConnectionError:
running_project = "text-danger|CRAWLER SERVER IS DOWN"
running_spider = "text-danger|CRAWLER SERVER IS DOWN"
project_version = "text-danger|CRAWLER SERVER IS DOWN"
except IndexError:
running_project = "text-danger|NO CRAWLER PROJECT RUNNING"
running_spider = "text-danger|NO CRAWLER PROJECT RUNNING"
project_version = "text-danger|NO CRAWLER PROJECT RUNNING"
self.render('views/main.html', title=APP_NAME, name=user, \
running_project=running_project, running_spider=running_spider, \
project_version=project_version, engine_count=engine_count, \
engines=engine_list, post_to_lintas=post_to_lintas)
class InformationHandler(BaseHandler):
def get(self):
user = self.get_current_user()
if not user:
self.redirect("/engine/console/login")
return
engine_count = len(load_engine_db(DB_PATH)['engine'])
try:
running_project = "text-primary|" + send_request("%s/listprojects.json" % \
(self.scrapyd_api_url))['projects'][0]
running_spider = "text-primary|" + send_request("%s/listspiders.json?project=%s" % \
(self.scrapyd_api_url, running_project.split('|')[1]))['spiders'][0]
project_version = "text-primary|" + send_request("%s/listversions.json?project=%s" % \
(self.scrapyd_api_url, running_project.split('|')[1]))['versions'][0]
except requests.ConnectionError:
running_project = "text-danger|CRAWLER SERVER IS DOWN"
running_spider = "text-danger|CRAWLER SERVER IS DOWN"
project_version = "text-danger|CRAWLER SERVER IS DOWN"
except IndexError:
running_project = "text-danger|NO CRAWLER PROJECT RUNNING"
running_spider = "text-danger|NO CRAWLER PROJECT RUNNING"
project_version = "text-danger|NO CRAWLER PROJECT RUNNING"
self.render('views/informations.html', title=APP_NAME, name=user, \
running_project=running_project, running_spider=running_spider, \
project_version=project_version, engine_count=engine_count) | w33ladalah/news-crawler-engine | webapp/console.py | console.py | py | 5,059 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tornado.web.RequestHandler",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "config.USERNAME",
"line_number": 35,
"usage_type": "name"
},
{
"api_name": "config.PASSWORD",
"line_number": 35,
"usage_type": "name"
},
{
"api_name": "config.USE... |
25534524692 | #how to import video in openCV
import cv2 as cv2
import matplotlib.pyplot as plt
import numpy as np
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('outpu.avi',fourcc,20.0,(640,480))
while(cap.isOpened()):
ret, frame = cap.read(0)#This code initiates an infinite loop
#ret for boolean reagrading it returns or not
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#OpenCV reads colors as BGR (Blue Green Red),
# where most computer applications read as RGB
# (Red Green Blue)
out.write(frame)
cv2.imshow('FRAME',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cap.destroyAllWindows() | CoolCoder31/Machine_learning_and_analyze | MY_START/OpenCV/OpenCV1.py | OpenCV1.py | py | 677 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "cv2.VideoCapture",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "cv2.VideoWriter_fourcc",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "cv2.VideoWriter",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "cv2.cvtColor",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.