hexsha
stringlengths 40
40
| size
int64 1
1.03M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
239
| max_stars_repo_name
stringlengths 5
130
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
239
| max_issues_repo_name
stringlengths 5
130
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
239
| max_forks_repo_name
stringlengths 5
130
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 1
1.03M
| avg_line_length
float64 1
958k
| max_line_length
int64 1
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a0d9cf53c1d3b28d802fa0f4342100a5bae8636
| 14,493
|
py
|
Python
|
models/train_resnet_main.py
|
Lalit-garg/Gesture-Detection
|
fa405c57fa8497fbeb7b462968dd2534c32412cf
|
[
"MIT"
] | null | null | null |
models/train_resnet_main.py
|
Lalit-garg/Gesture-Detection
|
fa405c57fa8497fbeb7b462968dd2534c32412cf
|
[
"MIT"
] | null | null | null |
models/train_resnet_main.py
|
Lalit-garg/Gesture-Detection
|
fa405c57fa8497fbeb7b462968dd2534c32412cf
|
[
"MIT"
] | null | null | null |
import tensorflow as tf
import sys
import os
import numpy as np
import resnet_10 as resnet
import time
import pickle
import random
import argparse
from tensorflow.python.client import device_lib
from AdamWOptimizer import create_optimizer
def append_frames(cut_frame_array, required_num_frames):
appended_list_of_frames = list(cut_frame_array)
num_curr_frames = cut_frame_array.shape[0]
num_more_frames = required_num_frames - num_curr_frames
for i in range(num_more_frames):
appended_list_of_frames.append(cut_frame_array[i % num_curr_frames])
return np.array(appended_list_of_frames)
def train_neural_network(x_inpuT,
y_inpuT,
data_path,
val_data_path,
save_loss_path,
save_model_path,
batch_size,
val_batch_size,
learning_rate,
weight_decay,
epochs,
which_model,
num_val_videos,
random_clips,
win_size,
ignore_factor):
with tf.name_scope("cross_entropy"):
prediction = 0
if which_model == 1:
prediction = resnet.inference(x_inpuT)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y_inpuT))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
# optimizer = 0
if weight_decay is not None:
print("weight decay applied.")
optimizer = create_optimizer(cost, learning_rate, weight_decay)
else:
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
with tf.name_scope("accuracy"):
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y_inpuT, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
saver = tf.train.Saver()
gpu_options = tf.GPUOptions(allow_growth=True)
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
print("session starts!")
sess.run(tf.global_variables_initializer())
start_time = time.time()
epoch_loss_list = []
val_loss_list = []
pkl_files_list = os.listdir(data_path)
val_pkl_files_list = os.listdir(val_data_path)
for epoch in range(epochs):
print("Epoch {} started!".format(epoch + 1))
epoch_start_time = time.time()
epoch_loss = 0
train_acc = 0
num_batch_completed = 0
window_size = win_size
num_clips_per_video = random_clips
random.seed(7)
print("Random seed fixed for training.")
# pkl_files_list = pkl_files_list[ : 64]
num_videos = len(pkl_files_list) - (len(pkl_files_list) % batch_size)
num_blocks = int(num_videos / batch_size)
block_x = np.zeros((num_clips_per_video, batch_size, depth, height, width, 3))
block_y = np.zeros((num_clips_per_video, batch_size, num_classes))
for block_index in range(num_blocks):
for index_in_batch, pkl_file in enumerate(
pkl_files_list[block_index * batch_size: (block_index + 1) * batch_size]):
with open(os.path.join(data_path, pkl_file), 'rb') as f:
frames_and_label = pickle.load(f)
cut_frame_array = frames_and_label[0]
label = frames_and_label[1]
num_frames = cut_frame_array.shape[0]
required_num_frames = int(window_size * ignore_factor)
if num_frames <= required_num_frames:
# print(num_frames, required_num_frames)
cut_frame_array = append_frames(cut_frame_array, required_num_frames)
num_frames = cut_frame_array.shape[0]
# print(num_frames)
for batch_index in range(num_clips_per_video):
start_frame = random.randint(0, num_frames - window_size)
end_frame = start_frame + window_size
block_x[batch_index, index_in_batch, :, :, :, :] = np.array(
cut_frame_array[start_frame: end_frame, :, :, :])
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
block_y[batch_index, index_in_batch, :] = np.array(basic_label)
for batch_index in range(num_clips_per_video):
batch_start_time = time.time()
mini_batch_x = block_x[batch_index, :, :, :, :, :]
mini_batch_x = mini_batch_x / 255.0
mini_batch_y = block_y[batch_index, :, :]
perm = np.random.permutation(batch_size)
mini_batch_x = mini_batch_x[perm]
mini_batch_y = mini_batch_y[perm]
_optimizer, _cost, _prediction, _accuracy = sess.run([optimizer, cost, prediction, accuracy],
feed_dict={x_inpuT: mini_batch_x,
y_inpuT: mini_batch_y})
epoch_loss += _cost
train_acc += _accuracy
num_batch_completed += 1
batch_end_time = time.time()
log1 = "\rEpoch: {}, " \
"batches completed: {}, " \
"time taken: {:.5f}, " \
"loss: {:.6f}, " \
"accuracy: {:.4f} \n". \
format(
epoch + 1,
num_batch_completed,
batch_end_time - batch_start_time,
epoch_loss / (batch_size * num_batch_completed),
_accuracy)
print(log1)
sys.stdout.flush()
del block_x, block_y
# validation loss
val_loss = 0
val_acc = 0
val_num_batch_completed = 0
num_clips_per_video = 1
val_num_videos = num_val_videos
val_num_blocks = int(val_num_videos / val_batch_size)
val_block_x = np.zeros((num_clips_per_video, val_batch_size, depth, height, width, 3))
val_block_y = np.zeros((num_clips_per_video, val_batch_size, num_classes))
random.seed(23)
print("Random seed fixed for validation.")
for block_index in range(val_num_blocks):
for index_in_batch, val_pkl_file in enumerate(
val_pkl_files_list[block_index * val_batch_size: (block_index + 1) * val_batch_size]):
with open(os.path.join(val_data_path, val_pkl_file), 'rb') as f:
frames_and_label = pickle.load(f)
cut_frame_array = frames_and_label[0]
label = frames_and_label[1]
num_frames = cut_frame_array.shape[0]
required_num_frames = int(window_size * ignore_factor)
if num_frames <= window_size:
cut_frame_array = append_frames(cut_frame_array, required_num_frames)
num_frames = cut_frame_array.shape[0]
for batch_index in range(num_clips_per_video):
start_frame = random.randint(0, num_frames - window_size)
end_frame = start_frame + window_size
val_block_x[batch_index, index_in_batch, :, :, :, :] = np.array(
cut_frame_array[start_frame: end_frame, :, :, :])
basic_line = [0] * num_classes
basic_line[int(label) - 1] = 1
basic_label = basic_line
val_block_y[batch_index, index_in_batch, :] = np.array(basic_label)
for batch_index in range(num_clips_per_video):
val_batch_x = val_block_x[batch_index, :, :, :, :, :]
val_batch_x = val_batch_x / 255.0
val_batch_y = val_block_y[batch_index, :, :]
val_cost, val_batch_accuracy = sess.run([cost, accuracy],
feed_dict={x_inpuT: val_batch_x, y_inpuT: val_batch_y})
val_acc += val_batch_accuracy
val_loss += val_cost
val_num_batch_completed += 1
del val_block_x, val_block_y
epoch_loss = epoch_loss / (batch_size * num_batch_completed)
train_acc = train_acc / num_batch_completed
val_loss /= (val_batch_size * val_num_batch_completed)
val_acc = val_acc / val_num_batch_completed
epoch_end_time = time.time()
log3 = "Epoch {} done; " \
"Time Taken: {:.4f}s; " \
"Train_loss: {:.6f}; " \
"Val_loss: {:.6f}; " \
"Train_acc: {:.4f}; " \
"Val_acc: {:.4f}; " \
"Train batches: {}; " \
"Val batches: {};\n". \
format(epoch + 1, epoch_end_time - epoch_start_time, epoch_loss, val_loss, train_acc, val_acc,
num_batch_completed, val_num_batch_completed)
print(log3)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write(log3)
file1.close()
epoch_loss_list.append(epoch_loss)
val_loss_list.append(val_loss)
if save_model_path is not None:
saver.save(sess, save_model_path)
end_time = time.time()
print('Time elapse: ', str(end_time - start_time))
print(epoch_loss_list)
if save_loss_path is not None:
file1 = open(save_loss_path, "a")
file1.write("Train Loss List: {} \n".format(str(epoch_loss_list)))
file1.write("Val Loss List: {} \n".format(str(val_loss_list)))
file1.close()
if __name__ == '__main__':
np.random.seed(0)
parser = argparse.ArgumentParser()
parser.add_argument('-bs', action='store', dest='batch_size', type=int)
parser.add_argument('-vbs', action='store', dest='val_batch_size', type=int)
parser.add_argument('-lr', action='store', dest='learning_rate', type=float)
parser.add_argument('-wd', action='store', dest='weight_decay', type=float, const=None)
parser.add_argument('-e', action='store', dest='epochs', type=int)
parser.add_argument('-nvv', action='store', dest='num_val_videos', type=int)
parser.add_argument('-rc', action='store', dest='random_clips', type=int)
parser.add_argument('-ws', action='store', dest='win_size', type=int)
parser.add_argument('-slp', action='store', dest='save_loss_path', const=None)
parser.add_argument('-smp', action='store', dest='save_model_path', const=None)
parser.add_argument('-mn', action='store', dest='model_num', type=int)
parser.add_argument('-vd', action='store', dest='visible_devices')
parser.add_argument('-nd', action='store', dest='num_device', type=int)
parser.add_argument('-if', action='store', dest='ign_fact', type=float, const=None)
results = parser.parse_args()
arg_batch_size = results.batch_size
arg_val_batch_size = results.val_batch_size
arg_lr = results.learning_rate
arg_wd = results.weight_decay
arg_epochs = results.epochs
arg_num_val_videos = results.num_val_videos
arg_random_clips = results.random_clips
arg_win_size = results.win_size
arg_save_loss_path = results.save_loss_path
arg_save_model_path = results.save_model_path
arg_model_num = results.model_num
arg_visible_devices = results.visible_devices
arg_num_device = results.num_device
arg_ign_fact = results.ign_fact
data_path = "/home/axp798/axp798gallinahome/data/jester/train_64/"
val_data_path = "/home/axp798/axp798gallinahome/data/jester/valid_64/"
ar_save_loss_path = None
if arg_save_loss_path is not None:
ar_save_loss_path = "/home/axp798/axp798gallinahome/Gesture-Detection/models/loss_jester/{}".format(
arg_save_loss_path)
ar_save_model_path = None
if arg_save_model_path is not None:
path = '/home/axp798/axp798gallinahome/Gesture-Detection/models/saved_models_jester/{}/'.format(
arg_save_model_path)
if not os.path.exists(path):
os.mkdir(path)
ar_save_model_path = path + "model"
if ar_save_loss_path is not None:
file1 = open(ar_save_loss_path, "w")
file1.write("Params: {} \n".format(results))
file1.write("Losses: \n")
file1.close()
depth = arg_win_size
height = 64
width = 64
num_classes = 27
os.environ['CUDA_VISIBLE_DEVICES'] = "{}".format(arg_visible_devices)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
print(device_lib.list_local_devices())
choose_device = "/device:GPU:{}".format(arg_num_device)
with tf.device(choose_device):
x_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, depth, height, width, 3])
y_inpuT = tf.placeholder(tf.float32, shape=[arg_batch_size, num_classes])
train_neural_network(x_inpuT, y_inpuT, data_path, val_data_path,
save_loss_path=ar_save_loss_path,
save_model_path=ar_save_model_path,
batch_size=arg_batch_size,
learning_rate=arg_lr,
weight_decay=arg_wd,
epochs=arg_epochs,
val_batch_size=arg_val_batch_size,
which_model=arg_model_num,
num_val_videos=arg_num_val_videos,
random_clips=arg_random_clips,
win_size=arg_win_size,
ignore_factor=arg_ign_fact)
| 40.035912
| 115
| 0.567929
|
4a0d9ea110cbb3e2b1226784b889eadec72e9c5c
| 9,300
|
py
|
Python
|
ussd/tests/test_quiz_admin.py
|
dirkcuys/save4life
|
0dbc8feb0292e24177b8fcb4bd274dfc27f8264e
|
[
"BSD-3-Clause"
] | null | null | null |
ussd/tests/test_quiz_admin.py
|
dirkcuys/save4life
|
0dbc8feb0292e24177b8fcb4bd274dfc27f8264e
|
[
"BSD-3-Clause"
] | null | null | null |
ussd/tests/test_quiz_admin.py
|
dirkcuys/save4life
|
0dbc8feb0292e24177b8fcb4bd274dfc27f8264e
|
[
"BSD-3-Clause"
] | null | null | null |
from django.test import TestCase
from django.test import Client
from django.utils import timezone
from django.utils.timezone import utc
from django.contrib.auth.models import User
from ussd.models import Transaction
from ussd.models import Quiz
from ussd.models import Question
from ussd.models import Answer
from ussd.models import UssdUser
from ussd.models import Message
from ussd.transactions import award_joining_bonus
from mock import patch
from freezegun import freeze_time
from datetime import datetime, date, time
# Create your tests here.
class TestQuizAdmin(TestCase):
def setUp(self):
self.admin = User.objects.create_user('admin', 'admin@test.com', 'password')
self.admin.is_superuser = True
self.admin.is_staff = True
self.admin.save()
self.user = UssdUser.objects.create(
msisdn='27831112222',
name=u'Spongebob',
goal_item=u'Airtime',
goal_amount=50
)
# create a quiz
self.quiz = Quiz.objects.create(
publish_at=datetime(2016,10,31).replace(tzinfo=utc),
ends_at=datetime(2016,11,6).replace(tzinfo=utc)
)
self.questions = [
Question.objects.create(
quiz=self.quiz,
question='q1',
options='a,b,c,d',
reinforce_text='yeah, that was right',
solution=0
),
Question.objects.create(
quiz=self.quiz,
question='q2',
options='a,b,c,d',
reinforce_text='yeah, that was right',
solution=0
),
Question.objects.create(
quiz=self.quiz,
question='q3',
options='a,b,c,d',
reinforce_text='yeah, that was right',
solution=0
),
Question.objects.create(
quiz=self.quiz,
question='q4',
options='a,b,c,d',
reinforce_text='yeah, that was right',
solution=0
)
]
Answer.objects.create(question=self.questions[0], user=self.user, user_response=0)
Answer.objects.create(question=self.questions[1], user=self.user, user_response=0)
Answer.objects.create(question=self.questions[2], user=self.user, user_response=0)
Answer.objects.create(question=self.questions[3], user=self.user, user_response=0)
award_joining_bonus(self.user)
def test_award_quiz_prize(self):
c = Client()
c.login(username='admin', password='password')
data = {
'sms_text': 'Congratulations on winning the quiz this week'
}
balance = self.user.balance()
resp = c.post('/admin/ussd/quiz/1/award/{}/'.format(self.user.msisdn), data=data)
self.assertRedirects(resp, '/admin/ussd/quiz/1/results/')
self.assertEquals(Transaction.objects.filter(user=self.user, action=Transaction.QUIZ_PRIZE).count(), 1)
self.assertEquals(Transaction.objects.filter(user=self.user, action=Transaction.QUIZ_PRIZE).first().amount, balance)
self.assertEquals(Message.objects.all().count(), 1)
self.assertEquals(Message.objects.first().body, data['sms_text'])
def test_view_quiz_results(self):
c = Client()
c.login(username='admin', password='password')
resp = c.get('/admin/ussd/quiz/1/results/')
self.assertEquals(resp.status_code, 200)
self.assertEquals(len(resp.context['user_results']), 1)
def test_create_quiz(self):
c = Client()
c.login(username='admin', password='password')
data = {
'name': 'test_quiz',
'description': 'blah',
'publish_at_0': date(2016,1,1),
'publish_at_1': time(12,0),
'ends_at_0': date(2016,1,8),
'ends_at_1': time(12,0),
'reminder_text': 'This is a reminder. 1',
"question_set-TOTAL_FORMS": 4,
"question_set-INITIAL_FORMS": 0,
"question_set-MIN_NUM_FORMS": 4,
"question_set-MAX_NUM_FORMS": 4,
'question_set-0-question': 'Q1',
'question_set-0-options_0': 'O1',
'question_set-0-options_1': 'O2',
'question_set-0-options_2': 'O3',
'question_set-0-options_3': 'O4',
'question_set-0-reinforce_text': 'Reinforce',
'question_set-0-solution': 0,
'question_set-1-question': 'Q1',
'question_set-1-options_0': 'O1',
'question_set-1-options_1': 'O2',
'question_set-1-options_2': 'O3',
'question_set-1-options_3': 'O4',
'question_set-1-reinforce_text': 'Reinforce',
'question_set-1-solution': 0,
'question_set-2-question': 'Q1',
'question_set-2-options_0': 'O1',
'question_set-2-options_1': 'O2',
'question_set-2-options_2': 'O3',
'question_set-2-options_3': 'O4',
'question_set-2-reinforce_text': 'Reinforce',
'question_set-2-solution': 0,
'question_set-3-question': 'Q1',
'question_set-3-options_0': 'O1',
'question_set-3-options_1': 'O2',
'question_set-3-options_2': 'O3',
'question_set-3-options_3': 'O4',
'question_set-3-reinforce_text': 'Reinforce',
'question_set-3-solution': 0
}
resp = c.post('/admin/ussd/quiz/add/', data=data)
self.assertRedirects(resp, '/admin/ussd/quiz/')
self.assertEquals(Quiz.objects.all().count(), 2)
self.assertEquals(Question.objects.all().count(), 8)
self.assertEquals(Message.objects.all().count(), 1)
self.assertEquals(Message.objects.first().body, 'This is a reminder. 1')
def test_update_quiz(self):
c = Client()
c.login(username='admin', password='password')
data = {
'name': 'test_quiz',
'description': 'blah',
'publish_at_0': date(2016,1,1),
'publish_at_1': time(12,0),
'ends_at_0': date(2016,1,8),
'ends_at_1': time(12,0),
'reminder_text': 'This is a reminder. 1',
"question_set-TOTAL_FORMS": 4,
"question_set-INITIAL_FORMS": 0,
"question_set-MIN_NUM_FORMS": 4,
"question_set-MAX_NUM_FORMS": 4,
'question_set-0-question': 'Q1',
'question_set-0-options_0': 'O1',
'question_set-0-options_1': 'O2',
'question_set-0-options_2': 'O3',
'question_set-0-options_3': 'O4',
'question_set-0-reinforce_text': 'Reinforce',
'question_set-0-solution': 0,
'question_set-1-question': 'Q1',
'question_set-1-options_0': 'O1',
'question_set-1-options_1': 'O2',
'question_set-1-options_2': 'O3',
'question_set-1-options_3': 'O4',
'question_set-1-reinforce_text': 'Reinforce',
'question_set-1-solution': 0,
'question_set-2-question': 'Q1',
'question_set-2-options_0': 'O1',
'question_set-2-options_1': 'O2',
'question_set-2-options_2': 'O3',
'question_set-2-options_3': 'O4',
'question_set-2-reinforce_text': 'Reinforce',
'question_set-2-solution': 0,
'question_set-3-question': 'Q1',
'question_set-3-options_0': 'O1',
'question_set-3-options_1': 'O2',
'question_set-3-options_2': 'O3',
'question_set-3-options_3': 'O4',
'question_set-3-reinforce_text': 'Reinforce',
'question_set-3-solution': 0
}
resp = c.post('/admin/ussd/quiz/add/', data=data)
quiz = Quiz.objects.last()
reminder = Message.objects.first()
self.assertRedirects(resp, '/admin/ussd/quiz/')
self.assertEquals(Quiz.objects.all().count(), 2)
self.assertEquals(quiz.reminder, reminder)
self.assertEquals(reminder.body, 'This is a reminder. 1')
data['reminder_text'] = 'this is the new reminder'
resp = c.post('/admin/ussd/quiz/{0}/change/'.format(quiz.pk), data=data)
quiz = Quiz.objects.last()
reminder = Message.objects.first()
self.assertRedirects(resp, '/admin/ussd/quiz/')
self.assertEquals(Quiz.objects.all().count(), 2)
self.assertEquals(quiz.reminder, reminder)
self.assertEquals(reminder.body, 'this is the new reminder')
reminder.sent_at = datetime(2016,1,1,12,5).replace(tzinfo=utc)
reminder.save()
data['reminder_text'] = 'this is a reminder too late'
resp = c.post('/admin/ussd/quiz/{0}/change/'.format(quiz.pk), data=data, follow=True)
quiz = Quiz.objects.last()
reminder = Message.objects.first()
self.assertRedirects(resp, '/admin/ussd/quiz/')
self.assertEquals(Quiz.objects.all().count(), 2)
self.assertEquals(quiz.reminder, reminder)
self.assertEquals(reminder.body, 'this is the new reminder')
self.assertEquals(str(list(resp.context['messages'])[0]), 'The reminder SMS has already been sent')
| 41.150442
| 124
| 0.581828
|
4a0d9eaa76af0da376497b33ec69acb427847af0
| 17,903
|
py
|
Python
|
database/migrations/0005_auto_20210531_0929.py
|
bpprc/database
|
6e8302729793ddf840630840bd08c96ddd35a52e
|
[
"BSD-3-Clause"
] | 1
|
2021-04-14T16:54:57.000Z
|
2021-04-14T16:54:57.000Z
|
database/migrations/0005_auto_20210531_0929.py
|
bpprc/database
|
6e8302729793ddf840630840bd08c96ddd35a52e
|
[
"BSD-3-Clause"
] | null | null | null |
database/migrations/0005_auto_20210531_0929.py
|
bpprc/database
|
6e8302729793ddf840630840bd08c96ddd35a52e
|
[
"BSD-3-Clause"
] | null | null | null |
# Generated by Django 3.2.3 on 2021-05-31 14:29
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('database', '0004_auto_20210507_0114'),
]
operations = [
migrations.RemoveField(
model_name='pesticidalproteinhiddensequence',
name='private',
),
migrations.RemoveField(
model_name='pesticidalproteinhiddensequence',
name='toxicto',
),
migrations.RemoveField(
model_name='pesticidalproteinprivatedatabase',
name='private',
),
migrations.AlterField(
model_name='oldnamenewnametableleft',
name='alternative_name',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='oldnamenewnametableleft',
name='name_1998',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='oldnamenewnametableleft',
name='name_2020',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='oldnamenewnametableright',
name='alternative_name',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='oldnamenewnametableright',
name='name_1998',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='oldnamenewnametableright',
name='name_2020',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='admin_comments',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='comment',
field=models.TextField(blank=True, null=True, verbose_name='User comments'),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pesticidalproteindatabase_created_by', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='created_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Created on'),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='dnasequence',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='edited_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pesticidalproteindatabase_edited_by', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='edited_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Edited on'),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='name_category',
field=models.CharField(blank=True, max_length=15, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='nontoxic',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='oldname',
field=models.CharField(blank=True, max_length=105, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='othernames',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='pdbcode',
field=models.CharField(blank=True, max_length=10, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='predict_name',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='publication',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='published',
field=models.BooleanField(blank=True, choices=[(True, 'Yes'), (False, 'No')], default=False, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='submittersemail',
field=models.EmailField(blank=True, max_length=70, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='submittersname',
field=models.CharField(blank=True, default='Uploaded by default admin user', max_length=125, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='taxonid',
field=models.CharField(blank=True, max_length=25, null=True, validators=[django.core.validators.RegexValidator('\\d{25}', 'Number must digits', 'Invalid number')]),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='terms_conditions',
field=models.BooleanField(blank=True, choices=[(True, 'Yes'), (False, 'No')], default=False, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='toxicto',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteindatabase',
name='year',
field=models.CharField(blank=True, max_length=5, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='accession',
field=models.CharField(blank=True, max_length=25, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='bacterium_textbox',
field=models.CharField(blank=True, default='Bacillus Thuringiensis', max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='dnasequence',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='family',
field=models.CharField(blank=True, default='None', max_length=305, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='mammalian_active',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='name',
field=models.CharField(blank=True, max_length=15, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='nontoxic',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='oldname',
field=models.CharField(blank=True, max_length=305, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='othernames',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='partnerprotein_textbox',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='pdbcode',
field=models.CharField(blank=True, max_length=10, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='public',
field=models.BooleanField(blank=True, default=False, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='sequence',
field=models.TextField(null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='strain',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='submittersemail',
field=models.EmailField(blank=True, max_length=70, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='submittersname',
field=models.CharField(blank=True, max_length=25, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='taxonid',
field=models.CharField(blank=True, max_length=25, null=True, validators=[django.core.validators.RegexValidator('\\d{25}', 'Number must digits', 'Invalid number')]),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='terms_conditions',
field=models.BooleanField(blank=True, choices=[(True, 'Yes'), (False, 'No')], default=False, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='uploaded',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Uploaded'),
),
migrations.AlterField(
model_name='pesticidalproteinhiddensequence',
name='year',
field=models.CharField(blank=True, max_length=5, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='admin_comments',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='admin_user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='alignresults',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='bacterium_textbox',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='comment',
field=models.TextField(blank=True, null=True, verbose_name='User comments'),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pesticidalproteinprivatedatabase_created_by', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='created_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Created on'),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='dnasequence',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='edited_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pesticidalproteinprivatedatabase_edited_by', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='edited_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Edited on'),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='name_category',
field=models.CharField(blank=True, max_length=15, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='nontoxic',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='oldname',
field=models.CharField(blank=True, max_length=105, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='partnerprotein',
field=models.BooleanField(blank=True, choices=[(True, 'Yes'), (False, 'No')], default=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='partnerprotein_textbox',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='pdbcode',
field=models.CharField(blank=True, max_length=10, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='predict_name',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='publication',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='submittersemail',
field=models.EmailField(blank=True, max_length=70, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='submittersname',
field=models.CharField(blank=True, max_length=25, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='taxonid',
field=models.CharField(blank=True, max_length=25, null=True, validators=[django.core.validators.RegexValidator('\\d{25}', 'Number must digits', 'Invalid number')]),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='terms_conditions',
field=models.BooleanField(blank=True, choices=[(True, 'Yes'), (False, 'No')], default=False, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='toxicto',
field=models.CharField(blank=True, max_length=250, null=True),
),
migrations.AlterField(
model_name='pesticidalproteinprivatedatabase',
name='uploaded',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='Uploaded'),
),
migrations.AlterField(
model_name='structuredatabase',
name='accession',
field=models.CharField(blank=True, max_length=75, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='comment',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='modified',
field=models.CharField(blank=True, choices=[('yes', 'Yes'), ('no', 'No')], default='Yes', max_length=100, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='name',
field=models.CharField(blank=True, max_length=25, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='oldname',
field=models.CharField(blank=True, max_length=75, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='pubmedid',
field=models.CharField(blank=True, max_length=75, null=True),
),
migrations.AlterField(
model_name='structuredatabase',
name='year',
field=models.CharField(blank=True, max_length=5, null=True),
),
]
| 42.524941
| 193
| 0.614869
|
4a0da1ce02ab61a0622466a5af7a32de80fa2b50
| 5,596
|
py
|
Python
|
iceberg/simulate.py
|
wcwatson/iceberg
|
d73995ff6b364fe03f5f3d147c32698e67888674
|
[
"MIT"
] | 1
|
2020-06-28T17:59:37.000Z
|
2020-06-28T17:59:37.000Z
|
iceberg/simulate.py
|
wcwatson/iceberg
|
d73995ff6b364fe03f5f3d147c32698e67888674
|
[
"MIT"
] | null | null | null |
iceberg/simulate.py
|
wcwatson/iceberg
|
d73995ff6b364fe03f5f3d147c32698e67888674
|
[
"MIT"
] | null | null | null |
"""Exposes several functions that simulate situations illustrating the
capabilities of the estimators defined elsewhere in iceberg."""
import numpy as np
import iceberg.estimate as est
def identical_samples_save_one(n_samples=10, sample_size=10):
"""Simulates a collection of n_samples identical samples of size
sample_size, appends one unique entity to one sample, and calculates the BBC
estimate of the population size; Cuthbert's method is analytically solvable
and will yield sample_size as an estimate of the population.
Examples
--------
>>> identical_samples_save_one()
{'bbc': 12, 'cuthbert': 10}
Parameters
----------
n_samples: int
The number of samples to simulate.
sample_size: int
The (uniform) size of each sample.
Returns
-------
dict
A dictionary of estimates; the structure is { 'bbc': int, 'cuthbert':
int }.
Raises
------
ValueError
If n <=1.
"""
# Catch bad input
if n_samples <= 1:
raise ValueError('n must be greater than 1')
# Initialize result structure and simulate samples
results = {}
samples = [
[str(i) for i in range(sample_size)] for _ in range(n_samples)
]
samples[0].append(str(sample_size))
# Calculate BBC estimate
results['bbc'] = est.bbc(samples)
results['cuthbert'] = sample_size
# Return final results
return results
def unique_entities(n_samples=10, sample_size=10):
"""Simulates a collection of n_samples samples of size sample_size where no
entity is observed more than once, calculates the BBC estimate of the
population size, and calculates the uncorrected Cuthbert estimate after
repeating one entity to ensure convergence.
Examples
--------
>>> unique_entities()
{'bbc': 141, 'cuthbert': 4564}
>>> unique_entities(n_samples=100, sample_size=25)
{'bbc': 3503, 'cuthbert': 250000}
Parameters
----------
n_samples: int
The number of samples to simulate.
sample_size: int
The (uniform) size of each sample.
Returns
-------
dict
A dictionary of estimates; the structure is { 'bbc': int, 'cuthbert':
int }.
Raises
------
ValueError
If n <=1.
"""
# Catch bad input
if n_samples <= 1:
raise ValueError('n must be greater than 1')
# Initialize result structure and simulate samples
results = {}
samples = [
[str(sample_size * i + j) for j in range(sample_size)]
for i in range(n_samples)
]
# Calculate BBC estimate
results['bbc'] = est.bbc(samples)
# Append entity '0' to last sample to ensure Cuthbert convergence and
# calculate
samples[n_samples - 1].append('0')
results['cuthbert'] = est.cuthbert(samples)['uncorrected']
# Return final results
return results
def random_samples(pop_size, sample_sizes, n_samples=None):
"""Simulates a random collection of samples taken from a population of a
given size and returns BBC and (uncorrected) Cuthbert estimates of
population size. Can construct samples of uniform size or of varying size,
depending on the values of the parameters.
Examples
--------
>>> np.random.seed(1729)
>>> random_samples(1000, 20, 20)
{'entities_observed': 330, 'bbc': 449, 'cuthbert': 962}
>>> random_samples(10000, 20, 200)
{'entities_observed': 3297, 'bbc': 4483, 'cuthbert': 9960}
>>> random_samples(1000, [10, 10, 20, 20, 25, 25, 30, 40, 80, 160])
{'entities_observed': 359, 'bbc': 492, 'cuthbert': 1053}
Parameters
----------
pop_size: int
The size of the population to be simulated.
sample_sizes: list or int
If a list of ints, specifies the size of each sample individually. If an
int, the uniform size of all samples (in this case n_samples is
required).
n_samples: int
If sample_sizes is an int, then n_samples indicates the number of
uniformly sized samples that should be simulated.
Returns
-------
dict
A dictionary of estimates; the structure is { 'entities_observed': int,
'bbc': int, 'cuthbert': int }.
Raises
------
ValueError
If pop_size < sample_sizes or max(sample_sizes).
"""
# Catch bad input
if (
(isinstance(sample_sizes, int) and pop_size < sample_sizes)
or
(isinstance(sample_sizes, list) and pop_size < max(sample_sizes))
):
raise ValueError('pop_size must be larger than the largest sample size')
# Population of dummy entities
population = [str(i) for i in range(pop_size)]
# Simulate uniformly sized samples if sample_sizes is an integer
if isinstance(sample_sizes, int):
samples = [
np.random.choice(population, sample_sizes, replace=False).tolist()
for _ in range(n_samples)
]
# Simulate samples of varying size if sample_sizes is a list
elif isinstance(sample_sizes, list):
samples = [
np.random.choice(population, size, replace=False).tolist()
for size in sample_sizes
]
# Catch any other input
else:
raise TypeError('sample_sizes must either be a list or an int')
# Calculate and return results
results = {}
results['entities_observed'] = len(
set(entity for sample in samples for entity in sample)
)
results['bbc'] = est.bbc(samples)
results['cuthbert'] = est.cuthbert(samples)['uncorrected']
return results
| 31.088889
| 80
| 0.641708
|
4a0da249d4564371f693605bea1c6cf2f9a75fb5
| 39,450
|
py
|
Python
|
megacli/mega.py
|
BigSmokeCuba/3
|
c76711f5daa648ad858a246ddc401f36c49f836b
|
[
"Apache-2.0"
] | null | null | null |
megacli/mega.py
|
BigSmokeCuba/3
|
c76711f5daa648ad858a246ddc401f36c49f836b
|
[
"Apache-2.0"
] | null | null | null |
megacli/mega.py
|
BigSmokeCuba/3
|
c76711f5daa648ad858a246ddc401f36c49f836b
|
[
"Apache-2.0"
] | null | null | null |
import math
import re
import json
import logging
import secrets
from pathlib import Path
import hashlib
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Util import Counter
import os
import random
import binascii
import tempfile
import shutil
import requests
from tenacity import retry, wait_exponential, retry_if_exception_type
from errors import ValidationError, RequestError
from crypto import (a32_to_base64, encrypt_key, base64_url_encode,
encrypt_attr, base64_to_a32, base64_url_decode,
decrypt_attr, a32_to_str, get_chunks, str_to_a32,
decrypt_key, mpi_to_int, stringhash, prepare_key, make_id,
makebyte, modular_inverse)
logger = logging.getLogger(__name__)
class Mega:
def __init__(self, options=None):
self.schema = 'https'
self.domain = 'mega.co.nz'
self.timeout = 160 # max secs to wait for resp from api requests
self.sid = None
self.sequence_num = random.randint(0, 0xFFFFFFFF)
self.request_id = make_id(10)
self._trash_folder_node_id = None
self.stoping = False
if options is None:
options = {}
self.options = options
def stop(self):self.stoping = True
def login(self, email=None, password=None):
if email:
self._login_user(email, password)
else:
self.login_anonymous()
self._trash_folder_node_id = self.get_node_by_type(4)[0]
logger.info('Login complete')
return self
def _login_user(self, email, password):
logger.info('Logging in user...')
email = email.lower()
get_user_salt_resp = self._api_request({'a': 'us0', 'user': email})
user_salt = None
try:
user_salt = base64_to_a32(get_user_salt_resp['s'])
except KeyError:
# v1 user account
password_aes = prepare_key(str_to_a32(password))
user_hash = stringhash(email, password_aes)
else:
# v2 user account
pbkdf2_key = hashlib.pbkdf2_hmac(hash_name='sha512',
password=password.encode(),
salt=a32_to_str(user_salt),
iterations=100000,
dklen=32)
password_aes = str_to_a32(pbkdf2_key[:16])
user_hash = base64_url_encode(pbkdf2_key[-16:])
resp = self._api_request({'a': 'us', 'user': email, 'uh': user_hash})
if isinstance(resp, int):
raise RequestError(resp)
self._login_process(resp, password_aes)
def login_anonymous(self):
logger.info('Logging in anonymous temporary user...')
master_key = [random.randint(0, 0xFFFFFFFF)] * 4
password_key = [random.randint(0, 0xFFFFFFFF)] * 4
session_self_challenge = [random.randint(0, 0xFFFFFFFF)] * 4
user = self._api_request({
'a':
'up',
'k':
a32_to_base64(encrypt_key(master_key, password_key)),
'ts':
base64_url_encode(
a32_to_str(session_self_challenge) +
a32_to_str(encrypt_key(session_self_challenge, master_key)))
})
resp = self._api_request({'a': 'us', 'user': user})
if isinstance(resp, int):
raise RequestError(resp)
self._login_process(resp, password_key)
def _login_process(self, resp, password):
encrypted_master_key = base64_to_a32(resp['k'])
self.master_key = decrypt_key(encrypted_master_key, password)
if 'tsid' in resp:
tsid = base64_url_decode(resp['tsid'])
key_encrypted = a32_to_str(
encrypt_key(str_to_a32(tsid[:16]), self.master_key))
if key_encrypted == tsid[-16:]:
self.sid = resp['tsid']
elif 'csid' in resp:
encrypted_rsa_private_key = base64_to_a32(resp['privk'])
rsa_private_key = decrypt_key(encrypted_rsa_private_key,
self.master_key)
private_key = a32_to_str(rsa_private_key)
# The private_key contains 4 MPI integers concatenated together.
rsa_private_key = [0, 0, 0, 0]
for i in range(4):
# An MPI integer has a 2-byte header which describes the number
# of bits in the integer.
bitlength = (private_key[0] * 256) + private_key[1]
bytelength = math.ceil(bitlength / 8)
# Add 2 bytes to accommodate the MPI header
bytelength += 2
rsa_private_key[i] = mpi_to_int(private_key[:bytelength])
private_key = private_key[bytelength:]
first_factor_p = rsa_private_key[0]
second_factor_q = rsa_private_key[1]
private_exponent_d = rsa_private_key[2]
# In MEGA's webclient javascript, they assign [3] to a variable
# called u, but I do not see how it corresponds to pycryptodome's
# RSA.construct and it does not seem to be necessary.
rsa_modulus_n = first_factor_p * second_factor_q
phi = (first_factor_p - 1) * (second_factor_q - 1)
public_exponent_e = modular_inverse(private_exponent_d, phi)
rsa_components = (
rsa_modulus_n,
public_exponent_e,
private_exponent_d,
first_factor_p,
second_factor_q,
)
rsa_decrypter = RSA.construct(rsa_components)
encrypted_sid = mpi_to_int(base64_url_decode(resp['csid']))
sid = '%x' % rsa_decrypter._decrypt(encrypted_sid)
sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid)
self.sid = base64_url_encode(sid[:43])
@retry(retry=retry_if_exception_type(RuntimeError),
wait=wait_exponential(multiplier=2, min=2, max=60))
def _api_request(self, data):
params = {'id': self.sequence_num}
self.sequence_num += 1
if self.sid:
params.update({'sid': self.sid})
# ensure input data is a list
if not isinstance(data, list):
data = [data]
url = f'{self.schema}://g.api.{self.domain}/cs'
response = requests.post(
url,
params=params,
data=json.dumps(data),
timeout=self.timeout,
)
json_resp = json.loads(response.text)
try:
if isinstance(json_resp, list):
int_resp = json_resp[0] if isinstance(json_resp[0],
int) else None
elif isinstance(json_resp, int):
int_resp = json_resp
except IndexError:
int_resp = None
if int_resp is not None:
if int_resp == 0:
return int_resp
if int_resp == -3:
msg = 'Request failed, retrying'
logger.info(msg)
raise RuntimeError(msg)
raise RequestError(int_resp)
return json_resp[0]
def _parse_url(self, url):
"""Parse file id and key from url."""
if '/file/' in url:
# V2 URL structure
url = url.replace(' ', '')
file_id = re.findall(r'\W\w\w\w\w\w\w\w\w\W', url)[0][1:-1]
id_index = re.search(file_id, url).end()
key = url[id_index + 1:]
return f'{file_id}!{key}'
elif '!' in url:
# V1 URL structure
match = re.findall(r'/#!(.*)', url)
path = match[0]
return path
else:
raise RequestError('Url key missing')
def _process_file(self, file, shared_keys):
if file['t'] == 0 or file['t'] == 1:
keys = dict(
keypart.split(':', 1) for keypart in file['k'].split('/')
if ':' in keypart)
uid = file['u']
key = None
# my objects
if uid in keys:
key = decrypt_key(base64_to_a32(keys[uid]), self.master_key)
# shared folders
elif 'su' in file and 'sk' in file and ':' in file['k']:
shared_key = decrypt_key(base64_to_a32(file['sk']),
self.master_key)
key = decrypt_key(base64_to_a32(keys[file['h']]), shared_key)
if file['su'] not in shared_keys:
shared_keys[file['su']] = {}
shared_keys[file['su']][file['h']] = shared_key
# shared files
elif file['u'] and file['u'] in shared_keys:
for hkey in shared_keys[file['u']]:
shared_key = shared_keys[file['u']][hkey]
if hkey in keys:
key = keys[hkey]
key = decrypt_key(base64_to_a32(key), shared_key)
break
if file['h'] and file['h'] in shared_keys.get('EXP', ()):
shared_key = shared_keys['EXP'][file['h']]
encrypted_key = str_to_a32(
base64_url_decode(file['k'].split(':')[-1]))
key = decrypt_key(encrypted_key, shared_key)
file['shared_folder_key'] = shared_key
if key is not None:
# file
if file['t'] == 0:
k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6],
key[3] ^ key[7])
file['iv'] = key[4:6] + (0, 0)
file['meta_mac'] = key[6:8]
# folder
else:
k = key
file['key'] = key
file['k'] = k
attributes = base64_url_decode(file['a'])
attributes = decrypt_attr(attributes, k)
file['a'] = attributes
# other => wrong object
elif file['k'] == '':
file['a'] = False
elif file['t'] == 2:
self.root_id = file['h']
file['a'] = {'n': 'Cloud Drive'}
elif file['t'] == 3:
self.inbox_id = file['h']
file['a'] = {'n': 'Inbox'}
elif file['t'] == 4:
self.trashbin_id = file['h']
file['a'] = {'n': 'Rubbish Bin'}
return file
def _init_shared_keys(self, files, shared_keys):
"""
Init shared key not associated with a user.
Seems to happen when a folder is shared,
some files are exchanged and then the
folder is un-shared.
Keys are stored in files['s'] and files['ok']
"""
ok_dict = {}
for ok_item in files['ok']:
shared_key = decrypt_key(base64_to_a32(ok_item['k']),
self.master_key)
ok_dict[ok_item['h']] = shared_key
for s_item in files['s']:
if s_item['u'] not in shared_keys:
shared_keys[s_item['u']] = {}
if s_item['h'] in ok_dict:
shared_keys[s_item['u']][s_item['h']] = ok_dict[s_item['h']]
self.shared_keys = shared_keys
def find_path_descriptor(self, path, files=()):
"""
Find descriptor of folder inside a path. i.e.: folder1/folder2/folder3
Params:
path, string like folder1/folder2/folder3
Return:
Descriptor (str) of folder3 if exists, None otherwise
"""
paths = path.split('/')
files = files or self.get_files()
parent_desc = self.root_id
found = False
for foldername in paths:
if foldername != '':
for file in files.items():
if (file[1]['a'] and file[1]['t']
and file[1]['a']['n'] == foldername):
if parent_desc == file[1]['p']:
parent_desc = file[0]
found = True
if found:
found = False
else:
return None
return parent_desc
def find(self, filename=None, handle=None, exclude_deleted=False):
"""
Return file object from given filename
"""
files = self.get_files()
if handle:
return files[handle]
path = Path(filename)
filename = path.name
parent_dir_name = path.parent.name
for file in list(files.items()):
parent_node_id = None
try:
if parent_dir_name:
parent_node_id = self.find_path_descriptor(parent_dir_name,
files=files)
if (filename and parent_node_id and file[1]['a']
and file[1]['a']['n'] == filename
and parent_node_id == file[1]['p']):
if (exclude_deleted and self._trash_folder_node_id
== file[1]['p']):
continue
return file
elif (filename and file[1]['a']
and file[1]['a']['n'] == filename):
if (exclude_deleted
and self._trash_folder_node_id == file[1]['p']):
continue
return file
except TypeError:
continue
def get_files(self):
logger.info('Getting all files...')
files = self._api_request({'a': 'f', 'c': 1, 'r': 1})
files_dict = {}
shared_keys = {}
self._init_shared_keys(files, shared_keys)
for file in files['f']:
processed_file = self._process_file(file, shared_keys)
# ensure each file has a name before returning
if processed_file['a']:
files_dict[file['h']] = processed_file
return files_dict
def get_upload_link(self, file):
"""
Get a files public link inc. decrypted key
Requires upload() response as input
"""
if 'f' in file:
file = file['f'][0]
public_handle = self._api_request({'a': 'l', 'n': file['h']})
file_key = file['k'][file['k'].index(':') + 1:]
decrypted_key = a32_to_base64(
decrypt_key(base64_to_a32(file_key), self.master_key))
return (f'{self.schema}://{self.domain}'
f'/#!{public_handle}!{decrypted_key}')
else:
raise ValueError('''Upload() response required as input,
use get_link() for regular file input''')
def get_link(self, file):
"""
Get a file public link from given file object
"""
file = file[1]
if 'h' in file and 'k' in file:
public_handle = self._api_request({'a': 'l', 'n': file['h']})
if public_handle == -11:
raise RequestError("Can't get a public link from that file "
"(is this a shared file?)")
decrypted_key = a32_to_base64(file['key'])
return (f'{self.schema}://{self.domain}'
f'/#!{public_handle}!{decrypted_key}')
else:
raise ValidationError('File id and key must be present')
def _node_data(self, node):
try:
return node[1]
except (IndexError, KeyError):
return node
def get_folder_link(self, file):
try:
file = file[1]
except (IndexError, KeyError):
pass
if 'h' in file and 'k' in file:
public_handle = self._api_request({'a': 'l', 'n': file['h']})
if public_handle == -11:
raise RequestError("Can't get a public link from that file "
"(is this a shared file?)")
decrypted_key = a32_to_base64(file['shared_folder_key'])
return (f'{self.schema}://{self.domain}'
f'/#F!{public_handle}!{decrypted_key}')
else:
raise ValidationError('File id and key must be present')
def get_user(self):
user_data = self._api_request({'a': 'ug'})
return user_data
def get_node_by_type(self, type):
"""
Get a node by it's numeric type id, e.g:
0: file
1: dir
2: special: root cloud drive
3: special: inbox
4: special trash bin
"""
nodes = self.get_files()
for node in list(nodes.items()):
if node[1]['t'] == type:
return node
def get_files_in_node(self, target):
"""
Get all files in a given target, e.g. 4=trash
"""
if type(target) == int:
# convert special nodes (e.g. trash)
node_id = self.get_node_by_type(target)
else:
node_id = [target]
files = self._api_request({'a': 'f', 'c': 1})
files_dict = {}
shared_keys = {}
self._init_shared_keys(files, shared_keys)
for file in files['f']:
processed_file = self._process_file(file, shared_keys)
if processed_file['a'] and processed_file['p'] == node_id[0]:
files_dict[file['h']] = processed_file
return files_dict
def get_id_from_public_handle(self, public_handle):
# get node data
node_data = self._api_request({'a': 'f', 'f': 1, 'p': public_handle})
node_id = self.get_id_from_obj(node_data)
return node_id
def get_id_from_obj(self, node_data):
"""
Get node id from a file object
"""
node_id = None
for i in node_data['f']:
if i['h'] != '':
node_id = i['h']
return node_id
def get_quota(self):
"""
Get current remaining disk quota in MegaBytes
"""
json_resp = self._api_request({
'a': 'uq',
'xfer': 1,
'strg': 1,
'v': 1
})
# convert bytes to megabyes
return json_resp['mstrg'] / 1048576
def get_storage_space(self, giga=False, mega=False, kilo=False):
"""
Get the current storage space.
Return a dict containing at least:
'used' : the used space on the account
'total' : the maximum space allowed with current plan
All storage space are in bytes unless asked differently.
"""
if sum(1 if x else 0 for x in (kilo, mega, giga)) > 1:
raise ValueError("Only one unit prefix can be specified")
unit_coef = 1
if kilo:
unit_coef = 1024
if mega:
unit_coef = 1048576
if giga:
unit_coef = 1073741824
json_resp = self._api_request({'a': 'uq', 'xfer': 1, 'strg': 1})
return {
'used': json_resp['cstrg'] / unit_coef,
'total': json_resp['mstrg'] / unit_coef,
}
def get_balance(self):
"""
Get account monetary balance, Pro accounts only
"""
user_data = self._api_request({"a": "uq", "pro": 1})
if 'balance' in user_data:
return user_data['balance']
def delete(self, public_handle):
"""
Delete a file by its public handle
"""
return self.move(public_handle, 4)
def delete_url(self, url):
"""
Delete a file by its url
"""
path = self._parse_url(url).split('!')
public_handle = path[0]
file_id = self.get_id_from_public_handle(public_handle)
return self.move(file_id, 4)
def destroy(self, file_id):
"""
Destroy a file by its private id
"""
return self._api_request({
'a': 'd',
'n': file_id,
'i': self.request_id
})
def destroy_url(self, url):
"""
Destroy a file by its url
"""
path = self._parse_url(url).split('!')
public_handle = path[0]
file_id = self.get_id_from_public_handle(public_handle)
return self.destroy(file_id)
def empty_trash(self):
# get list of files in rubbish out
files = self.get_files_in_node(4)
# make a list of json
if files != {}:
post_list = []
for file in files:
post_list.append({"a": "d", "n": file, "i": self.request_id})
return self._api_request(post_list)
def download(self, file, dest_path=None, dest_filename=None):
"""
Download a file by it's file object
"""
return self._download_file(file_handle=None,
file_key=None,
file=file[1],
dest_path=dest_path,
dest_filename=dest_filename,
is_public=False)
def _export_file(self, node):
node_data = self._node_data(node)
self._api_request([{
'a': 'l',
'n': node_data['h'],
'i': self.request_id
}])
return self.get_link(node)
def export(self, path=None, node_id=None):
nodes = self.get_files()
if node_id:
node = nodes[node_id]
else:
node = self.find(path)
node_data = self._node_data(node)
is_file_node = node_data['t'] == 0
if is_file_node:
return self._export_file(node)
if node:
try:
# If already exported
return self.get_folder_link(node)
except (RequestError, KeyError):
pass
master_key_cipher = AES.new(a32_to_str(self.master_key), AES.MODE_ECB)
ha = base64_url_encode(
master_key_cipher.encrypt(node_data['h'].encode("utf8") +
node_data['h'].encode("utf8")))
share_key = secrets.token_bytes(16)
ok = base64_url_encode(master_key_cipher.encrypt(share_key))
share_key_cipher = AES.new(share_key, AES.MODE_ECB)
node_key = node_data['k']
encrypted_node_key = base64_url_encode(
share_key_cipher.encrypt(a32_to_str(node_key)))
node_id = node_data['h']
request_body = [{
'a':
's2',
'n':
node_id,
's': [{
'u': 'EXP',
'r': 0
}],
'i':
self.request_id,
'ok':
ok,
'ha':
ha,
'cr': [[node_id], [node_id], [0, 0, encrypted_node_key]]
}]
self._api_request(request_body)
nodes = self.get_files()
return self.get_folder_link(nodes[node_id])
def download_url(self, url, dest_path=None, dest_filename=None,progressfunc=None,args=()):
"""
Download a file by it's public url
"""
path = self._parse_url(url).split('!')
file_id = path[0]
file_key = path[1]
return self._download_file(
file_handle=file_id,
file_key=file_key,
dest_path=dest_path,
dest_filename=dest_filename,
is_public=True,
progressfunc=progressfunc,
args=args
)
def _download_file(self,
file_handle,
file_key,
dest_path=None,
dest_filename=None,
is_public=False,
file=None,
progressfunc=None,
args=None,
f_data=None):
if file is None:
if is_public:
file_key = base64_to_a32(file_key)
file_data = self._api_request({
'a': 'g',
'g': 1,
'p': file_handle
})
else:
if f_data is None:
file_data = self._api_request({
'a': 'g',
'g': 1,
'n': file_handle
})
else:
file_data = f_data
k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5],
file_key[2] ^ file_key[6], file_key[3] ^ file_key[7])
iv = file_key[4:6] + (0, 0)
meta_mac = file_key[6:8]
else:
file_data = self._api_request({'a': 'g', 'g': 1, 'n': file['h']})
k = file['k']
iv = file['iv']
meta_mac = file['meta_mac']
# Seems to happens sometime... When this occurs, files are
# inaccessible also in the official also in the official web app.
# Strangely, files can come back later.
if 'g' not in file_data:
raise RequestError('File not accessible anymore')
file_url = file_data['g']
file_size = file_data['s']
attribs = base64_url_decode(file_data['at'])
attribs = decrypt_attr(attribs, k)
if dest_filename is not None:
file_name = dest_filename
else:
file_name = attribs['n']
import time
chunk_por = 0
chunkrandom = 100
total = file_size
time_start = time.time()
time_total = 0
size_per_second = 0
input_file = requests.get(file_url, stream=True).raw
if dest_path is None:
dest_path = ''
else:
dest_path += '/'
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='megapy_',
delete=False) as temp_output_file:
k_str = a32_to_str(k)
counter = Counter.new(128,
initial_value=((iv[0] << 32) + iv[1]) << 64)
aes = AES.new(k_str, AES.MODE_CTR, counter=counter)
mac_str = '\0' * 16
mac_encryptor = AES.new(k_str, AES.MODE_CBC,
mac_str.encode("utf8"))
iv_str = a32_to_str([iv[0], iv[1], iv[0], iv[1]])
for chunk_start, chunk_size in get_chunks(file_size):
chunk = input_file.read(chunk_size)
#funcion de progres
if self.stoping:break
chunk_por += len(chunk)
size_per_second+=len(chunk);
tcurrent = time.time() - time_start
time_total += tcurrent
time_start = time.time()
if time_total>=1:
if progressfunc:
progressfunc(self,file_name,chunk_por,file_size,size_per_second,args)
time_total = 0
size_per_second = 0
chunk = aes.decrypt(chunk)
temp_output_file.write(chunk)
encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
for i in range(0, len(chunk) - 16, 16):
block = chunk[i:i + 16]
encryptor.encrypt(block)
# fix for files under 16 bytes failing
if file_size > 16:
i += 16
else:
i = 0
block = chunk[i:i + 16]
if len(block) % 16:
block += b'\0' * (16 - (len(block) % 16))
mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))
file_info = os.stat(temp_output_file.name)
logger.info('%s of %s downloaded', file_info.st_size,
file_size)
file_mac = str_to_a32(mac_str)
# check mac integrity
if (file_mac[0] ^ file_mac[1],
file_mac[2] ^ file_mac[3]) != meta_mac:
raise ValueError('Mismatched mac')
output_path = Path(dest_path + file_name)
shutil.move(temp_output_file.name, output_path)
return output_path
def upload(self, filename, dest=None, dest_filename=None):
# determine storage node
if dest is None:
# if none set, upload to cloud drive node
if not hasattr(self, 'root_id'):
self.get_files()
dest = self.root_id
# request upload url, call 'u' method
with open(filename, 'rb') as input_file:
file_size = os.path.getsize(filename)
ul_url = self._api_request({'a': 'u', 's': file_size})['p']
# generate random aes key (128) for file
ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
k_str = a32_to_str(ul_key[:4])
count = Counter.new(
128, initial_value=((ul_key[4] << 32) + ul_key[5]) << 64)
aes = AES.new(k_str, AES.MODE_CTR, counter=count)
upload_progress = 0
completion_file_handle = None
mac_str = '\0' * 16
mac_encryptor = AES.new(k_str, AES.MODE_CBC,
mac_str.encode("utf8"))
iv_str = a32_to_str([ul_key[4], ul_key[5], ul_key[4], ul_key[5]])
if file_size > 0:
for chunk_start, chunk_size in get_chunks(file_size):
chunk = input_file.read(chunk_size)
upload_progress += len(chunk)
encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
for i in range(0, len(chunk) - 16, 16):
block = chunk[i:i + 16]
encryptor.encrypt(block)
# fix for files under 16 bytes failing
if file_size > 16:
i += 16
else:
i = 0
block = chunk[i:i + 16]
if len(block) % 16:
block += makebyte('\0' * (16 - len(block) % 16))
mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))
# encrypt file and upload
chunk = aes.encrypt(chunk)
output_file = requests.post(ul_url + "/" +
str(chunk_start),
data=chunk,
timeout=self.timeout)
completion_file_handle = output_file.text
logger.info('%s of %s uploaded', upload_progress,
file_size)
else:
output_file = requests.post(ul_url + "/0",
data='',
timeout=self.timeout)
completion_file_handle = output_file.text
logger.info('Chunks uploaded')
logger.info('Setting attributes to complete upload')
logger.info('Computing attributes')
file_mac = str_to_a32(mac_str)
# determine meta mac
meta_mac = (file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3])
dest_filename = dest_filename or os.path.basename(filename)
attribs = {'n': dest_filename}
encrypt_attribs = base64_url_encode(
encrypt_attr(attribs, ul_key[:4]))
key = [
ul_key[0] ^ ul_key[4], ul_key[1] ^ ul_key[5],
ul_key[2] ^ meta_mac[0], ul_key[3] ^ meta_mac[1], ul_key[4],
ul_key[5], meta_mac[0], meta_mac[1]
]
encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
logger.info('Sending request to update attributes')
# update attributes
data = self._api_request({
'a':
'p',
't':
dest,
'i':
self.request_id,
'n': [{
'h': completion_file_handle,
't': 0,
'a': encrypt_attribs,
'k': encrypted_key
}]
})
logger.info('Upload complete')
return data
def _mkdir(self, name, parent_node_id):
# generate random aes key (128) for folder
ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
# encrypt attribs
attribs = {'n': name}
encrypt_attribs = base64_url_encode(encrypt_attr(attribs, ul_key[:4]))
encrypted_key = a32_to_base64(encrypt_key(ul_key[:4], self.master_key))
# update attributes
data = self._api_request({
'a':
'p',
't':
parent_node_id,
'n': [{
'h': 'xxxxxxxx',
't': 1,
'a': encrypt_attribs,
'k': encrypted_key
}],
'i':
self.request_id
})
return data
def _root_node_id(self):
if not hasattr(self, 'root_id'):
self.get_files()
return self.root_id
def create_folder(self, name, dest=None):
dirs = tuple(dir_name for dir_name in str(name).split('/') if dir_name)
folder_node_ids = {}
for idx, directory_name in enumerate(dirs):
existing_node_id = self.find_path_descriptor(directory_name)
if existing_node_id:
folder_node_ids[idx] = existing_node_id
continue
if idx == 0:
if dest is None:
parent_node_id = self._root_node_id()
else:
parent_node_id = dest
else:
parent_node_id = folder_node_ids[idx - 1]
created_node = self._mkdir(name=directory_name,
parent_node_id=parent_node_id)
node_id = created_node['f'][0]['h']
folder_node_ids[idx] = node_id
return dict(zip(dirs, folder_node_ids.values()))
def rename(self, file, new_name):
file = file[1]
# create new attribs
attribs = {'n': new_name}
# encrypt attribs
encrypt_attribs = base64_url_encode(encrypt_attr(attribs, file['k']))
encrypted_key = a32_to_base64(encrypt_key(file['key'],
self.master_key))
# update attributes
return self._api_request([{
'a': 'a',
'attr': encrypt_attribs,
'key': encrypted_key,
'n': file['h'],
'i': self.request_id
}])
def move(self, file_id, target):
"""
Move a file to another parent node
params:
a : command
n : node we're moving
t : id of target parent node, moving to
i : request id
targets
2 : root
3 : inbox
4 : trash
or...
target's id
or...
target's structure returned by find()
"""
# determine target_node_id
if type(target) == int:
target_node_id = str(self.get_node_by_type(target)[0])
elif type(target) in (str, ):
target_node_id = target
else:
file = target[1]
target_node_id = file['h']
return self._api_request({
'a': 'm',
'n': file_id,
't': target_node_id,
'i': self.request_id
})
def add_contact(self, email):
"""
Add another user to your mega contact list
"""
return self._edit_contact(email, True)
def remove_contact(self, email):
"""
Remove a user to your mega contact list
"""
return self._edit_contact(email, False)
def _edit_contact(self, email, add):
"""
Editing contacts
"""
if add is True:
l = '1' # add command
elif add is False:
l = '0' # remove command
else:
raise ValidationError('add parameter must be of type bool')
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
ValidationError('add_contact requires a valid email address')
else:
return self._api_request({
'a': 'ur',
'u': email,
'l': l,
'i': self.request_id
})
def get_public_url_info(self, url):
"""
Get size and name from a public url, dict returned
"""
file_handle, file_key = self._parse_url(url).split('!')
return self.get_public_file_info(file_handle, file_key)
def import_public_url(self, url, dest_node=None, dest_name=None):
"""
Import the public url into user account
"""
file_handle, file_key = self._parse_url(url).split('!')
return self.import_public_file(file_handle,
file_key,
dest_node=dest_node,
dest_name=dest_name)
def get_public_file_info(self, file_handle, file_key):
"""
Get size and name of a public file
"""
data = self._api_request({'a': 'g', 'p': file_handle, 'ssm': 1})
if isinstance(data, int):
raise RequestError(data)
if 'at' not in data or 's' not in data:
raise ValueError("Unexpected result", data)
key = base64_to_a32(file_key)
k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6],
key[3] ^ key[7])
size = data['s']
unencrypted_attrs = decrypt_attr(base64_url_decode(data['at']), k)
if not unencrypted_attrs:
return None
result = {'size': size, 'name': unencrypted_attrs['n']}
return result
def import_public_file(self,
file_handle,
file_key,
dest_node=None,
dest_name=None):
"""
Import the public file into user account
"""
# Providing dest_node spare an API call to retrieve it.
if dest_node is None:
# Get '/Cloud Drive' folder no dest node specified
dest_node = self.get_node_by_type(2)[1]
# Providing dest_name spares an API call to retrieve it.
if dest_name is None:
pl_info = self.get_public_file_info(file_handle, file_key)
dest_name = pl_info['name']
key = base64_to_a32(file_key)
k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6],
key[3] ^ key[7])
encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
encrypted_name = base64_url_encode(encrypt_attr({'n': dest_name}, k))
return self._api_request({
'a':
'p',
't':
dest_node['h'],
'n': [{
'ph': file_handle,
't': 0,
'a': encrypted_name,
'k': encrypted_key
}]
})
| 35.961714
| 94
| 0.500684
|
4a0da30849706682cd628384a408a112fd8e8baa
| 32,100
|
py
|
Python
|
yolact.py
|
kaylode/Clothes-Segmentation
|
3b46d23e33753474878a0898c7cded0755396767
|
[
"MIT"
] | 4
|
2020-10-21T14:20:11.000Z
|
2021-12-13T01:33:17.000Z
|
yolact.py
|
kaylode/Trash-Segmentation
|
3b46d23e33753474878a0898c7cded0755396767
|
[
"MIT"
] | 1
|
2020-10-16T12:55:18.000Z
|
2020-10-21T14:21:01.000Z
|
yolact.py
|
kaylode/Trash-Segmentation
|
3b46d23e33753474878a0898c7cded0755396767
|
[
"MIT"
] | 1
|
2022-01-27T13:19:28.000Z
|
2022-01-27T13:19:28.000Z
|
import torch, torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import Bottleneck
import numpy as np
from itertools import product
from math import sqrt
from typing import List
from collections import defaultdict
from data.config import cfg, mask_type
from layers import Detect
from layers.interpolate import InterpolateModule
from backbone import construct_backbone
from efficientdet.model import BiFPN
import torch.backends.cudnn as cudnn
from utils import timer
from utils.functions import MovingAverage, make_net
from efficient_utils import load_pretrained_weights
# This is required for Pytorch 1.0.1 on Windows to initialize Cuda on some driver versions.
# See the bug report here: https://github.com/pytorch/pytorch/issues/17108
torch.cuda.current_device()
# As of March 10, 2019, Pytorch DataParallel still doesn't support JIT Script Modules
use_jit = torch.cuda.device_count() <= 1
if not use_jit:
print('Multiple GPUs detected! Turning off JIT.')
ScriptModuleWrapper = torch.jit.ScriptModule if use_jit else nn.Module
script_method_wrapper = torch.jit.script_method if use_jit else lambda fn, _rcn=None: fn
class Concat(nn.Module):
def __init__(self, nets, extra_params):
super().__init__()
self.nets = nn.ModuleList(nets)
self.extra_params = extra_params
def forward(self, x):
# Concat each along the channel dimension
return torch.cat([net(x) for net in self.nets], dim=1, **self.extra_params)
prior_cache = defaultdict(lambda: None)
class PredictionModule(nn.Module):
"""
The (c) prediction module adapted from DSSD:
https://arxiv.org/pdf/1701.06659.pdf
Note that this is slightly different to the module in the paper
because the Bottleneck block actually has a 3x3 convolution in
the middle instead of a 1x1 convolution. Though, I really can't
be arsed to implement it myself, and, who knows, this might be
better.
Args:
- in_channels: The input feature size.
- out_channels: The output feature size (must be a multiple of 4).
- aspect_ratios: A list of lists of priorbox aspect ratios (one list per scale).
- scales: A list of priorbox scales relative to this layer's convsize.
For instance: If this layer has convouts of size 30x30 for
an image of size 600x600, the 'default' (scale
of 1) for this layer would produce bounding
boxes with an area of 20x20px. If the scale is
.5 on the other hand, this layer would consider
bounding boxes with area 10x10px, etc.
- parent: If parent is a PredictionModule, this module will use all the layers
from parent instead of from this module.
"""
def __init__(self, in_channels, out_channels=1024, aspect_ratios=[[1]], scales=[1], parent=None, index=0):
super().__init__()
self.num_classes = cfg.num_classes
self.mask_dim = cfg.mask_dim # Defined by Yolact
self.num_priors = sum(len(x)*len(scales) for x in aspect_ratios)
self.parent = [parent] # Don't include this in the state dict
self.index = index
self.num_heads = cfg.num_heads # Defined by Yolact
if cfg.mask_proto_split_prototypes_by_head and cfg.mask_type == mask_type.lincomb:
self.mask_dim = self.mask_dim // self.num_heads
if cfg.mask_proto_prototypes_as_features:
in_channels += self.mask_dim
if parent is None:
if cfg.extra_head_net is None:
out_channels = in_channels
else:
self.upfeature, out_channels = make_net(in_channels, cfg.extra_head_net)
if cfg.use_prediction_module:
self.block = Bottleneck(out_channels, out_channels // 4)
self.conv = nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=True)
self.bn = nn.BatchNorm2d(out_channels)
self.bbox_layer = nn.Conv2d(out_channels, self.num_priors * 4, **cfg.head_layer_params)
self.conf_layer = nn.Conv2d(out_channels, self.num_priors * self.num_classes, **cfg.head_layer_params)
self.mask_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, **cfg.head_layer_params)
if cfg.use_mask_scoring:
self.score_layer = nn.Conv2d(out_channels, self.num_priors, **cfg.head_layer_params)
if cfg.use_instance_coeff:
self.inst_layer = nn.Conv2d(out_channels, self.num_priors * cfg.num_instance_coeffs, **cfg.head_layer_params)
# What is this ugly lambda doing in the middle of all this clean prediction module code?
def make_extra(num_layers):
if num_layers == 0:
return lambda x: x
else:
# Looks more complicated than it is. This just creates an array of num_layers alternating conv-relu
return nn.Sequential(*sum([[
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
] for _ in range(num_layers)], []))
self.bbox_extra, self.conf_extra, self.mask_extra = [make_extra(x) for x in cfg.extra_layers]
if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_coeff_gate:
self.gate_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, kernel_size=3, padding=1)
self.aspect_ratios = aspect_ratios
self.scales = scales
self.priors = None
self.last_conv_size = None
self.last_img_size = None
def forward(self, x):
"""
Args:
- x: The convOut from a layer in the backbone network
Size: [batch_size, in_channels, conv_h, conv_w])
Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes
- bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]
- class_confs: [batch_size, conv_h*conv_w*num_priors, num_classes]
- mask_output: [batch_size, conv_h*conv_w*num_priors, mask_dim]
- prior_boxes: [conv_h*conv_w*num_priors, 4]
"""
# In case we want to use another module's layers
src = self if self.parent[0] is None else self.parent[0]
conv_h = x.size(2)
conv_w = x.size(3)
if cfg.extra_head_net is not None:
x = src.upfeature(x)
if cfg.use_prediction_module:
# The two branches of PM design (c)
a = src.block(x)
b = src.conv(x)
b = src.bn(b)
b = F.relu(b)
# TODO: Possibly switch this out for a product
x = a + b
bbox_x = src.bbox_extra(x)
conf_x = src.conf_extra(x)
mask_x = src.mask_extra(x)
bbox = src.bbox_layer(bbox_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 4)
conf = src.conf_layer(conf_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.num_classes)
if cfg.eval_mask_branch:
mask = src.mask_layer(mask_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)
else:
mask = torch.zeros(x.size(0), bbox.size(1), self.mask_dim, device=bbox.device)
if cfg.use_mask_scoring:
score = src.score_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 1)
if cfg.use_instance_coeff:
inst = src.inst_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, cfg.num_instance_coeffs)
# See box_utils.decode for an explanation of this
if cfg.use_yolo_regressors:
bbox[:, :, :2] = torch.sigmoid(bbox[:, :, :2]) - 0.5
bbox[:, :, 0] /= conv_w
bbox[:, :, 1] /= conv_h
if cfg.eval_mask_branch:
if cfg.mask_type == mask_type.direct:
mask = torch.sigmoid(mask)
elif cfg.mask_type == mask_type.lincomb:
mask = cfg.mask_proto_coeff_activation(mask)
if cfg.mask_proto_coeff_gate:
gate = src.gate_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)
mask = mask * torch.sigmoid(gate)
if cfg.mask_proto_split_prototypes_by_head and cfg.mask_type == mask_type.lincomb:
mask = F.pad(mask, (self.index * self.mask_dim, (self.num_heads - self.index - 1) * self.mask_dim), mode='constant', value=0)
priors = self.make_priors(conv_h, conv_w, x.device)
preds = { 'loc': bbox, 'conf': conf, 'mask': mask, 'priors': priors }
if cfg.use_mask_scoring:
preds['score'] = score
if cfg.use_instance_coeff:
preds['inst'] = inst
return preds
def make_priors(self, conv_h, conv_w, device):
""" Note that priors are [x,y,width,height] where (x,y) is the center of the box. """
global prior_cache
size = (conv_h, conv_w)
with timer.env('makepriors'):
if self.last_img_size != (cfg._tmp_img_w, cfg._tmp_img_h):
prior_data = []
# Iteration order is important (it has to sync up with the convout)
for j, i in product(range(conv_h), range(conv_w)):
# +0.5 because priors are in center-size notation
x = (i + 0.5) / conv_w
y = (j + 0.5) / conv_h
for ars in self.aspect_ratios:
for scale in self.scales:
for ar in ars:
if not cfg.backbone.preapply_sqrt:
ar = sqrt(ar)
if cfg.backbone.use_pixel_scales:
w = scale * ar / cfg.max_size
h = scale / ar / cfg.max_size
else:
w = scale * ar / conv_w
h = scale / ar / conv_h
# This is for backward compatability with a bug where I made everything square by accident
if cfg.backbone.use_square_anchors:
h = w
prior_data += [x, y, w, h]
self.priors = torch.Tensor(prior_data, device=device).view(-1, 4).detach()
self.priors.requires_grad = False
self.last_img_size = (cfg._tmp_img_w, cfg._tmp_img_h)
self.last_conv_size = (conv_w, conv_h)
prior_cache[size] = None
elif self.priors.device != device:
# This whole weird situation is so that DataParalell doesn't copy the priors each iteration
if prior_cache[size] is None:
prior_cache[size] = {}
if device not in prior_cache[size]:
prior_cache[size][device] = self.priors.to(device)
self.priors = prior_cache[size][device]
return self.priors
class FPN(ScriptModuleWrapper):
"""
Implements a general version of the FPN introduced in
https://arxiv.org/pdf/1612.03144.pdf
Parameters (in cfg.fpn):
- num_features (int): The number of output features in the fpn layers.
- interpolation_mode (str): The mode to pass to F.interpolate.
- num_downsample (int): The number of downsampled layers to add onto the selected layers.
These extra layers are downsampled from the last selected layer.
Args:
- in_channels (list): For each conv layer you supply in the forward pass,
how many features will it have?
"""
__constants__ = ['interpolation_mode', 'num_downsample', 'use_conv_downsample', 'relu_pred_layers',
'lat_layers', 'pred_layers', 'downsample_layers', 'relu_downsample_layers']
def __init__(self, in_channels):
super().__init__()
self.lat_layers = nn.ModuleList([
nn.Conv2d(x, cfg.fpn.num_features, kernel_size=1)
for x in reversed(in_channels)
])
# This is here for backwards compatability
padding = 1 if cfg.fpn.pad else 0
self.pred_layers = nn.ModuleList([
nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=padding)
for _ in in_channels
])
if cfg.fpn.use_conv_downsample:
self.downsample_layers = nn.ModuleList([
nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=1, stride=2)
for _ in range(cfg.fpn.num_downsample)
])
self.interpolation_mode = cfg.fpn.interpolation_mode
self.num_downsample = cfg.fpn.num_downsample
self.use_conv_downsample = cfg.fpn.use_conv_downsample
self.relu_downsample_layers = cfg.fpn.relu_downsample_layers
self.relu_pred_layers = cfg.fpn.relu_pred_layers
@script_method_wrapper
def forward(self, convouts:List[torch.Tensor]):
"""
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
"""
out = []
x = torch.zeros(1, device=convouts[0].device)
for i in range(len(convouts)):
out.append(x)
# For backward compatability, the conv layers are stored in reverse but the input and output is
# given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.
j = len(convouts)
for lat_layer in self.lat_layers:
j -= 1
if j < len(convouts) - 1:
_, _, h, w = convouts[j].size()
x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)
x = x + lat_layer(convouts[j])
out[j] = x
# This janky second loop is here because TorchScript.
j = len(convouts)
for pred_layer in self.pred_layers:
j -= 1
out[j] = pred_layer(out[j])
if self.relu_pred_layers:
F.relu(out[j], inplace=True)
cur_idx = len(out)
# In the original paper, this takes care of P6
if self.use_conv_downsample:
for downsample_layer in self.downsample_layers:
out.append(downsample_layer(out[-1]))
else:
for idx in range(self.num_downsample):
# Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.
out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))
if self.relu_downsample_layers:
for idx in range(len(out) - cur_idx):
out[idx] = F.relu(out[idx + cur_idx], inplace=False)
return out
class FastMaskIoUNet(ScriptModuleWrapper):
def __init__(self):
super().__init__()
input_channels = 1
last_layer = [(cfg.num_classes-1, 1, {})]
self.maskiou_net, _ = make_net(input_channels, cfg.maskiou_net + last_layer, include_last_relu=True)
def forward(self, x):
x = self.maskiou_net(x)
maskiou_p = F.max_pool2d(x, kernel_size=x.size()[2:]).squeeze(-1).squeeze(-1)
return maskiou_p
def BiFPNLayers(num_filters, conv_channel_coef, fpn_cell_repeats, load_weights = False):
bifpn = nn.Sequential(
*[BiFPN(num_filters,
conv_channel_coef,
True if _ == 0 else False,
attention=True)
for _ in range(fpn_cell_repeats)])
if load_weights:
load_pretrained_weights(bifpn, 'efficientnet-b6', load_bifpn = load_weights)
return bifpn
class Yolact(nn.Module):
"""
██╗ ██╗ ██████╗ ██╗ █████╗ ██████╗████████╗
╚██╗ ██╔╝██╔═══██╗██║ ██╔══██╗██╔════╝╚══██╔══╝
╚████╔╝ ██║ ██║██║ ███████║██║ ██║
╚██╔╝ ██║ ██║██║ ██╔══██║██║ ██║
██║ ╚██████╔╝███████╗██║ ██║╚██████╗ ██║
╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝
You can set the arguments by changing them in the backbone config object in config.py.
Parameters (in cfg.backbone):
- selected_layers: The indices of the conv layers to use for prediction.
- pred_scales: A list with len(selected_layers) containing tuples of scales (see PredictionModule)
- pred_aspect_ratios: A list of lists of aspect ratios with len(selected_layers) (see PredictionModule)
"""
def __init__(self):
super().__init__()
self.backbone = construct_backbone(cfg.backbone)
if cfg.freeze_bn:
self.freeze_bn()
# Compute mask_dim here and add it back to the config. Make sure Yolact's constructor is called early!
if cfg.mask_type == mask_type.direct:
cfg.mask_dim = cfg.mask_size**2
elif cfg.mask_type == mask_type.lincomb:
if cfg.mask_proto_use_grid:
self.grid = torch.Tensor(np.load(cfg.mask_proto_grid_file))
self.num_grids = self.grid.size(0)
else:
self.num_grids = 0
self.proto_src = cfg.mask_proto_src
if self.proto_src is None: in_channels = 3
elif cfg.fpn is not None: in_channels = cfg.fpn.num_features
else: in_channels = self.backbone.channels[self.proto_src]
in_channels += self.num_grids
# The include_last_relu=false here is because we might want to change it to another function
self.proto_net, cfg.mask_dim = make_net(in_channels, cfg.mask_proto_net, include_last_relu=False)
if cfg.mask_proto_bias:
cfg.mask_dim += 1
self.selected_layers = cfg.backbone.selected_layers
src_channels = self.backbone.channels
if cfg.use_maskiou:
self.maskiou_net = FastMaskIoUNet()
if cfg.fpn is not None:
# Some hacky rewiring to accomodate the FPN
if cfg.use_bifpn:
self.fpn = BiFPNLayers(
self.backbone.fpn_num_filters[self.backbone.compound_coef],
self.backbone.conv_channel_coef[self.backbone.compound_coef],
self.backbone.fpn_cell_repeats[self.backbone.compound_coef], load_weights=False)
else:
self.fpn = FPN([src_channels[i] for i in self.selected_layers])
self.selected_layers = list(range(len(self.selected_layers) + cfg.fpn.num_downsample))
src_channels = [cfg.fpn.num_features] * len(self.selected_layers)
self.prediction_layers = nn.ModuleList()
cfg.num_heads = len(self.selected_layers)
for idx, layer_idx in enumerate(self.selected_layers):
# If we're sharing prediction module weights, have every module's parent be the first one
parent = None
if cfg.share_prediction_module and idx > 0:
parent = self.prediction_layers[0]
pred = PredictionModule(src_channels[layer_idx], src_channels[layer_idx],
aspect_ratios = cfg.backbone.pred_aspect_ratios[idx],
scales = cfg.backbone.pred_scales[idx],
parent = parent,
index = idx)
self.prediction_layers.append(pred)
# Extra parameters for the extra losses
if cfg.use_class_existence_loss:
# This comes from the smallest layer selected
# Also note that cfg.num_classes includes background
self.class_existence_fc = nn.Linear(src_channels[-1], cfg.num_classes - 1)
if cfg.use_semantic_segmentation_loss:
self.semantic_seg_conv = nn.Conv2d(src_channels[0], cfg.num_classes-1, kernel_size=1)
# For use in evaluation
self.detect = Detect(cfg.num_classes, bkg_label=0, top_k=cfg.nms_top_k,
conf_thresh=cfg.nms_conf_thresh, nms_thresh=cfg.nms_thresh)
def save_weights(self, path):
""" Saves the model's weights using compression because the file sizes were getting too big. """
torch.save(self.state_dict(), path)
def load_weights(self, path):
""" Loads weights from a compressed save file. """
state_dict = torch.load(path)
# For backward compatability, remove these (the new variable is called layers)
for key in list(state_dict.keys()):
if key.startswith('backbone.layer') and not key.startswith('backbone.layers'):
del state_dict[key]
# Also for backward compatibility with v1.0 weights, do this check
if key.startswith('fpn.downsample_layers.'):
if cfg.fpn is not None and int(key.split('.')[2]) >= cfg.fpn.num_downsample:
del state_dict[key]
self.load_state_dict(state_dict)
def init_weights(self, backbone_path):
""" Initialize weights for training. """
# Initialize the backbone with the pretrained weights.
self.backbone.init_backbone(backbone_path)
conv_constants = getattr(nn.Conv2d(1, 1, 1), '__constants__')
# Quick lambda to test if one list contains the other
def all_in(x, y):
for _x in x:
if _x not in y:
return False
return True
# Initialize the rest of the conv layers with xavier
for name, module in self.named_modules():
# See issue #127 for why we need such a complicated condition if the module is a WeakScriptModuleProxy
# Broke in 1.3 (see issue #175), WeakScriptModuleProxy was turned into just ScriptModule.
# Broke in 1.4 (see issue #292), where RecursiveScriptModule is the new star of the show.
# Note that this might break with future pytorch updates, so let me know if it does
is_script_conv = False
if 'Script' in type(module).__name__:
# 1.4 workaround: now there's an original_name member so just use that
if hasattr(module, 'original_name'):
is_script_conv = 'Conv' in module.original_name
# 1.3 workaround: check if this has the same constants as a conv module
else:
is_script_conv = (
all_in(module.__dict__['_constants_set'], conv_constants)
and all_in(conv_constants, module.__dict__['_constants_set']))
is_conv_layer = isinstance(module, nn.Conv2d) or is_script_conv
if is_conv_layer and module not in self.backbone.backbone_modules:
nn.init.xavier_uniform_(module.weight.data)
if module.bias is not None:
if cfg.use_focal_loss and 'conf_layer' in name:
if not cfg.use_sigmoid_focal_loss:
# Initialize the last layer as in the focal loss paper.
# Because we use softmax and not sigmoid, I had to derive an alternate expression
# on a notecard. Define pi to be the probability of outputting a foreground detection.
# Then let z = sum(exp(x)) - exp(x_0). Finally let c be the number of foreground classes.
# Chugging through the math, this gives us
# x_0 = log(z * (1 - pi) / pi) where 0 is the background class
# x_i = log(z / c) for all i > 0
# For simplicity (and because we have a degree of freedom here), set z = 1. Then we have
# x_0 = log((1 - pi) / pi) note: don't split up the log for numerical stability
# x_i = -log(c) for all i > 0
module.bias.data[0] = np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)
module.bias.data[1:] = -np.log(module.bias.size(0) - 1)
else:
module.bias.data[0] = -np.log(cfg.focal_loss_init_pi / (1 - cfg.focal_loss_init_pi))
module.bias.data[1:] = -np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)
else:
module.bias.data.zero_()
def train(self, mode=True):
super().train(mode)
if cfg.freeze_bn:
self.freeze_bn()
def freeze_bn(self, enable=False):
""" Adapted from https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/8 """
for module in self.modules():
if isinstance(module, nn.BatchNorm2d):
module.train() if enable else module.eval()
module.weight.requires_grad = enable
module.bias.requires_grad = enable
def forward(self, x):
""" The input should be of size [batch_size, 3, img_h, img_w] """
_, _, img_h, img_w = x.size()
cfg._tmp_img_h = img_h
cfg._tmp_img_w = img_w
with timer.env('backbone'):
outs = self.backbone(x)
if cfg.fpn is not None:
with timer.env('fpn'):
# Use backbone.selected_layers because we overwrote self.selected_layers
outs = [outs[i] for i in cfg.backbone.selected_layers]
outs = self.fpn(outs)
proto_out = None
if cfg.mask_type == mask_type.lincomb and cfg.eval_mask_branch:
with timer.env('proto'):
proto_x = x if self.proto_src is None else outs[self.proto_src]
if self.num_grids > 0:
grids = self.grid.repeat(proto_x.size(0), 1, 1, 1)
proto_x = torch.cat([proto_x, grids], dim=1)
proto_out = self.proto_net(proto_x)
proto_out = cfg.mask_proto_prototype_activation(proto_out)
if cfg.mask_proto_prototypes_as_features:
# Clone here because we don't want to permute this, though idk if contiguous makes this unnecessary
proto_downsampled = proto_out.clone()
if cfg.mask_proto_prototypes_as_features_no_grad:
proto_downsampled = proto_out.detach()
# Move the features last so the multiplication is easy
proto_out = proto_out.permute(0, 2, 3, 1).contiguous()
if cfg.mask_proto_bias:
bias_shape = [x for x in proto_out.size()]
bias_shape[-1] = 1
proto_out = torch.cat([proto_out, torch.ones(*bias_shape)], -1)
with timer.env('pred_heads'):
pred_outs = { 'loc': [], 'conf': [], 'mask': [], 'priors': [] }
if cfg.use_mask_scoring:
pred_outs['score'] = []
if cfg.use_instance_coeff:
pred_outs['inst'] = []
for idx, pred_layer in zip(self.selected_layers, self.prediction_layers):
pred_x = outs[idx]
if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_prototypes_as_features:
# Scale the prototypes down to the current prediction layer's size and add it as inputs
proto_downsampled = F.interpolate(proto_downsampled, size=outs[idx].size()[2:], mode='bilinear', align_corners=False)
pred_x = torch.cat([pred_x, proto_downsampled], dim=1)
# A hack for the way dataparallel works
if cfg.share_prediction_module and pred_layer is not self.prediction_layers[0]:
pred_layer.parent = [self.prediction_layers[0]]
p = pred_layer(pred_x)
for k, v in p.items():
pred_outs[k].append(v)
for k, v in pred_outs.items():
pred_outs[k] = torch.cat(v, -2)
if proto_out is not None:
pred_outs['proto'] = proto_out
if self.training:
# For the extra loss functions
if cfg.use_class_existence_loss:
pred_outs['classes'] = self.class_existence_fc(outs[-1].mean(dim=(2, 3)))
if cfg.use_semantic_segmentation_loss:
pred_outs['segm'] = self.semantic_seg_conv(outs[0])
return pred_outs
else:
if cfg.use_mask_scoring:
pred_outs['score'] = torch.sigmoid(pred_outs['score'])
if cfg.use_focal_loss:
if cfg.use_sigmoid_focal_loss:
# Note: even though conf[0] exists, this mode doesn't train it so don't use it
pred_outs['conf'] = torch.sigmoid(pred_outs['conf'])
if cfg.use_mask_scoring:
pred_outs['conf'] *= pred_outs['score']
elif cfg.use_objectness_score:
# See focal_loss_sigmoid in multibox_loss.py for details
objectness = torch.sigmoid(pred_outs['conf'][:, :, 0])
pred_outs['conf'][:, :, 1:] = objectness[:, :, None] * F.softmax(pred_outs['conf'][:, :, 1:], -1)
pred_outs['conf'][:, :, 0 ] = 1 - objectness
else:
pred_outs['conf'] = F.softmax(pred_outs['conf'], -1)
else:
if cfg.use_objectness_score:
objectness = torch.sigmoid(pred_outs['conf'][:, :, 0])
pred_outs['conf'][:, :, 1:] = (objectness > 0.10)[..., None] \
* F.softmax(pred_outs['conf'][:, :, 1:], dim=-1)
else:
pred_outs['conf'] = F.softmax(pred_outs['conf'], -1)
return self.detect(pred_outs, self)
# Some testing code
if __name__ == '__main__':
from utils.functions import init_console
init_console()
# Use the first argument to set the config if you want
import sys
if len(sys.argv) > 1:
from data.config import set_cfg
set_cfg(sys.argv[1])
net = Yolact()
net.train()
net.init_weights(backbone_path='weights/' + cfg.backbone.path)
# GPU
net = net.cuda()
torch.set_default_tensor_type('torch.cuda.FloatTensor')
x = torch.zeros((1, 3, cfg.max_size, cfg.max_size))
y = net(x)
for p in net.prediction_layers:
print(p.last_conv_size)
print()
for k, a in y.items():
print(k + ': ', a.size(), torch.sum(a))
exit()
net(x)
# timer.disable('pass2')
avg = MovingAverage()
try:
while True:
timer.reset()
with timer.env('everything else'):
net(x)
avg.add(timer.total_time())
print('\033[2J') # Moves console cursor to 0,0
timer.print_stats()
print('Avg fps: %.2f\tAvg ms: %.2f ' % (1/avg.get_avg(), avg.get_avg()*1000))
except KeyboardInterrupt:
pass
| 42.8
| 137
| 0.569688
|
4a0da3ef8bc7919cf403c6118a2831480bd389bb
| 6,190
|
py
|
Python
|
samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py
|
thalescpl-io/openapi-generator
|
586386fd69e978380c39cdcd919365cd175be988
|
[
"Apache-2.0"
] | null | null | null |
samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py
|
thalescpl-io/openapi-generator
|
586386fd69e978380c39cdcd919365cd175be988
|
[
"Apache-2.0"
] | null | null | null |
samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py
|
thalescpl-io/openapi-generator
|
586386fd69e978380c39cdcd919365cd175be988
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F401
import six # noqa: F401
import nulltype # noqa: F401
from petstore_api.model_utils import ( # noqa: F401
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
int,
none_type,
str,
validate_get_composed_info,
)
class AdditionalPropertiesArray(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
additional_properties_type = ([bool, date, datetime, dict, float, int, list, str],) # noqa: E501
@cached_property
def openapi_types():
"""
This must be a class method so a model may have properties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
'name': (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'name': 'name', # noqa: E501
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, _check_type=True, _spec_property_naming=False, _path_to_item=(), _configuration=None, _visited_composed_classes=(), **kwargs): # noqa: E501
"""additional_properties_array.AdditionalPropertiesArray - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in six.iteritems(kwargs):
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
| 39.935484
| 174
| 0.595315
|
4a0da4532100ef691e1dff75991e168bc07d7253
| 888
|
py
|
Python
|
cifar10/edition1/__init__.py
|
nowgood/ComputeVersion
|
f2475570bfb33779b2a71bb9da03f12ffe5609c5
|
[
"Apache-2.0"
] | null | null | null |
cifar10/edition1/__init__.py
|
nowgood/ComputeVersion
|
f2475570bfb33779b2a71bb9da03f12ffe5609c5
|
[
"Apache-2.0"
] | null | null | null |
cifar10/edition1/__init__.py
|
nowgood/ComputeVersion
|
f2475570bfb33779b2a71bb9da03f12ffe5609c5
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Makes helper libraries available in the cifar10 package."""
''''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
'''
import edition1
| 37
| 80
| 0.703829
|
4a0da5dbc9f425362b481d4b71513561cd5a7c9f
| 1,523
|
py
|
Python
|
order/models.py
|
devsingh-code/Django-ecommerce
|
35d93ca0c81f0bf2bafda1e8285c2a0a32a441eb
|
[
"MIT"
] | 1
|
2020-06-13T11:23:40.000Z
|
2020-06-13T11:23:40.000Z
|
order/models.py
|
devsingh-code/Django-ecommerce
|
35d93ca0c81f0bf2bafda1e8285c2a0a32a441eb
|
[
"MIT"
] | null | null | null |
order/models.py
|
devsingh-code/Django-ecommerce
|
35d93ca0c81f0bf2bafda1e8285c2a0a32a441eb
|
[
"MIT"
] | null | null | null |
from django.db import models
class Order(models.Model):
token = models.CharField(max_length=250, blank=True)
total = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Order Total')
emailAddress = models.EmailField(max_length=250, blank=True, verbose_name='Email Address')
created = models.DateTimeField(auto_now_add=True)
billingName = models.CharField(max_length=250, blank=True)
billingAddress1 = models.CharField(max_length=250, blank=True)
billingCity = models.CharField(max_length=250, blank=True)
billingPostcode = models.CharField(max_length=10, blank=True)
billingCountry = models.CharField(max_length=200, blank=True)
shippingName = models.CharField(max_length=250, blank=True)
shippingAddress1 = models.CharField(max_length=250, blank=True)
shippingCity = models.CharField(max_length=250, blank=True)
shippingPostcode = models.CharField(max_length=10, blank=True)
shippingCountry = models.CharField(max_length=200, blank=True)
class Meta:
db_table = 'Order'
ordering = ['-created'] # -created for in order to have latest on top
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.CharField(max_length=250)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Price')
order = models.ForeignKey(Order, on_delete=models.CASCADE)
class Meta:
db_table = 'OrderItem'
def sub_total(self):
return self.quantity * self.price
def __str__(self):
return self.product
| 37.146341
| 93
| 0.779383
|
4a0da5f39b973c29780b79c2e334652bac2c44d7
| 1,125
|
py
|
Python
|
src/food.py
|
wmontgomery4/cells
|
4193ef8556d9a0e6e4fdc23f802ae218909cabd5
|
[
"MIT"
] | null | null | null |
src/food.py
|
wmontgomery4/cells
|
4193ef8556d9a0e6e4fdc23f802ae218909cabd5
|
[
"MIT"
] | null | null | null |
src/food.py
|
wmontgomery4/cells
|
4193ef8556d9a0e6e4fdc23f802ae218909cabd5
|
[
"MIT"
] | null | null | null |
"""
Basic food class, just provides energy for cells.
"""
import pymunk as pm
import math
import random
import collision
# Physics constants.
RADIUS = 3
ENERGY = 15
DENSITY = 1e-4
FRICTION = 0.3
class Food():
""" Container class for food bodies. """
def __init__(self):
""" Initialize food particle. """
# Initialize body.
mass = DENSITY * RADIUS**2
moment = pm.moment_for_circle(mass, 0, RADIUS, (0,0))
self.body = pm.Body(mass, moment)
# Initialize shape.
self.shape = pm.Circle(self.body, RADIUS, (0,0))
self.shape.color = (255, 255, 255)
self.shape.friction = FRICTION
self.shape.collision_type = collision.FOOD
self.shape.filter = pm.ShapeFilter(categories=collision.FOOD)
self.eaten = False
self.energy = ENERGY
# Store reference to self in shape for collisons.
# TODO: This feels hacky, sign of bad design?
self.shape.food = self
def remove(self):
""" Remove self from space. """
self.eaten = True
self.body.space.remove(self.body, self.shape)
| 24.456522
| 69
| 0.616889
|
4a0da710a42c3cbdb2242f2eaeb88b5579c5f30a
| 18,211
|
py
|
Python
|
ml-agents-envs/mlagents_envs/tests/test_rpc_utils.py
|
rabienrose/ml-agents
|
6de68f2247498f9accc05b59353faa3c7f09d370
|
[
"Apache-2.0"
] | 1
|
2021-01-04T09:13:59.000Z
|
2021-01-04T09:13:59.000Z
|
ml-agents-envs/mlagents_envs/tests/test_rpc_utils.py
|
guplem/ml-agents
|
87c9a0b170fe805138ca69abffac8d4a59cd731d
|
[
"Apache-2.0"
] | null | null | null |
ml-agents-envs/mlagents_envs/tests/test_rpc_utils.py
|
guplem/ml-agents
|
87c9a0b170fe805138ca69abffac8d4a59cd731d
|
[
"Apache-2.0"
] | null | null | null |
import io
import numpy as np
import pytest
from typing import List, Tuple
from mlagents_envs.communicator_objects.agent_info_pb2 import AgentInfoProto
from mlagents_envs.communicator_objects.observation_pb2 import (
ObservationProto,
NONE,
PNG,
)
from mlagents_envs.communicator_objects.brain_parameters_pb2 import BrainParametersProto
from mlagents_envs.communicator_objects.agent_info_action_pair_pb2 import (
AgentInfoActionPairProto,
)
from mlagents_envs.communicator_objects.agent_action_pb2 import AgentActionProto
from mlagents_envs.base_env import (
BehaviorSpec,
ActionSpec,
DecisionSteps,
TerminalSteps,
)
from mlagents_envs.exception import UnityObservationException
from mlagents_envs.rpc_utils import (
behavior_spec_from_proto,
process_pixels,
_process_visual_observation,
_process_vector_observation,
steps_from_proto,
)
from PIL import Image
from mlagents.trainers.tests.dummy_config import create_sensor_specs_with_shapes
def generate_list_agent_proto(
n_agent: int,
shape: List[Tuple[int]],
infinite_rewards: bool = False,
nan_observations: bool = False,
) -> List[AgentInfoProto]:
result = []
for agent_index in range(n_agent):
ap = AgentInfoProto()
ap.reward = float("inf") if infinite_rewards else agent_index
ap.done = agent_index % 2 == 0
ap.max_step_reached = agent_index % 4 == 0
ap.id = agent_index
ap.action_mask.extend([True, False] * 5)
obs_proto_list = []
for obs_index in range(len(shape)):
obs_proto = ObservationProto()
obs_proto.shape.extend(list(shape[obs_index]))
obs_proto.compression_type = NONE
obs_proto.float_data.data.extend(
([float("nan")] if nan_observations else [0.1])
* np.prod(shape[obs_index])
)
obs_proto_list.append(obs_proto)
ap.observations.extend(obs_proto_list)
result.append(ap)
return result
def generate_compressed_data(in_array: np.ndarray) -> bytes:
image_arr = (in_array * 255).astype(np.uint8)
bytes_out = bytes()
num_channels = in_array.shape[2]
num_images = (num_channels + 2) // 3
# Split the input image into batches of 3 channels.
for i in range(num_images):
sub_image = image_arr[..., 3 * i : 3 * i + 3]
if (i == num_images - 1) and (num_channels % 3) != 0:
# Pad zeros
zero_shape = list(in_array.shape)
zero_shape[2] = 3 - (num_channels % 3)
z = np.zeros(zero_shape, dtype=np.uint8)
sub_image = np.concatenate([sub_image, z], axis=2)
im = Image.fromarray(sub_image, "RGB")
byteIO = io.BytesIO()
im.save(byteIO, format="PNG")
bytes_out += byteIO.getvalue()
return bytes_out
# test helper function for old C# API (no compressed channel mapping)
def generate_compressed_proto_obs(
in_array: np.ndarray, grayscale: bool = False
) -> ObservationProto:
obs_proto = ObservationProto()
obs_proto.compressed_data = generate_compressed_data(in_array)
obs_proto.compression_type = PNG
if grayscale:
# grayscale flag is only used for old API without mapping
expected_shape = [in_array.shape[0], in_array.shape[1], 1]
obs_proto.shape.extend(expected_shape)
else:
obs_proto.shape.extend(in_array.shape)
return obs_proto
# test helper function for new C# API (with compressed channel mapping)
def generate_compressed_proto_obs_with_mapping(
in_array: np.ndarray, mapping: List[int]
) -> ObservationProto:
obs_proto = ObservationProto()
obs_proto.compressed_data = generate_compressed_data(in_array)
obs_proto.compression_type = PNG
if mapping is not None:
obs_proto.compressed_channel_mapping.extend(mapping)
expected_shape = [
in_array.shape[0],
in_array.shape[1],
len({m for m in mapping if m >= 0}),
]
obs_proto.shape.extend(expected_shape)
else:
obs_proto.shape.extend(in_array.shape)
return obs_proto
def generate_uncompressed_proto_obs(in_array: np.ndarray) -> ObservationProto:
obs_proto = ObservationProto()
obs_proto.float_data.data.extend(in_array.flatten().tolist())
obs_proto.compression_type = NONE
obs_proto.shape.extend(in_array.shape)
return obs_proto
def proto_from_steps(
decision_steps: DecisionSteps, terminal_steps: TerminalSteps
) -> List[AgentInfoProto]:
agent_info_protos: List[AgentInfoProto] = []
# Take care of the DecisionSteps first
for agent_id in decision_steps.agent_id:
agent_id_index = decision_steps.agent_id_to_index[agent_id]
reward = decision_steps.reward[agent_id_index]
done = False
max_step_reached = False
agent_mask = None
if decision_steps.action_mask is not None:
agent_mask = [] # type: ignore
for _branch in decision_steps.action_mask:
agent_mask = np.concatenate(
(agent_mask, _branch[agent_id_index, :]), axis=0
)
observations: List[ObservationProto] = []
for all_observations_of_type in decision_steps.obs:
observation = all_observations_of_type[agent_id_index]
if len(observation.shape) == 3:
observations.append(generate_uncompressed_proto_obs(observation))
else:
observations.append(
ObservationProto(
float_data=ObservationProto.FloatData(data=observation),
shape=[len(observation)],
compression_type=NONE,
)
)
agent_info_proto = AgentInfoProto(
reward=reward,
done=done,
id=agent_id,
max_step_reached=max_step_reached,
action_mask=agent_mask,
observations=observations,
)
agent_info_protos.append(agent_info_proto)
# Take care of the TerminalSteps second
for agent_id in terminal_steps.agent_id:
agent_id_index = terminal_steps.agent_id_to_index[agent_id]
reward = terminal_steps.reward[agent_id_index]
done = True
max_step_reached = terminal_steps.interrupted[agent_id_index]
final_observations: List[ObservationProto] = []
for all_observations_of_type in terminal_steps.obs:
observation = all_observations_of_type[agent_id_index]
if len(observation.shape) == 3:
final_observations.append(generate_uncompressed_proto_obs(observation))
else:
final_observations.append(
ObservationProto(
float_data=ObservationProto.FloatData(data=observation),
shape=[len(observation)],
compression_type=NONE,
)
)
agent_info_proto = AgentInfoProto(
reward=reward,
done=done,
id=agent_id,
max_step_reached=max_step_reached,
action_mask=None,
observations=final_observations,
)
agent_info_protos.append(agent_info_proto)
return agent_info_protos
# The arguments here are the DecisionSteps, TerminalSteps and continuous/discrete actions for a single agent name
def proto_from_steps_and_action(
decision_steps: DecisionSteps,
terminal_steps: TerminalSteps,
continuous_actions: np.ndarray,
discrete_actions: np.ndarray,
) -> List[AgentInfoActionPairProto]:
agent_info_protos = proto_from_steps(decision_steps, terminal_steps)
agent_action_protos = []
num_agents = (
len(continuous_actions)
if continuous_actions is not None
else len(discrete_actions)
)
for i in range(num_agents):
proto = AgentActionProto()
if continuous_actions is not None:
proto.continuous_actions.extend(continuous_actions[i])
proto.vector_actions_deprecated.extend(continuous_actions[i])
if discrete_actions is not None:
proto.discrete_actions.extend(discrete_actions[i])
proto.vector_actions_deprecated.extend(discrete_actions[i])
agent_action_protos.append(proto)
agent_info_action_pair_protos = [
AgentInfoActionPairProto(agent_info=agent_info_proto, action_info=action_proto)
for agent_info_proto, action_proto in zip(
agent_info_protos, agent_action_protos
)
]
return agent_info_action_pair_protos
def test_process_pixels():
in_array = np.random.rand(128, 64, 3)
byte_arr = generate_compressed_data(in_array)
out_array = process_pixels(byte_arr, 3)
assert out_array.shape == (128, 64, 3)
assert np.sum(in_array - out_array) / np.prod(in_array.shape) < 0.01
assert np.allclose(in_array, out_array, atol=0.01)
def test_process_pixels_multi_png():
height = 128
width = 64
num_channels = 7
in_array = np.random.rand(height, width, num_channels)
byte_arr = generate_compressed_data(in_array)
out_array = process_pixels(byte_arr, num_channels)
assert out_array.shape == (height, width, num_channels)
assert np.sum(in_array - out_array) / np.prod(in_array.shape) < 0.01
assert np.allclose(in_array, out_array, atol=0.01)
def test_process_pixels_gray():
in_array = np.random.rand(128, 64, 3)
byte_arr = generate_compressed_data(in_array)
out_array = process_pixels(byte_arr, 1)
assert out_array.shape == (128, 64, 1)
assert np.mean(in_array.mean(axis=2, keepdims=True) - out_array) < 0.01
assert np.allclose(in_array.mean(axis=2, keepdims=True), out_array, atol=0.01)
def test_vector_observation():
n_agents = 10
shapes = [(3,), (4,)]
list_proto = generate_list_agent_proto(n_agents, shapes)
for obs_index, shape in enumerate(shapes):
arr = _process_vector_observation(obs_index, shape, list_proto)
assert list(arr.shape) == ([n_agents] + list(shape))
assert np.allclose(arr, 0.1, atol=0.01)
def test_process_visual_observation():
in_array_1 = np.random.rand(128, 64, 3)
proto_obs_1 = generate_compressed_proto_obs(in_array_1)
in_array_2 = np.random.rand(128, 64, 3)
in_array_2_mapping = [0, 1, 2]
proto_obs_2 = generate_compressed_proto_obs_with_mapping(
in_array_2, in_array_2_mapping
)
ap1 = AgentInfoProto()
ap1.observations.extend([proto_obs_1])
ap2 = AgentInfoProto()
ap2.observations.extend([proto_obs_2])
ap_list = [ap1, ap2]
arr = _process_visual_observation(0, (128, 64, 3), ap_list)
assert list(arr.shape) == [2, 128, 64, 3]
assert np.allclose(arr[0, :, :, :], in_array_1, atol=0.01)
assert np.allclose(arr[1, :, :, :], in_array_2, atol=0.01)
def test_process_visual_observation_grayscale():
in_array_1 = np.random.rand(128, 64, 3)
proto_obs_1 = generate_compressed_proto_obs(in_array_1, grayscale=True)
expected_out_array_1 = np.mean(in_array_1, axis=2, keepdims=True)
in_array_2 = np.random.rand(128, 64, 3)
in_array_2_mapping = [0, 0, 0]
proto_obs_2 = generate_compressed_proto_obs_with_mapping(
in_array_2, in_array_2_mapping
)
expected_out_array_2 = np.mean(in_array_2, axis=2, keepdims=True)
ap1 = AgentInfoProto()
ap1.observations.extend([proto_obs_1])
ap2 = AgentInfoProto()
ap2.observations.extend([proto_obs_2])
ap_list = [ap1, ap2]
arr = _process_visual_observation(0, (128, 64, 1), ap_list)
assert list(arr.shape) == [2, 128, 64, 1]
assert np.allclose(arr[0, :, :, :], expected_out_array_1, atol=0.01)
assert np.allclose(arr[1, :, :, :], expected_out_array_2, atol=0.01)
def test_process_visual_observation_padded_channels():
in_array_1 = np.random.rand(128, 64, 12)
in_array_1_mapping = [0, 1, 2, 3, -1, -1, 4, 5, 6, 7, -1, -1]
proto_obs_1 = generate_compressed_proto_obs_with_mapping(
in_array_1, in_array_1_mapping
)
expected_out_array_1 = np.take(in_array_1, [0, 1, 2, 3, 6, 7, 8, 9], axis=2)
ap1 = AgentInfoProto()
ap1.observations.extend([proto_obs_1])
ap_list = [ap1]
arr = _process_visual_observation(0, (128, 64, 8), ap_list)
assert list(arr.shape) == [1, 128, 64, 8]
assert np.allclose(arr[0, :, :, :], expected_out_array_1, atol=0.01)
def test_process_visual_observation_bad_shape():
in_array_1 = np.random.rand(128, 64, 3)
proto_obs_1 = generate_compressed_proto_obs(in_array_1)
ap1 = AgentInfoProto()
ap1.observations.extend([proto_obs_1])
ap_list = [ap1]
with pytest.raises(UnityObservationException):
_process_visual_observation(0, (128, 42, 3), ap_list)
def test_batched_step_result_from_proto():
n_agents = 10
shapes = [(3,), (4,)]
spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_continuous(3)
)
ap_list = generate_list_agent_proto(n_agents, shapes)
decision_steps, terminal_steps = steps_from_proto(ap_list, spec)
for agent_id in range(n_agents):
if agent_id in decision_steps:
# we set the reward equal to the agent id in generate_list_agent_proto
assert decision_steps[agent_id].reward == agent_id
elif agent_id in terminal_steps:
assert terminal_steps[agent_id].reward == agent_id
else:
raise Exception("Missing agent from the steps")
# We sort the AgentId since they are split between DecisionSteps and TerminalSteps
combined_agent_id = list(decision_steps.agent_id) + list(terminal_steps.agent_id)
combined_agent_id.sort()
assert combined_agent_id == list(range(n_agents))
for agent_id in range(n_agents):
assert (agent_id in terminal_steps) == (agent_id % 2 == 0)
if agent_id in terminal_steps:
assert terminal_steps[agent_id].interrupted == (agent_id % 4 == 0)
assert decision_steps.obs[0].shape[1] == shapes[0][0]
assert decision_steps.obs[1].shape[1] == shapes[1][0]
assert terminal_steps.obs[0].shape[1] == shapes[0][0]
assert terminal_steps.obs[1].shape[1] == shapes[1][0]
def test_action_masking_discrete():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_discrete((7, 3))
)
ap_list = generate_list_agent_proto(n_agents, shapes)
decision_steps, terminal_steps = steps_from_proto(ap_list, behavior_spec)
masks = decision_steps.action_mask
assert isinstance(masks, list)
assert len(masks) == 2
assert masks[0].shape == (n_agents / 2, 7) # half agents are done
assert masks[1].shape == (n_agents / 2, 3) # half agents are done
assert masks[0][0, 0]
assert not masks[1][0, 0]
assert masks[1][0, 1]
def test_action_masking_discrete_1():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_discrete((10,))
)
ap_list = generate_list_agent_proto(n_agents, shapes)
decision_steps, terminal_steps = steps_from_proto(ap_list, behavior_spec)
masks = decision_steps.action_mask
assert isinstance(masks, list)
assert len(masks) == 1
assert masks[0].shape == (n_agents / 2, 10)
assert masks[0][0, 0]
def test_action_masking_discrete_2():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_discrete((2, 2, 6))
)
ap_list = generate_list_agent_proto(n_agents, shapes)
decision_steps, terminal_steps = steps_from_proto(ap_list, behavior_spec)
masks = decision_steps.action_mask
assert isinstance(masks, list)
assert len(masks) == 3
assert masks[0].shape == (n_agents / 2, 2)
assert masks[1].shape == (n_agents / 2, 2)
assert masks[2].shape == (n_agents / 2, 6)
assert masks[0][0, 0]
def test_action_masking_continuous():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_continuous(10)
)
ap_list = generate_list_agent_proto(n_agents, shapes)
decision_steps, terminal_steps = steps_from_proto(ap_list, behavior_spec)
masks = decision_steps.action_mask
assert masks is None
def test_agent_behavior_spec_from_proto():
agent_proto = generate_list_agent_proto(1, [(3,), (4,)])[0]
bp = BrainParametersProto()
bp.vector_action_size_deprecated.extend([5, 4])
bp.vector_action_space_type_deprecated = 0
behavior_spec = behavior_spec_from_proto(bp, agent_proto)
assert behavior_spec.action_spec.is_discrete()
assert not behavior_spec.action_spec.is_continuous()
assert [spec.shape for spec in behavior_spec.sensor_specs] == [(3,), (4,)]
assert behavior_spec.action_spec.discrete_branches == (5, 4)
assert behavior_spec.action_spec.discrete_size == 2
bp = BrainParametersProto()
bp.vector_action_size_deprecated.extend([6])
bp.vector_action_space_type_deprecated = 1
behavior_spec = behavior_spec_from_proto(bp, agent_proto)
assert not behavior_spec.action_spec.is_discrete()
assert behavior_spec.action_spec.is_continuous()
assert behavior_spec.action_spec.continuous_size == 6
def test_batched_step_result_from_proto_raises_on_infinite():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_continuous(3)
)
ap_list = generate_list_agent_proto(n_agents, shapes, infinite_rewards=True)
with pytest.raises(RuntimeError):
steps_from_proto(ap_list, behavior_spec)
def test_batched_step_result_from_proto_raises_on_nan():
n_agents = 10
shapes = [(3,), (4,)]
behavior_spec = BehaviorSpec(
create_sensor_specs_with_shapes(shapes), ActionSpec.create_continuous(3)
)
ap_list = generate_list_agent_proto(n_agents, shapes, nan_observations=True)
with pytest.raises(RuntimeError):
steps_from_proto(ap_list, behavior_spec)
| 38.419831
| 113
| 0.687497
|
4a0da71c3d298aa521f9b75b52428c1987ac6bc5
| 1,266
|
py
|
Python
|
replace_n2space.py
|
y-kbys/Python_utility
|
fa3c106a5c3ccfd5fb66f2cf854fe6752426b6e8
|
[
"Unlicense"
] | null | null | null |
replace_n2space.py
|
y-kbys/Python_utility
|
fa3c106a5c3ccfd5fb66f2cf854fe6752426b6e8
|
[
"Unlicense"
] | null | null | null |
replace_n2space.py
|
y-kbys/Python_utility
|
fa3c106a5c3ccfd5fb66f2cf854fe6752426b6e8
|
[
"Unlicense"
] | null | null | null |
#! /Users/ykobayashi/.pyenv/shims/python
import argparse
import os
import sys
import pyperclip
def replace_n2space(input_file_name: str = None):
if input_file_name is None:
print('input text here.')
input_text = sys.stdin.read()
else:
try:
input_file_name = os.path.expanduser(input_file_name)
with open(input_file_name, 'r') as f:
input_text = f.read()
except (IOError, TypeError):
raise FileNotFoundError(str(input_file_name) + ' : file open error.')
return input_text.replace('\n', ' ')
def main():
parser = argparse.ArgumentParser(description='改行文字を半角スペースに置き換える')
parser.add_argument('--input_file', '-i', nargs='?', default=None, help='入力ファイル')
parser.add_argument('--output_file', '-o', nargs='?', default=None, help='出力ファイル')
args = parser.parse_args()
result_text = replace_n2space(args.input_file)
if args.output_file:
with open(args.output_file, 'w') as f:
f.write(result_text)
else:
print('\n---------------------------------------------------------\n')
print(result_text + '\n')
pyperclip.copy(result_text + '\n')
if __name__ == '__main__':
main()
print('complete.')
| 28.133333
| 86
| 0.597946
|
4a0da8c64e403bc147fb22b488a0db35f19ffbca
| 4,620
|
py
|
Python
|
main.py
|
ytyaru/Hatena.PhotLife.API.GetAllLink.201703040849
|
237dae75dfa9f391d5da4c05347dbd3cf6601ba5
|
[
"CC0-1.0"
] | null | null | null |
main.py
|
ytyaru/Hatena.PhotLife.API.GetAllLink.201703040849
|
237dae75dfa9f391d5da4c05347dbd3cf6601ba5
|
[
"CC0-1.0"
] | null | null | null |
main.py
|
ytyaru/Hatena.PhotLife.API.GetAllLink.201703040849
|
237dae75dfa9f391d5da4c05347dbd3cf6601ba5
|
[
"CC0-1.0"
] | null | null | null |
#!python3
#encoding:utf-8
import urllib
from urllib.request import build_opener, HTTPCookieProcessor
from urllib.parse import urlencode
from http.cookiejar import CookieJar
import pprint
import dataset
import sys
from bs4 import BeautifulSoup
import datetime
import time
import os.path
import math
class HatenaSite(object):
def __init__(self, hatena_id, path_hatena_accounts_sqlite3, path_hatena_photolife_sqlite3):
self.hatena_id = hatena_id
self.path_hatena_accounts_sqlite3 = path_hatena_accounts_sqlite3
self.path_hatena_photolife_sqlite3 = path_hatena_photolife_sqlite3
self.db_accounts = dataset.connect('sqlite:///' + path_hatena_accounts_sqlite3)
self.db_photo = dataset.connect('sqlite:///' + path_hatena_photolife_sqlite3)
self.opener = None
def __login(self):
account = self.db_accounts['Accounts'].find_one(HatenaId=hatena_id)
if (None == account):
print('{0} のはてなIDを持ったアカウント情報は次のDBに存在しません。: {1}'.format(hatena_id, self.path_hatena_accounts_sqlite3))
sys.exit()
print(account['Password'])
self.opener = build_opener(HTTPCookieProcessor(CookieJar()))
print(self.opener)
post = {
'name': self.hatena_id,
'password': account['Password']
}
data = urlencode(post).encode('utf-8')
res = self.opener.open('https://www.hatena.ne.jp/login', data)
pprint.pprint(res.getheaders())
res.close()
def all_insert(self, subject='Hatena Blog'):
self.db_photo.begin()
# ログイン
self.__login()
# 1page目
rss = self.__request_photolife_rss(subject=subject, page=1, sort='old')
self.__insert_items(rss)
# 全ページ数取得
all_page_num = self.__get_all_page_num(rss)
# 2page目以降(all_page_numが1ならループしない。最後page+1しないと最後pageが含まれない)
for page in range(1, all_page_num + 1):
# 1page目を飛ばすために`page+1`する
rss = self.__request_photolife_rss(subject=subject, page=(page+1), sort='old')
self.__insert_items(rss)
self.db_photo.commit()
"""
はてなフォトライフのRSSを取得する。
@hatena_id {string} はてなID。
@subject {string} フォトライフ上のディレクトリ。はてなブログからアップロードした画像はすべて'Hatena Blog'。URLエンコード必須。
@page {integer} pageは1以上の整数。
@sort {string} sortは`new`または`old`。
"""
def __request_photolife_rss(self, subject='Hatena Blog', page=1, sort='new'):
time.sleep(2)
url = 'http://f.hatena.ne.jp/{0}/{1}/rss?page={2}&sort={3}'.format(self.hatena_id, subject, page, sort)
print(url)
with self.opener.open(url) as res:
return res.read()
def __get_all_page_num(self, rss):
soup = BeautifulSoup(rss, 'lxml')
channel = soup.find('channel')
print(channel)
totalResults = int(channel.find('openSearch:totalResults'.lower()).string)
startIndex = int(channel.find('openSearch:startIndex'.lower()).string)
itemsPerPage = int(channel.find('openSearch:itemsPerPage'.lower()).string)
print("totalResults={0}".format(totalResults))
print("startIndex={0}".format(startIndex))
print("itemsPerPage={0}".format(itemsPerPage))
# 小数点を切り上げしてPerPage未満のページも1ページ分として加算する
all_page_num = math.ceil(totalResults / itemsPerPage)
print("all_page_num={0}".format(all_page_num))
return all_page_num
def __insert_items(self, rss):
soup = BeautifulSoup(rss, 'lxml')
for item in soup.find_all('item'):
self.__insert_item(item)
def __insert_item(self, item):
# .{ext}
preExt = os.path.splitext(item.find('hatena:imageurl').string)[1]
# {ext}
FileExtension = preExt[1:]
print("FileExtension="+FileExtension)
imageUrl = urllib.parse.urlparse(item.find('hatena:imageurl').string)
ItemId = os.path.split(imageUrl.path)[1].replace(preExt, "")
print("imageUrl.path="+imageUrl.path)
print("ItemId="+ItemId)
self.db_photo['Contents'].insert(dict(
ItemId=ItemId,
FileExtension=FileExtension,
Content=None
))
print(self.db_photo['Contents'].find_one(ItemId=ItemId))
if __name__ == '__main__':
hatena_id = 'ytyaru'
client = HatenaSite(
hatena_id = hatena_id,
path_hatena_accounts_sqlite3 = "meta_Hatena.Accounts.sqlite3",
path_hatena_photolife_sqlite3 = "meta_Hatena.PhotoLife.ytyaru.sqlite3"
)
client.all_insert(subject='Hatena Blog')
| 36.377953
| 113
| 0.644156
|
4a0da90ce18f10a1811de76029b02b3e0dfe17de
| 504
|
bzl
|
Python
|
tools/workspace/styleguide/repository.bzl
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | 2
|
2021-02-25T02:01:02.000Z
|
2021-03-17T04:52:04.000Z
|
tools/workspace/styleguide/repository.bzl
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | null | null | null |
tools/workspace/styleguide/repository.bzl
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | 1
|
2021-06-13T12:05:39.000Z
|
2021-06-13T12:05:39.000Z
|
# -*- python -*-
load("@drake//tools/workspace:github.bzl", "github_archive")
def styleguide_repository(
name,
mirrors = None):
github_archive(
name = name,
repository = "RobotLocomotion/styleguide",
commit = "748ed4dd4e543001421c6618646a60e2a2dca8ea",
sha256 = "94b54d00f67a9d536dec685982b38f43b261eaf689a024209c40b39c567cbc02", # noqa
build_file = "@drake//tools/workspace/styleguide:package.BUILD.bazel",
mirrors = mirrors,
)
| 31.5
| 92
| 0.670635
|
4a0da9585069ec729576d517afe2913876716013
| 849
|
py
|
Python
|
armulator/armv6/opcodes/abstract_opcodes/add_immediate_thumb.py
|
matan1008/armulator
|
04d24dcec6ab42326018f5e09331e5b4738d6b52
|
[
"MIT"
] | 16
|
2018-01-22T14:36:49.000Z
|
2021-12-17T15:39:52.000Z
|
armulator/armv6/opcodes/abstract_opcodes/add_immediate_thumb.py
|
AhmedMounir/armulator
|
04d24dcec6ab42326018f5e09331e5b4738d6b52
|
[
"MIT"
] | 3
|
2019-02-19T17:51:47.000Z
|
2022-03-31T20:45:21.000Z
|
armulator/armv6/opcodes/abstract_opcodes/add_immediate_thumb.py
|
AhmedMounir/armulator
|
04d24dcec6ab42326018f5e09331e5b4738d6b52
|
[
"MIT"
] | 4
|
2020-06-18T23:51:03.000Z
|
2022-02-09T17:43:13.000Z
|
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode
from armulator.armv6.bits_ops import add_with_carry
class AddImmediateThumb(AbstractOpcode):
def __init__(self, setflags, d, n, imm32):
super(AddImmediateThumb, self).__init__()
self.setflags = setflags
self.d = d
self.n = n
self.imm32 = imm32
def execute(self, processor):
if processor.condition_passed():
result, carry, overflow = add_with_carry(processor.registers.get(self.n), self.imm32, "0")
processor.registers.set(self.d, result)
if self.setflags:
processor.registers.cpsr.set_n(result[0])
processor.registers.cpsr.set_z(result.all(0))
processor.registers.cpsr.set_c(carry)
processor.registers.cpsr.set_v(overflow)
| 38.590909
| 102
| 0.65371
|
4a0da9c172018e9c7b08fc12d00a2ce8ec0ad3f4
| 1,658
|
py
|
Python
|
uecp/commands/base.py
|
chrko/uecp
|
8f82ac3311c82939688b095c5c546e6337f7075a
|
[
"MIT"
] | 3
|
2021-11-26T10:32:17.000Z
|
2022-01-12T19:25:40.000Z
|
uecp/commands/base.py
|
chrko/python-uecp
|
8f82ac3311c82939688b095c5c546e6337f7075a
|
[
"MIT"
] | null | null | null |
uecp/commands/base.py
|
chrko/python-uecp
|
8f82ac3311c82939688b095c5c546e6337f7075a
|
[
"MIT"
] | null | null | null |
import abc
import typing
T_UECPCommand = typing.TypeVar("T_UECPCommand", bound="UECPCommand")
class UECPCommand(abc.ABC):
ELEMENT_CODE: typing.ClassVar[int]
ELEMENT_CODE_MAP: typing.ClassVar[dict[int, type["UECPCommand"]]] = {}
@abc.abstractmethod
def encode(self) -> list[int]:
...
@classmethod
@abc.abstractmethod
def create_from(
cls, data: typing.Union[bytes, list[int]]
) -> tuple["UECPCommand", int]:
...
@classmethod
def register_type(cls, message_type: type[T_UECPCommand]) -> type[T_UECPCommand]:
mec = int(message_type.ELEMENT_CODE)
if not (0x01 <= mec <= 0xFD):
raise ValueError(f"MEC must be in [0x01, 0xFD], given {mec:#x}")
if mec in cls.ELEMENT_CODE_MAP:
raise ValueError(f"MEC {mec:#x} already defined")
cls.ELEMENT_CODE_MAP[mec] = message_type
return message_type
@classmethod
def decode_commands(
cls, data: typing.Union[bytes, list[int]]
) -> list["UECPCommand"]:
cmds = []
data = list(data)
while len(data) > 0:
mec = data[0]
if mec not in cls.ELEMENT_CODE_MAP:
raise ValueError()
cmd, consumed_bytes = cls.ELEMENT_CODE_MAP[mec].create_from(data)
cmds.append(cmd)
data = data[consumed_bytes:]
return cmds
class UECPCommandException(Exception):
pass
class UECPCommandDecodeError(UECPCommandException):
pass
class UECPCommandDecodeNotEnoughData(UECPCommandDecodeError):
pass
class UECPCommandDecodeElementCodeMismatchError(UECPCommandDecodeError):
pass
| 26.741935
| 85
| 0.641737
|
4a0daa59c087c7597e58af781a66606222174333
| 286
|
py
|
Python
|
neodroidvision/detection/single_stage/ssd/architecture/__init__.py
|
aivclab/vision
|
6c644dd72f68bca608a2900e5d9461e90fe841eb
|
[
"Apache-2.0"
] | 1
|
2019-07-03T04:33:51.000Z
|
2019-07-03T04:33:51.000Z
|
neodroidvision/detection/single_stage/ssd/architecture/__init__.py
|
aivclab/vision
|
6c644dd72f68bca608a2900e5d9461e90fe841eb
|
[
"Apache-2.0"
] | 5
|
2019-07-03T04:38:07.000Z
|
2021-09-10T15:40:44.000Z
|
neodroidvision/detection/single_stage/ssd/architecture/__init__.py
|
aivclab/vision
|
6c644dd72f68bca608a2900e5d9461e90fe841eb
|
[
"Apache-2.0"
] | 3
|
2019-10-03T06:14:40.000Z
|
2021-01-31T14:31:39.000Z
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 04/03/2020
"""
from .backbones import *
from .nms_box_heads import *
from .single_shot_dectection import *
from .single_shot_detection_nms import *
| 20.428571
| 40
| 0.671329
|
4a0dab9bf3c0cc168e15fcb1e6beca679ed2e5d1
| 1,975
|
py
|
Python
|
tests/integration/test_status_issue.py
|
covx/graypy_v6
|
b4cf60d7d22ee4e6877b31ab31f0b0d073f5bf43
|
[
"BSD-3-Clause"
] | 181
|
2015-01-23T21:01:38.000Z
|
2022-03-25T13:01:06.000Z
|
tests/integration/test_status_issue.py
|
covx/graypy_v6
|
b4cf60d7d22ee4e6877b31ab31f0b0d073f5bf43
|
[
"BSD-3-Clause"
] | 82
|
2015-02-27T09:20:18.000Z
|
2021-12-02T08:37:17.000Z
|
tests/integration/test_status_issue.py
|
covx/graypy_v6
|
b4cf60d7d22ee4e6877b31ab31f0b0d073f5bf43
|
[
"BSD-3-Clause"
] | 75
|
2015-01-23T21:01:40.000Z
|
2022-03-15T19:00:20.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pytests for addressing potential issues with adding an ``status`` extra
field withing a given log and having the log failing to appear within graylog.
Related issue:
- Fails to log silently with specific extra field #85
URL:
- https://github.com/severb/graypy/issues/85
"""
import pytest
from tests.helper import handler, logger
from tests.integration import LOCAL_GRAYLOG_UP
from tests.integration.helper import get_unique_message, get_graylog_response
@pytest.mark.skipif(not LOCAL_GRAYLOG_UP, reason="local Graylog instance not up")
def test_non_status_field_log(logger):
message = get_unique_message()
logger.error(message, extra={"foo": "bar"})
graylog_response = get_graylog_response(message, fields=["foo"])
assert message == graylog_response["message"]
assert "long_message" not in graylog_response
assert "timestamp" in graylog_response
assert "bar" == graylog_response["foo"]
@pytest.mark.skipif(not LOCAL_GRAYLOG_UP, reason="local Graylog instance not up")
def test_status_field_issue(logger):
message = get_unique_message()
logger.error(message, extra={"status": "OK"})
graylog_response = get_graylog_response(message, fields=["status"])
assert message == graylog_response["message"]
assert "long_message" not in graylog_response
assert "timestamp" in graylog_response
assert "OK" == graylog_response["status"]
@pytest.mark.skipif(not LOCAL_GRAYLOG_UP, reason="local Graylog instance not up")
def test_status_field_issue_multi(logger):
message = get_unique_message()
logger.error(message, extra={"foo": "bar", "status": "OK"})
graylog_response = get_graylog_response(message, fields=["foo", "status"])
assert message == graylog_response["message"]
assert "long_message" not in graylog_response
assert "timestamp" in graylog_response
assert "bar" == graylog_response["foo"]
assert "OK" == graylog_response["status"]
| 37.264151
| 81
| 0.746835
|
4a0dabb689873edeabd138f9f25d48d841897e4b
| 1,601
|
py
|
Python
|
Initial version/echowithredir.py
|
mgtburid/Ubuntu-CLI
|
27b4cd139a8d71bd728ba9c06508d4fbaf664a84
|
[
"MIT"
] | null | null | null |
Initial version/echowithredir.py
|
mgtburid/Ubuntu-CLI
|
27b4cd139a8d71bd728ba9c06508d4fbaf664a84
|
[
"MIT"
] | null | null | null |
Initial version/echowithredir.py
|
mgtburid/Ubuntu-CLI
|
27b4cd139a8d71bd728ba9c06508d4fbaf664a84
|
[
"MIT"
] | null | null | null |
# echo with redirection functionality
class echo:
echow = "echo"
append = ">>"
overwrite = ">"
class User:
name = str(input("Enter the username: ")) #accepts input from a keyboard
host = "@" #delimiter between usrnm and hstnm
hostname = str(input("Enter the hostname: ")) #accepts input from a keyboard
umode = "~$ " #regular user mode marker
rmode = "# " #root user mode marker
usrnm = User.name #is entered manually from the keyboard
hst = User.host #an @ delimiter
hstnm = User.hostname #is entered manually from the keyboard
umode = User.umode
rmode = User.rmode #superuser mode. Currently not used
x = str(input(usrnm+hst+hstnm+umode))
if (echo.echow in x and echo.append in x):
x = x.split(">> ") #splits user input so there is a part [0]
x[0] = x[0].replace("echo ", "") #gets rid from "echo" in the STDOUT
file = open(x[1], "a") #with the command itself and a part [1]
file.write(x[0]+"\n") #where it should be put
elif (echo.echow in x and echo.overwrite in x):
x = x.split("> ") #same here, yet it overwrites not appends
x[0] = x[0].replace("echo ", "")
file = open(x[1], "w")
file.write(x[0]+"\n")
| 50.03125
| 97
| 0.472829
|
4a0dad2b54f2f11ed1fb817aec71e857eb63acb1
| 10,465
|
py
|
Python
|
src/modeling/self_supervised/cycle_energy_direct_add_all_noise.py
|
deeplearning-wisc/stud
|
b667a369e368181ef6e913c32f26e574bead9b56
|
[
"Apache-2.0"
] | 22
|
2022-03-09T03:13:10.000Z
|
2022-03-31T02:45:50.000Z
|
src/modeling/self_supervised/cycle_energy_direct_add_all_noise.py
|
deeplearning-wisc/stud
|
b667a369e368181ef6e913c32f26e574bead9b56
|
[
"Apache-2.0"
] | 1
|
2022-03-22T12:27:38.000Z
|
2022-03-22T22:45:46.000Z
|
src/modeling/self_supervised/cycle_energy_direct_add_all_noise.py
|
deeplearning-wisc/stud
|
b667a369e368181ef6e913c32f26e574bead9b56
|
[
"Apache-2.0"
] | 2
|
2022-03-21T02:32:53.000Z
|
2022-03-22T18:43:52.000Z
|
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from detectron2.structures import ImageList
from .build import SSHEAD_REGISTRY
from .ss_layers import Flatten
class CycleEnergyDirectAddAllNoiseHead(nn.Module):
def __init__(self, cfg, cin):
super(CycleEnergyDirectAddAllNoiseHead, self).__init__()
self.name = 'cycle'
self.input = 'ROI'
self.device = torch.device(cfg.MODEL.DEVICE)
self.coef = cfg.MODEL.SS.COEF
# self.enc1 = nn.Sequential(
# nn.Conv2d(cin, 256, kernel_size=3, padding=0, bias=True),
# # nn.BatchNorm2d(256),
# nn.ReLU(inplace=True),
# nn.Conv2d(256, 256, kernel_size=3, padding=0, bias=True),
# # nn.BatchNorm2d(256),
# nn.ReLU(inplace=True),
# nn.AdaptiveAvgPool2d(1)
# # nn.Flatten(start_dim=1, end_dim=-1)
# )
self.add = nn.Conv2d(256, 256, kernel_size=1)
# self.map_back = nn.Linear(256, 256*49)
self.pos = []
self.neg = []
self.topk = 100
self.bs = cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE
self.scale = cfg.MODEL.SS.LOSS_SCALE
self.cfg = cfg
self.save = []
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
m.bias.data.zero_()
elif isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out',
nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 0)
def cal_pair_dist(self, feat_u, feat_v):
# finding the similarity score of feat_v
us = feat_u.size(0)
vs = feat_v.size(0)
fs = feat_u.size(1)
assert fs == feat_v.size(1)
dist = torch.cdist(feat_u, feat_v, p=2).pow(2) * self.coef
# breakpoint()
# uu = feat_u.unsqueeze(1).repeat(1, vs, 1).view(-1, fs)
# vv = feat_v.repeat(us, 1)
#
# diff = uu - vv
# dist = (diff * diff).sum(dim=1).view(us, vs) * self.coef
if 'vis' in self.cfg.DATASETS.TRAIN[0]:
score = F.softmax(dist, dim=1)
else:
score = F.softmax(dist / 16, dim=1)
# print(score)
# breakpoint()
return dist, score
def computer_corr_softmax(self, feat_u, feat_v):
# track forward
# calculate the L2 distance between feat_u and feat_v
sim_dist, sim_score = self.cal_pair_dist(feat_u, feat_v)
# soft_v = torch.matmul(sim_score, feat_v)
#
# # track backward
# back_dist, back_score = self.cal_pair_dist(soft_v, feat_u)
# labels = torch.arange(len(feat_u)).long().to(back_dist.device)
# loss = nn.CrossEntropyLoss()(back_dist, labels)
#
# if back_dist.size(1) == 0:# there is no objects in the first frame.
# print(back_dist.size(), feat_u.size(), feat_v.size(), loss)
# correct = (back_dist.argmax(dim=1) == labels).float().sum()
# count = len(back_dist)
return torch.zeros(1).cuda(), 0, 0, sim_score, sim_dist
def forward(self, roi_head, features, prev_boxes=None):
features, idxs, proposals = features
pos_fea= None
neg_fea = None
fea_v_all = None
v_all = None
prev = 0
# frame = None
# since the number of proposals might be different for different pairs
if prev_boxes is not None:
feat_u = self.enc1(features)
feat_v = self.enc1(prev_boxes)
feat_u = feat_u.view(feat_u.size(0), feat_u.size(1))
feat_v = feat_v.view(feat_v.size(0), feat_v.size(1))
if feat_u.size(0) == 0:
print(feat_u, feat_v)
return {'loss_cycle': feat_u.sum() * self.scale}, 0.
total_loss, correct, cnt, _ = self.computer_corr_softmax(feat_u, feat_v)
# print('correct: ', correct, 'cnt: ', cnt)
total_acc = correct.item()/cnt
else:
for i in range(0, len(idxs), self.cfg.DATALOADER.SELCTED_NUMBER + 1):
u = features[prev:idxs[i]]
# feat_u = self.enc1(u)
# feat_u = feat_u.view(feat_u.size(0), feat_u.size(1))
if u.size(0) == 0:
# # print(feat_u.size(), feat_v.size())
# loss = 0 #feat_u.sum()
# correct = 0
# cnt = 0
pass
else:
if pos_fea is None:
pos_fea = self.add(u).view(-1, 256 * 49)
else:
pos_fea = torch.cat([pos_fea, self.add(u).view(-1, 256 * 49)], 0)
for frame in range(self.cfg.DATALOADER.SELCTED_NUMBER):
v = features[idxs[i+frame]: idxs[i + frame + 1]]
# feat_v = self.enc1(v)
# feat_v = feat_v.view(feat_v.size(0), feat_v.size(1))
# fea_temp = roi_head.box_head(v)
# predictions1 = roi_head.box_predictor(fea_temp)
# energy_scores_all = torch.logsumexp(predictions1[0][:, :-1], dim=1)
# selected_indices = energy_scores_all.argsort()[
# int(self.cfg.MODEL.SS.FILTERING1 * len(energy_scores_all)):
# int(self.cfg.MODEL.SS.FILTERING2 * len(energy_scores_all))]
# breakpoint()
# feat_v = feat_v[selected_indices]
# v = v[selected_indices]
if fea_v_all is not None:
# fea_v_all = torch.cat([fea_v_all, feat_v], 0)
v_all = torch.cat([v_all, v], 0)
else:
# fea_v_all = feat_v
v_all = v
# breakpoint()
# loss, correct, cnt, soft_target_score, dist = self.computer_corr_softmax(feat_u, fea_v_all)
# # temp
# fea_temp = roi_head.box_head(torch.matmul(soft_target_score, self.add(v_all).view(-1, 256 * 49)).view(-1, 256, 7, 7))
# predictions1 = roi_head.box_predictor(fea_temp)
# energy_scores_all = torch.logsumexp(predictions1[0][:, :-1], dim=1)
# # print(energy_scores_all)
#
# fea_temp = roi_head.box_head(u)
# predictions1 = roi_head.box_predictor(fea_temp)
# energy_scores_all_pos = torch.logsumexp(predictions1[0][:, :-1], dim=1)
# # print(energy_scores_all_pos)
#
# if len(self.pos) < 200:
# self.pos.append(energy_scores_all_pos)
# self.neg.append(energy_scores_all)
# else:
# np.save('./pos_energy.npy', self.pos)
# np.save('./neg_energy.npy', self.neg)
# break
# # temp
# # breakpoint()
# print(energy_scores_all)
# print(energy_scores_all_pos)
# breakpoint()
if neg_fea is None:
scale = pos_fea.detach()
# breakpoint()
neg_fea = torch.tensor(0).expand(pos_fea.size()).cuda().float().normal_() * scale
#torch.matmul(soft_target_score, self.add(v_all).view(-1, 256 * 49))
else:
scale = pos_fea.detach()
neg_fea1 = torch.tensor(0).expand(pos_fea.size()).cuda().float().normal_() * scale
neg_fea = torch.cat(
[neg_fea, neg_fea1], 0)
# breakpoint()
# assert frame == - 1
prev = idxs[i + self.cfg.DATALOADER.SELCTED_NUMBER]
# breakpoint()
if pos_fea is not None:
# print('hhh')
assert len(pos_fea) == len(neg_fea) #/ self.cfg.DATALOADER.SELCTED_NUMBER
# print('total loss: {:.4f}\ttotal acc: {:.3f}'.format(total_loss, total_acc))
return {'loss_cycle': 0.0}, 0.0, torch.cat([pos_fea, neg_fea], 0), None
else:
print('marker!')
conv_input = torch.zeros(256,256, 5, 5).cuda()
fake_loss = (self.add(conv_input) - self.add(conv_input)).sum()
assert fake_loss == 0
# print('fake_loss: ', fake_loss)
return {'loss_cycle': 0.0}, 0.0, None, fake_loss
class GaussianNoise(nn.Module):
"""Gaussian noise regularizer.
Args:
sigma (float, optional): relative standard deviation used to generate the
noise. Relative means that it will be multiplied by the magnitude of
the value your are adding the noise to. This means that sigma can be
the same regardless of the scale of the vector.
is_relative_detach (bool, optional): whether to detach the variable before
computing the scale of the noise. If `False` then the scale of the noise
won't be seen as a constant but something to optimize: this will bias the
network to generate vectors with smaller values.
"""
def __init__(self, sigma=0.1, is_relative_detach=True):
super().__init__()
self.sigma = sigma
self.is_relative_detach = is_relative_detach
self.register_buffer('noise', torch.tensor(0))
def forward(self, x):
if self.training and self.sigma != 0:
scale = self.sigma * x.detach() if self.is_relative_detach else self.sigma * x
sampled_noise = self.noise.expand(*x.size()).float().normal_() * scale
x = x + sampled_noise
return x
@SSHEAD_REGISTRY.register()
def build_cycle_energy_direct_add_all_noise_head(cfg, input_shape):
in_channels = cfg.MODEL.FPN.OUT_CHANNELS
rot_head = CycleEnergyDirectAddAllNoiseHead(cfg, in_channels)
return rot_head
| 43.604167
| 139
| 0.527281
|
4a0dad73cab45880a7282e28562ef7e6ed5b7a6d
| 267
|
py
|
Python
|
setup.py
|
saksholm/hhc_n8i8op_mqtt
|
ffe97248673ffb12308f20b7410719c0c30962f5
|
[
"BSD-2-Clause"
] | null | null | null |
setup.py
|
saksholm/hhc_n8i8op_mqtt
|
ffe97248673ffb12308f20b7410719c0c30962f5
|
[
"BSD-2-Clause"
] | null | null | null |
setup.py
|
saksholm/hhc_n8i8op_mqtt
|
ffe97248673ffb12308f20b7410719c0c30962f5
|
[
"BSD-2-Clause"
] | null | null | null |
#!/usr/bin/python3
import shutil
shutil.copy2('./default_config.yaml', './config.yaml')
print("Copied 'default_config.yaml' to 'config.yaml'");
shutil.copy2('./default_inventory.yaml', './inventory.yaml')
print("Copied 'default_inventory.yaml' to 'inventory.yaml'");
| 38.142857
| 61
| 0.737828
|
4a0dad7fc262edf3de126469ffac026b1a01a84c
| 7,272
|
py
|
Python
|
src/tweetynet/graphs.py
|
marcbadger/tweetynet
|
048cc26ae3fe74c00a1d8f5a891eca21428c668c
|
[
"BSD-3-Clause"
] | null | null | null |
src/tweetynet/graphs.py
|
marcbadger/tweetynet
|
048cc26ae3fe74c00a1d8f5a891eca21428c668c
|
[
"BSD-3-Clause"
] | null | null | null |
src/tweetynet/graphs.py
|
marcbadger/tweetynet
|
048cc26ae3fe74c00a1d8f5a891eca21428c668c
|
[
"BSD-3-Clause"
] | null | null | null |
from math import ceil
import tensorflow as tf
def out_width(in_width, filter_width, stride):
return ceil(float(in_width - filter_width + 1) / float(stride))
def inference(spectrogram,
seq_length,
n_syllables,
batch_size=11,
input_vec_size=513,
conv1_filters=32,
conv2_filters=64,
pool1_size=(1,8),
pool1_strides=(1,8),
pool2_size=(1,8),
pool2_strides=(1, 8)):
"""inference graph for 'inferring' labels of birdsong syllables
hybrid convolutional neural net with bidirectional LSTM layer
Arguments
---------
spectrogram : tf.placeholder
placeholder for training data.
gets reshaped to (batch_size, spectrogram width, spectrogram height, 1 channel)
spectrogram height is the same as "input vec size"
num_hidden : int
number of hidden layers in LSTMs
seq_length : tf.placeholder
holds sequence length
equals time_steps * batch_size, where time_steps is defined by user as a constant
n_syllables : int
number of syllable types
used as shape of output
batch_size : int
number of items in a batch.
length of axis 0 of 3-d input array (spectrogram)
default is 11.
input_vec_size : int
length of axis 3 of 3-d input array
number of frequency bins in spectrogram
default is 513
Returns
-------
outputs : tensorflow tensor
logits : tensorflow tensor
"""
# First convolutional layers
# Convolutional Layer #1
conv1 = tf.layers.conv2d(
inputs=tf.reshape(spectrogram, [batch_size, -1, input_vec_size, 1]),
filters=conv1_filters,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
# Pooling Layer #1
pool1 = tf.layers.max_pooling2d(inputs=conv1,
pool_size=pool1_size,
strides=pool1_strides)
# Convolutional Layer #2 and Pooling Layer #2
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=conv2_filters,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2,
pool_size=pool2_size,
strides=pool2_strides)
# Determine number of hidden units in bidirectional LSTM:
# uniquely determined by number of filters and frequency bins
# in output shape of pool2
freq_bins_after_pool1 = out_width(input_vec_size,
pool1_size[1],
pool1_strides[1])
freq_bins_after_pool2 = out_width(freq_bins_after_pool1,
pool2_size[1],
pool2_strides[1])
num_hidden = freq_bins_after_pool2 * conv2_filters
# dynamic bi-directional LSTM
lstm_f1 = tf.contrib.rnn.BasicLSTMCell(num_hidden, forget_bias=1.0, state_is_tuple=True, reuse=None)
lstm_b1 = tf.contrib.rnn.BasicLSTMCell(num_hidden, forget_bias=1.0, state_is_tuple=True, reuse=None)
outputs, _states = tf.nn.bidirectional_dynamic_rnn(lstm_f1,
lstm_b1,
tf.reshape(pool2, [batch_size, -1, num_hidden]),
time_major=False,
dtype=tf.float32,
sequence_length=seq_length)
# projection on the number of syllables creates logits time_steps
with tf.name_scope('Projection'):
W_f = tf.Variable(tf.random_normal([num_hidden, n_syllables]))
W_b = tf.Variable(tf.random_normal([num_hidden, n_syllables]))
bias = tf.Variable(tf.random_normal([n_syllables]))
expr1 = tf.unstack(outputs[0],
axis=0,
num=batch_size)
expr2 = tf.unstack(outputs[1],
axis=0,
num=batch_size)
logits = tf.concat([tf.matmul(ex1, W_f) + bias + tf.matmul(ex2, W_b)
for ex1, ex2 in zip(expr1, expr2)],
0)
return logits, outputs
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits
def train(logits, lbls, rate, batch_size):
"""training graph for label inference graph.
Calculates cross entropy and loss function
Parameters
----------
logits : tensorflow tensor
lbls: int
labels
rate:
learning rate
"""
xentropy_layer = xentropy(logits=logits,
labels=tf.concat(tf.unstack(lbls,
axis=0,
num=batch_size),
0),
name='xentropy')
cost = tf.reduce_mean(xentropy_layer, name='cost')
optimizer = tf.train.AdamOptimizer(learning_rate=rate)
global_step = tf.Variable(0, name='global_step', trainable=False)
train_op = optimizer.minimize(cost, global_step=global_step)
return train_op, cost
def get_full_graph(input_vec_size=513, n_syllables=16,
learning_rate=0.001, batch_size=11):
full_graph = tf.Graph()
with full_graph.as_default():
# Generate placeholders for the spectrograms and labels.
# X holds spectrograms batch_size,time_steps
X = tf.placeholder("float",
[None,
None,
input_vec_size],
name="Xdata")
Y = tf.placeholder("int32",
[None, None],
name="Ylabels") # holds labels batch_size
lng = tf.placeholder("int32",
name="nSteps") # holds the sequence length
tf.add_to_collection("specs", X)
tf.add_to_collection("labels", Y)
tf.add_to_collection("lng", lng)
# Build a Graph that computes predictions from the inference model.
logits, outputs = inference(X,
lng,
n_syllables,
batch_size,
input_vec_size)
tf.add_to_collection("logits", logits)
# Add to the Graph the Ops that calculate and apply gradients.
train_op, cost = train(logits, Y, learning_rate, batch_size)
# Create a summary to monitor cost tensor
tf.summary.scalar("loss", cost)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
# Create a saver for writing training checkpoints.
saver = tf.train.Saver(max_to_keep=10)
return (full_graph, train_op, cost,
init, saver, logits, X, Y, lng, merged_summary_op)
| 38.680851
| 104
| 0.544967
|
4a0dae1592859049ce22dd96380a6100dd9dc68d
| 2,444
|
py
|
Python
|
datasetsnx/readers/ccpd.py
|
ckxy/part-of-hitogata
|
76402d48a336fcd964d0e64bb01d959e8f07f296
|
[
"MIT"
] | null | null | null |
datasetsnx/readers/ccpd.py
|
ckxy/part-of-hitogata
|
76402d48a336fcd964d0e64bb01d959e8f07f296
|
[
"MIT"
] | null | null | null |
datasetsnx/readers/ccpd.py
|
ckxy/part-of-hitogata
|
76402d48a336fcd964d0e64bb01d959e8f07f296
|
[
"MIT"
] | null | null | null |
import os
import numpy as np
from addict import Dict
from PIL import Image
from .reader import Reader
__all__ = ['CCPD2019FolderReader']
class CCPD2019FolderReader(Reader):
def __init__(self, root, **kwargs):
super(CCPD2019FolderReader, self).__init__(**kwargs)
self.root = root
self.chars = ('京', '沪', '津', '渝', '冀', '晋', '蒙', '辽', '吉', '黑',
'苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤',
'桂', '琼', '川', '贵', '云', '藏', '陕', '甘', '青', '宁',
'新',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'I', 'O', '-')
self.img_paths = sorted(os.listdir(kwargs['root']))
assert len(self.img_paths) > 0
def get_dataset_info(self):
return range(len(self.img_paths)), Dict({'chars': self.chars})
def get_data_info(self, index):
img = Image.open(self.img_paths[index][0])
w, h = img.size
return dict(h=h, w=w)
def __call__(self, index):
# index = data_dict
# img = Image.open(os.path.join(self.root, self.img_paths[index])).convert('RGB')
img = self.read_image(os.path.join(self.root, self.img_paths[index]))
w, h = img.size
path = os.path.join(self.root, self.img_paths[index])
base_name = os.path.basename(self.img_paths[index])
img_name, suffix = os.path.splitext(base_name)
img_name = img_name.split("-")[0].split("_")[0]
# if len(img_name) == 8:
# print(path, 'a')
# if img_name[2] != 'D' and img_name[2] != 'F' and img_name[-1] != 'D' and img_name[-1] != 'F':
# print(path)
# raise ValueError
words = []
for c in img_name:
words.append(self.chars.index(c))
# return {'image': img, 'ori_size': np.array([h, w]).astype(np.float32), 'path': path, 'seq': words, 'seq_length': len(words)}
return dict(
image=img,
ori_size=np.array([h, w]).astype(np.float32),
path=path,
seq=words,
seq_length=len(words)
)
def __repr__(self):
return 'CCPD2019FolderReader(root={}, {})'.format(self.root, super(CCPD2019FolderReader, self).__repr__())
| 36.477612
| 134
| 0.49509
|
4a0dae8008e31fe76a1459696b88ca393893cae8
| 6,049
|
py
|
Python
|
pybind/slxos/v17r_2_00/brocade_mpls_rpc/clear_mpls_lsp/input/__init__.py
|
extremenetworks/pybind
|
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
|
[
"Apache-2.0"
] | null | null | null |
pybind/slxos/v17r_2_00/brocade_mpls_rpc/clear_mpls_lsp/input/__init__.py
|
extremenetworks/pybind
|
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
|
[
"Apache-2.0"
] | null | null | null |
pybind/slxos/v17r_2_00/brocade_mpls_rpc/clear_mpls_lsp/input/__init__.py
|
extremenetworks/pybind
|
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
|
[
"Apache-2.0"
] | 1
|
2021-11-05T22:15:42.000Z
|
2021-11-05T22:15:42.000Z
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class input(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/clear-mpls-lsp/input. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__mpls_clear_lsp_name_in',)
_yang_name = 'input'
_rest_name = 'input'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__mpls_clear_lsp_name_in = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'length': [u'1..64']}), is_leaf=True, yang_name="mpls-clear-lsp-name-in", rest_name="mpls-clear-lsp-name-in", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='string', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'brocade_mpls_rpc', u'clear-mpls-lsp', u'input']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'clear-mpls-lsp', u'input']
def _get_mpls_clear_lsp_name_in(self):
"""
Getter method for mpls_clear_lsp_name_in, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_lsp/input/mpls_clear_lsp_name_in (string)
YANG Description: Clear LSP(both primary and secondary) lsp-name
"""
return self.__mpls_clear_lsp_name_in
def _set_mpls_clear_lsp_name_in(self, v, load=False):
"""
Setter method for mpls_clear_lsp_name_in, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_lsp/input/mpls_clear_lsp_name_in (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_clear_lsp_name_in is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mpls_clear_lsp_name_in() directly.
YANG Description: Clear LSP(both primary and secondary) lsp-name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'length': [u'1..64']}), is_leaf=True, yang_name="mpls-clear-lsp-name-in", rest_name="mpls-clear-lsp-name-in", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mpls_clear_lsp_name_in must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'length': [u'1..64']}), is_leaf=True, yang_name="mpls-clear-lsp-name-in", rest_name="mpls-clear-lsp-name-in", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='string', is_config=True)""",
})
self.__mpls_clear_lsp_name_in = t
if hasattr(self, '_set'):
self._set()
def _unset_mpls_clear_lsp_name_in(self):
self.__mpls_clear_lsp_name_in = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'length': [u'1..64']}), is_leaf=True, yang_name="mpls-clear-lsp-name-in", rest_name="mpls-clear-lsp-name-in", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='string', is_config=True)
mpls_clear_lsp_name_in = __builtin__.property(_get_mpls_clear_lsp_name_in, _set_mpls_clear_lsp_name_in)
_pyangbind_elements = {'mpls_clear_lsp_name_in': mpls_clear_lsp_name_in, }
| 47.629921
| 430
| 0.725905
|
4a0dae951f67e932b026a414f6c1f58ef331c6f1
| 83
|
py
|
Python
|
statictypes/__init__.py
|
eriksholmlund/statictypes
|
0e9171b40959a61f0dc4c976615613959d9db9a2
|
[
"Apache-2.0"
] | 2
|
2020-05-22T16:36:39.000Z
|
2020-06-01T08:16:36.000Z
|
statictypes/__init__.py
|
eriksholmlund/statictypes
|
0e9171b40959a61f0dc4c976615613959d9db9a2
|
[
"Apache-2.0"
] | 2
|
2020-09-12T15:19:05.000Z
|
2020-10-15T07:53:08.000Z
|
statictypes/__init__.py
|
eriksholmlund/statictypes
|
0e9171b40959a61f0dc4c976615613959d9db9a2
|
[
"Apache-2.0"
] | null | null | null |
from .type_check import enforce, warn, convert, StaticTypeError, StaticTypeWarning
| 41.5
| 82
| 0.843373
|
4a0db111b7d51f7d025b237330491a7a5ed28800
| 4,019
|
py
|
Python
|
homeassistant/components/point/alarm_control_panel.py
|
alemuro/home-assistant
|
9b1315d8e55f0ca906c4c8a1b2ae8c2ea511dc90
|
[
"Apache-2.0"
] | 2
|
2019-10-19T15:07:32.000Z
|
2022-01-29T10:33:20.000Z
|
homeassistant/components/point/alarm_control_panel.py
|
alemuro/home-assistant
|
9b1315d8e55f0ca906c4c8a1b2ae8c2ea511dc90
|
[
"Apache-2.0"
] | 4
|
2021-02-08T21:05:14.000Z
|
2021-09-08T02:57:03.000Z
|
homeassistant/components/point/alarm_control_panel.py
|
alemuro/home-assistant
|
9b1315d8e55f0ca906c4c8a1b2ae8c2ea511dc90
|
[
"Apache-2.0"
] | 1
|
2019-10-04T13:26:54.000Z
|
2019-10-04T13:26:54.000Z
|
"""Support for Minut Point."""
import logging
from homeassistant.components.alarm_control_panel import DOMAIN, AlarmControlPanel
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DOMAIN as POINT_DOMAIN, POINT_DISCOVERY_NEW, SIGNAL_WEBHOOK
_LOGGER = logging.getLogger(__name__)
EVENT_MAP = {
"off": STATE_ALARM_DISARMED,
"alarm_silenced": STATE_ALARM_DISARMED,
"alarm_grace_period_expired": STATE_ALARM_TRIGGERED,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Point's alarm_control_panel based on a config entry."""
async def async_discover_home(home_id):
"""Discover and add a discovered home."""
client = hass.data[POINT_DOMAIN][config_entry.entry_id]
async_add_entities([MinutPointAlarmControl(client, home_id)], True)
async_dispatcher_connect(
hass, POINT_DISCOVERY_NEW.format(DOMAIN, POINT_DOMAIN), async_discover_home
)
class MinutPointAlarmControl(AlarmControlPanel):
"""The platform class required by Home Assistant."""
def __init__(self, point_client, home_id):
"""Initialize the entity."""
self._client = point_client
self._home_id = home_id
self._async_unsub_hook_dispatcher_connect = None
self._changed_by = None
async def async_added_to_hass(self):
"""Call when entity is added to HOme Assistant."""
await super().async_added_to_hass()
self._async_unsub_hook_dispatcher_connect = async_dispatcher_connect(
self.hass, SIGNAL_WEBHOOK, self._webhook_event
)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
await super().async_will_remove_from_hass()
if self._async_unsub_hook_dispatcher_connect:
self._async_unsub_hook_dispatcher_connect()
@callback
def _webhook_event(self, data, webhook):
"""Process new event from the webhook."""
_type = data.get("event", {}).get("type")
_device_id = data.get("event", {}).get("device_id")
_changed_by = data.get("event", {}).get("user_id")
if (
_device_id not in self._home["devices"] and _type not in EVENT_MAP
) and _type != "alarm_silenced": # alarm_silenced does not have device_id
return
_LOGGER.debug("Received webhook: %s", _type)
self._home["alarm_status"] = _type
self._changed_by = _changed_by
self.async_schedule_update_ha_state()
@property
def _home(self):
"""Return the home object."""
return self._client.homes[self._home_id]
@property
def name(self):
"""Return name of the device."""
return self._home["name"]
@property
def state(self):
"""Return state of the device."""
return EVENT_MAP.get(self._home["alarm_status"], STATE_ALARM_ARMED_AWAY)
@property
def changed_by(self):
"""Return the user the last change was triggered by."""
return self._changed_by
def alarm_disarm(self, code=None):
"""Send disarm command."""
status = self._client.alarm_disarm(self._home_id)
if status:
self._home["alarm_status"] = "off"
def alarm_arm_away(self, code=None):
"""Send arm away command."""
status = self._client.alarm_arm(self._home_id)
if status:
self._home["alarm_status"] = "on"
@property
def unique_id(self):
"""Return the unique id of the sensor."""
return "point.{}".format(self._home_id)
@property
def device_info(self):
"""Return a device description for device registry."""
return {
"identifiers": {(POINT_DOMAIN, self._home_id)},
"name": self.name,
"manufacturer": "Minut",
}
| 33.214876
| 83
| 0.667081
|
4a0db138b6f74c9695437ca785ff108f5e28e88e
| 992
|
py
|
Python
|
atom/proton/python/setup.py
|
sumit4-ttn/SDK
|
b3ae385e5415e47ac70abd0b3fdeeaeee9aa7cff
|
[
"Apache-2.0"
] | null | null | null |
atom/proton/python/setup.py
|
sumit4-ttn/SDK
|
b3ae385e5415e47ac70abd0b3fdeeaeee9aa7cff
|
[
"Apache-2.0"
] | null | null | null |
atom/proton/python/setup.py
|
sumit4-ttn/SDK
|
b3ae385e5415e47ac70abd0b3fdeeaeee9aa7cff
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
"""
Hydrogen Proton API
Financial engineering module of Hydrogen Atom # noqa: E501
OpenAPI spec version: 1.7.18
Contact: info@hydrogenplatform.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from setuptools import setup, find_packages # noqa: H301
NAME = "proton_api"
VERSION = "1.7.18"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"certifi>=2017.4.17",
"python-dateutil>=2.1",
"six>=1.10",
"urllib3>=1.23"
]
setup(
name=NAME,
version=VERSION,
description="Hydrogen Proton API",
author_email="info@hydrogenplatform.com",
url="",
keywords=["Swagger", "Hydrogen Proton API"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""\
Financial engineering module of Hydrogen Atom # noqa: E501
"""
)
| 21.106383
| 68
| 0.674395
|
4a0db1f8972cbf97d2d3bb147955091cb9140d5b
| 3,344
|
py
|
Python
|
ch14/apic/apic/settings.py
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | 19
|
2021-11-05T22:54:09.000Z
|
2022-03-29T15:03:47.000Z
|
ch14/apic/apic/settings.py
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | null | null | null |
ch14/apic/apic/settings.py
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | 26
|
2021-11-12T17:04:50.000Z
|
2022-03-29T01:10:35.000Z
|
# apic/apic/settings.py
"""
Django settings for apic project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-98u5ntukr@mo0e5c*ve+8bk5$i3lr+4n4gc^@=b-7c*j_lyxa("
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"rails.apps.RailsConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "apic.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "apic.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# API Settings
BASE_API_URL = "http://localhost:8000"
| 25.142857
| 91
| 0.701256
|
4a0db2b269e2b3323c39129bce961f498b11027c
| 1,000
|
py
|
Python
|
setup.py
|
IntelAI/forking-tuner
|
8c6c4f8b0d33bdeffbf7fddb1864a5be8ba8dd73
|
[
"Apache-2.0"
] | 1
|
2021-03-03T02:30:19.000Z
|
2021-03-03T02:30:19.000Z
|
setup.py
|
IntelAI/forking-tuner
|
8c6c4f8b0d33bdeffbf7fddb1864a5be8ba8dd73
|
[
"Apache-2.0"
] | null | null | null |
setup.py
|
IntelAI/forking-tuner
|
8c6c4f8b0d33bdeffbf7fddb1864a5be8ba8dd73
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from setuptools import setup, find_packages
NAME = "forking-tuner"
VERSION = "0.1.0"
setup(name=NAME,
version=VERSION,
description="Forking Tuner for TensorFlow.",
author='Intel Corporation',
author_email='intelai@intel.com',
url="",
keywords=["tensorflow"],
packages=find_packages(),
long_description=""
)
| 27.777778
| 74
| 0.705
|
4a0db6abc8083cb6314e7dc5d91c41bcc02e4cfc
| 1,555
|
py
|
Python
|
provisioner/__main__.py
|
srlehn/opennms-provisioner
|
aec001a24ed71ff54a9ff6d05c178c84d4d2c71d
|
[
"MIT"
] | 1
|
2019-04-23T11:57:11.000Z
|
2019-04-23T11:57:11.000Z
|
provisioner/__main__.py
|
srlehn/opennms-provisioner
|
aec001a24ed71ff54a9ff6d05c178c84d4d2c71d
|
[
"MIT"
] | 1
|
2019-04-23T14:01:39.000Z
|
2019-04-23T14:01:39.000Z
|
provisioner/__main__.py
|
srlehn/opennms-provisioner
|
aec001a24ed71ff54a9ff6d05c178c84d4d2c71d
|
[
"MIT"
] | 2
|
2018-11-17T16:10:59.000Z
|
2019-04-23T11:57:49.000Z
|
"""
opennms-provisioner main module
This is the main module of opennms-provisioner
:license: MIT, see LICENSE for more details
:copyright: (c) 2018 by Michael Batz, see AUTHORS for more details
"""
import argparse
import os
import sys
import logging
import logging.config
import pkg_resources
import provisioner.config
import provisioner.executor
def main():
"""main function"""
# get config and JobUtilty
appconfig = provisioner.config.AppConfig(pkg_resources.resource_filename(__name__, "data/etc/appconfig.conf"))
jobutil = provisioner.executor.JobUtility(appconfig)
# get logging
logging.basedir = pkg_resources.resource_filename(__name__, "data/logs")
logconfig = pkg_resources.resource_filename(__name__, "data/etc/logging.conf")
logging.config.fileConfig(logconfig)
logger = logging.getLogger("app")
# parse arguments
parser = argparse.ArgumentParser(description="Helper for OpenNMS Provisioning")
parser.add_argument("jobname", help="name of the provisioning job")
args = parser.parse_args()
# get job
try:
job = jobutil.create_job(args.jobname)
job.execute()
except provisioner.executor.ConfigException as e:
logger.error("Configuration Error: %s", e)
sys.exit(-1)
except provisioner.executor.SourceException as e:
logger.error("Source Error: %s", e)
sys.exit(-1)
except provisioner.executor.TargetException as e:
logger.error("Target Error: %s", e)
sys.exit(-1)
if __name__ == "__main__":
main()
| 29.339623
| 114
| 0.713826
|
4a0db6c814f212fc409fadc1b56d2d8874a082f9
| 27,346
|
py
|
Python
|
tests/cli/test_run.py
|
theoplatt/prefect
|
7aecbe366831a0e9fbed71fe6b8f8fe22bf40d87
|
[
"Apache-2.0"
] | 1
|
2021-08-14T17:05:48.000Z
|
2021-08-14T17:05:48.000Z
|
tests/cli/test_run.py
|
theoplatt/prefect
|
7aecbe366831a0e9fbed71fe6b8f8fe22bf40d87
|
[
"Apache-2.0"
] | 6
|
2021-12-18T09:07:37.000Z
|
2022-03-26T08:06:09.000Z
|
tests/cli/test_run.py
|
ngriffiths13/prefect
|
7f5613abcb182494b7dc12159277c3bc5f3c9898
|
[
"Apache-2.0"
] | null | null | null |
import textwrap
import sys
import os
import json
import pytest
import pendulum
from click.testing import CliRunner
from unittest.mock import MagicMock
from prefect import Flow
from prefect.engine.state import Scheduled, Success, Failed, Submitted
from prefect.run_configs import UniversalRun
from prefect.storage import Local as LocalStorage
from prefect.backend import FlowRunView, FlowView
from prefect.cli.run import load_json_key_values, run
FAILURE_LOCAL_STDOUT = """
Retrieving local flow... Done
Running flow locally...
Flow run failed!
""".lstrip()
TEST_FLOW_VIEW = FlowView(
flow_id="flow-id",
name="flow-name",
settings={"key": "value"},
run_config=UniversalRun(env={"ENV": "VAL"}),
flow=Flow("flow"),
serialized_flow=Flow("flow").serialize(),
archived=False,
project_name="project",
flow_group_labels=["label"],
core_version="0.0.0",
storage=LocalStorage(stored_as_script=True, path="fake-path.py"),
)
SUCCESS_FLOW_RUN_VIEW = FlowRunView(
flow_run_id="flow-run-id",
name="flow-run-name",
flow_id="flow-id",
state=Success(message="state-1"),
states=[],
parameters={"param": "value"},
context={"foo": "bar"},
labels=["label"],
updated_at=pendulum.now(),
run_config=UniversalRun(),
)
# On `get_latest` return the same flow run view
SUCCESS_FLOW_RUN_VIEW.get_latest = MagicMock(return_value=SUCCESS_FLOW_RUN_VIEW)
FAILED_FLOW_RUN_VIEW = FlowRunView(
flow_run_id="flow-run-id",
name="flow-run-name",
flow_id="flow-id",
state=Failed(message="state-1"),
states=[],
parameters={"param": "value"},
context={"foo": "bar"},
labels=["label"],
updated_at=pendulum.now(),
run_config=UniversalRun(),
)
# On `get_latest` return the same flow run view
FAILED_FLOW_RUN_VIEW.get_latest = MagicMock(return_value=FAILED_FLOW_RUN_VIEW)
SUBMITTED_FLOW_RUN_VIEW = FlowRunView(
flow_run_id="flow-run-id",
name="flow-run-name",
flow_id="flow-id",
state=Submitted(message="state-1"),
states=[],
parameters={"param": "value"},
context={"foo": "bar"},
labels=["label"],
updated_at=pendulum.now(),
run_config=UniversalRun(),
)
# On `get_latest` return the same flow run view
SUBMITTED_FLOW_RUN_VIEW.get_latest = MagicMock(return_value=SUBMITTED_FLOW_RUN_VIEW)
TEST_FLOW_RUN_VIEW = FlowRunView(
flow_run_id="flow-run-id",
name="flow-run-name",
flow_id="flow-id",
state=Scheduled(message="state-1"),
states=[],
parameters={"param": "value"},
context={"foo": "bar"},
labels=["label"],
updated_at=pendulum.now(),
run_config=UniversalRun(),
)
# On `get_latest` return the success flow run view
TEST_FLOW_RUN_VIEW.get_latest = MagicMock(return_value=SUCCESS_FLOW_RUN_VIEW)
@pytest.fixture()
def hello_world_flow_file(tmpdir):
flow_file = tmpdir.join("flow.py")
flow_file.write_text(
"""
from prefect.hello_world import hello_flow
""".strip(),
encoding="UTF-8",
)
return str(flow_file)
@pytest.fixture()
def multiflow_file(tmpdir):
flow_file = tmpdir.join("flow.py")
flow_file.write_text(
textwrap.dedent(
"""
from prefect import Flow
flow_a = Flow("a")
flow_b = Flow("b")
"""
),
encoding="UTF-8",
)
return str(flow_file)
@pytest.fixture()
def context_flow_file(tmpdir):
flow_file = tmpdir.join("flow.py")
flow_file.write_text(
textwrap.dedent(
"""
from prefect import Flow, task
@task(log_stdout=True)
def print_context_x():
from prefect import context
print(context.get("x"))
with Flow("context-test-flow") as flow:
print_context_x()
"""
),
encoding="UTF-8",
)
return str(flow_file)
@pytest.fixture()
def runtime_failing_flow(tmpdir):
flow_file = tmpdir.join("flow.py")
flow_file.write_text(
textwrap.dedent(
"""
from prefect import Flow, task
@task(log_stdout=True)
def fail_task():
raise ValueError("Some error")
with Flow("fail-test-flow") as flow:
fail_task()
"""
),
encoding="UTF-8",
)
return str(flow_file)
@pytest.fixture()
def at_load_failing_flow(tmpdir):
flow_file = tmpdir.join("flow.py")
flow_file.write_text(
textwrap.dedent(
"""
from prefect import Flow
with Flow("fail-test-flow") as flow:
reference_an_unknown_var
"""
),
encoding="UTF-8",
)
return str(flow_file)
@pytest.fixture()
def cloud_mocks(monkeypatch):
class CloudMocks:
FlowView = MagicMock()
FlowRunView = MagicMock()
Client = MagicMock()
watch_flow_run = MagicMock()
execute_flow_run_in_subprocess = MagicMock()
sleep = MagicMock()
mocks = CloudMocks()
monkeypatch.setattr("prefect.cli.run.FlowView", mocks.FlowView)
monkeypatch.setattr("prefect.cli.run.FlowRunView", mocks.FlowRunView)
monkeypatch.setattr("prefect.cli.run.Client", mocks.Client)
monkeypatch.setattr("prefect.cli.run.watch_flow_run", mocks.watch_flow_run)
monkeypatch.setattr(
"prefect.cli.run.execute_flow_run_in_subprocess",
mocks.execute_flow_run_in_subprocess,
)
# Mock sleep for faster testing
monkeypatch.setattr("prefect.cli.run.time.sleep", mocks.sleep)
return mocks
@pytest.mark.parametrize(
"input,output",
[
("2", 2),
("2.0", 2.0),
('"2.0"', "2.0"),
("foo", "foo"),
('"foo"', "foo"), # auto-quoted
('{"key": "value"}', {"key": "value"}),
],
)
def test_load_json_key_values(input, output):
assert load_json_key_values([f"test={input}"], "")["test"] == output
def test_run_help():
result = CliRunner().invoke(run, ["--help"])
assert not result.exit_code
assert "Run a flow" in result.output
assert "Examples:" in result.output
@pytest.mark.parametrize(
"options",
(
["--name", "hello", "--id", "fake-id"],
["--project", "hello", "--path", "fake-id"],
["--project", "hello", "--id", "fake-id"],
["--module", "hello", "--id", "fake-id"],
),
)
def test_run_lookup_help_too_many_options(options):
result = CliRunner().invoke(run, options)
assert result.exit_code
assert "Received too many options to look up the flow" in result.output
assert (
"Look up a flow to run with one of the following option combinations"
in result.output
)
def test_run_lookup_help_no_options():
result = CliRunner().invoke(run, "--param foo=1")
assert result.exit_code
assert "Received no options to look up the flow" in result.output
assert (
"Look up a flow to run with one of the following option combinations"
in result.output
)
def test_run_wraps_parameter_file_parsing_exception(tmpdir):
params_file = tmpdir.join("params.json")
params_file.write_text("not-valid-json", encoding="UTF-8")
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--param-file", str(params_file)]
)
assert result.exit_code
assert "Failed to parse JSON" in result.output
def test_run_wraps_parameter_file_not_found_exception(tmpdir):
params_file = tmpdir.join("params.json")
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--param-file", str(params_file)]
)
assert result.exit_code
assert "Parameter file does not exist" in result.output
@pytest.mark.parametrize("kind", ["param", "context"])
def test_run_wraps_parameter_and_context_json_parsing_exception(tmpdir, kind):
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", f"--{kind}", 'x="foo"1']
)
assert result.exit_code
assert (
f"Failed to parse JSON for {kind.replace('param', 'parameter')} 'x'"
in result.output
)
def test_run_automatically_quotes_simple_strings():
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--param", "name=foo"]
)
assert not result.exit_code
assert "Parameters: {'name': 'foo'}" in result.output
@pytest.mark.parametrize("kind", ["path", "module"])
def test_run_local(tmpdir, kind, caplog, hello_world_flow_file):
location = hello_world_flow_file if kind == "path" else "prefect.hello_world"
result = CliRunner().invoke(run, [f"--{kind}", location])
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# FlowRunner logs are displayed
assert "Hello World" in caplog.text
@pytest.mark.parametrize("kind", ["path", "module"])
def test_run_local_allows_selection_from_multiple_flows(
monkeypatch, multiflow_file, kind
):
monkeypatch.syspath_prepend(os.path.dirname(os.path.abspath(multiflow_file)))
location = multiflow_file if kind == "path" else "flow"
result = CliRunner().invoke(run, [f"--{kind}", location, "--name", "b"])
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
@pytest.mark.parametrize("kind", ["path", "module"])
def test_run_local_asks_for_name_with_multiple_flows(tmpdir, multiflow_file, kind):
if kind == "module":
# Extend the sys.path so we can pull from the file like a module
orig_sys_path = sys.path.copy()
sys.path.insert(0, os.path.dirname(os.path.abspath(multiflow_file)))
location = multiflow_file if kind == "path" else "flow"
result = CliRunner().invoke(run, [f"--{kind}", location])
assert result.exit_code
assert (
f"Found multiple flows at {location!r}: 'a', 'b'\n\nSpecify a flow name to run"
in result.output
)
if kind == "module":
sys.path = orig_sys_path
@pytest.mark.parametrize("log_level", ["ERROR", "DEBUG"])
def test_run_local_log_level(tmpdir, caplog, log_level):
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--log-level", log_level]
)
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# Hello World is _not_ an error level log and should not be displayed then
if log_level == "ERROR":
assert "Hello World" not in caplog.text
assert "INFO" not in caplog.text
else:
assert "Hello World" in caplog.text
assert "INFO" in caplog.text
assert "DEBUG" in caplog.text
def test_run_local_respects_quiet(caplog):
result = CliRunner().invoke(run, ["--module", "prefect.hello_world", "--quiet"])
assert not result.exit_code
# CLI output is not there
assert "Running flow locally..." not in result.output
# Flow run logs are still happening for local runs
assert "Hello World" in caplog.text
def test_run_local_respects_no_logs(caplog):
result = CliRunner().invoke(run, ["--module", "prefect.hello_world", "--no-logs"])
assert not result.exit_code
# Run output still occurs
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# Flow run logs are silenced
assert caplog.text == ""
def test_run_local_passes_parameters(caplog):
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--param", 'name="foo"']
)
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# A configured section will apppear now that a parameter is set
assert "Configured local flow run\n└── Parameters: {'name': 'foo'}" in result.output
# Parameter was used by the flow
assert "Hello Foo" in caplog.text
def test_run_local_passes_parameters_from_file(caplog, tmpdir):
params_file = tmpdir.join("params.json")
params_file.write_text(json.dumps({"name": "foo"}), encoding="UTF-8")
result = CliRunner().invoke(
run, ["--module", "prefect.hello_world", "--param-file", str(params_file)]
)
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# A configured section will apppear now that a parameter is set
assert "Configured local flow run\n└── Parameters: {'name': 'foo'}" in result.output
# Parameter was used by the flow
assert "Hello Foo" in caplog.text
def test_run_local_passes_context(caplog, context_flow_file):
result = CliRunner().invoke(
run, ["--path", context_flow_file, "--context", 'x="custom-context-val"']
)
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# A configured section will apppear now that the context is set
assert (
"Configured local flow run\n└── Context: {'x': 'custom-context-val'}"
in result.output
)
# Parameter was used by the flow
assert "custom-context-val" in caplog.text
def test_run_passes_context(caplog, context_flow_file):
result = CliRunner().invoke(
run, ["--path", context_flow_file, "--context", 'x="custom-context-val"']
)
assert not result.exit_code
assert "Running flow locally..." in result.output
assert "Flow run succeeded" in result.output
# A configured section will apppear now that the context is set
assert (
"Configured local flow run\n└── Context: {'x': 'custom-context-val'}"
in result.output
)
# Parameter was used by the flow
assert "custom-context-val" in caplog.text
def test_run_local_handles_flow_run_failure(caplog, runtime_failing_flow):
result = CliRunner().invoke(run, ["--path", runtime_failing_flow])
assert result.exit_code == 1
assert "Running flow locally..." in result.output
assert "Flow run failed" in result.output
# Flow runner logged exception
assert "ValueError: Some error" in caplog.text
def test_run_local_handles_flow_load_failure_with_script_issue(at_load_failing_flow):
result = CliRunner().invoke(run, ["--path", at_load_failing_flow])
assert result.exit_code
assert "Retrieving local flow... Error" in result.output
assert "Traceback" in result.output
@pytest.mark.skipif(
sys.platform == "win32", reason="Full traceback displayed on Windows"
)
def test_run_local_handles_flow_load_failure_with_missing_file(tmpdir):
missing_file = str(tmpdir.join("file"))
result = CliRunner().invoke(run, ["--path", missing_file])
assert result.exit_code
assert "Retrieving local flow... Error" in result.output
# Instead of a traceback there is a short error
assert "Traceback" not in result.output
assert f"File does not exist: {missing_file!r}" in result.output
def test_run_local_handles_flow_load_failure_with_missing_module(tmpdir):
result = CliRunner().invoke(run, ["--module", "my_very_unique_module_name"])
assert result.exit_code
assert "Retrieving local flow... Error" in result.output
# Instead of a traceback there is a short error
assert "Traceback" not in result.output
assert "No module named 'my_very_unique_module_name'" in result.output
def test_run_local_handles_flow_load_failure_with_missing_module_attr(tmpdir):
result = CliRunner().invoke(run, ["--module", "prefect.foobar"])
assert result.exit_code
assert "Retrieving local flow... Error" in result.output
# Instead of a traceback there is a short error
assert "Traceback" not in result.output
assert "Module 'prefect' has no attribute 'foobar'" in result.output
@pytest.mark.parametrize("execute_flag", (["--execute"], []))
@pytest.mark.parametrize(
"cli_args,cloud_kwargs",
[
(
["--param", "a=2", "--param", "b=[1,2,3]"],
dict(parameters={"a": 2, "b": [1, 2, 3]}),
),
(
["--context", "a=1", "--context", 'b={"nested": 2}'],
dict(context={"a": 1, "b": {"nested": 2}}),
),
(["--label", "foo", "--label", "bar"], dict(labels=["foo", "bar"])),
(["--run-name", "my-run"], dict(run_name="my-run")),
(
["--log-level", "DEBUG"],
dict(
run_config=UniversalRun(
# Notice this tests for ENV merging
env={"ENV": "VAL", "PREFECT__LOGGING__LEVEL": "DEBUG"}
)
),
),
(
# No logs does not alter the log level for cloud runs, we just don't query
# for them in `watch_flow_run`
["--no-logs"],
dict(),
),
],
)
def test_run_cloud_creates_flow_run(
cloud_mocks, cli_args, cloud_kwargs, execute_flag, monkeypatch
):
cloud_mocks.FlowView.from_flow_id.return_value = TEST_FLOW_VIEW
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
if execute_flag:
# Create a preset unique id for the agentless run label for easy determinism
monkeypatch.setattr(
"prefect.cli.run.uuid.uuid4", MagicMock(return_value="0" * 36)
)
result = CliRunner().invoke(run, ["--id", "flow-id"] + cli_args + execute_flag)
assert not result.exit_code
cloud_kwargs = cloud_kwargs.copy() # Copy before mutating the pytest param dicts
cloud_kwargs.setdefault("parameters", {})
cloud_kwargs.setdefault("context", {})
cloud_kwargs.setdefault("labels", None)
cloud_kwargs.setdefault("run_name", None)
cloud_kwargs.setdefault("run_config", None)
if execute_flag:
labels = cloud_kwargs["labels"] or []
cloud_kwargs["labels"] = labels + ["agentless-run-00000000"]
cloud_mocks.Client().create_flow_run.assert_called_once_with(
flow_id=TEST_FLOW_VIEW.flow_id,
**cloud_kwargs,
)
if not execute_flag:
# Called once to retrieve information
cloud_mocks.FlowRunView.from_flow_run_id.assert_called_once()
else:
# Called again later to check final state
assert cloud_mocks.FlowRunView.from_flow_run_id.call_count == 2
def test_run_cloud_handles_create_flow_run_failure(cloud_mocks):
cloud_mocks.FlowView.from_flow_id.return_value = TEST_FLOW_VIEW
cloud_mocks.Client().create_flow_run.side_effect = ValueError("Foo!")
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert result.exit_code
assert "Creating run for flow 'flow-name'... Error" in result.output
assert "Traceback" in result.output
assert "ValueError: Foo!" in result.output
def test_run_cloud_handles_keyboard_interrupt_during_create_flow_run(cloud_mocks):
cloud_mocks.FlowView.from_flow_id.return_value = TEST_FLOW_VIEW
cloud_mocks.Client().create_flow_run.side_effect = KeyboardInterrupt
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert not result.exit_code
assert "Creating run for flow 'flow-name'..." in result.output
assert "Keyboard interrupt detected! Aborting..." in result.output
assert "Aborted." in result.output
def test_run_cloud_handles_keyboard_interrupt_during_flow_run_info(cloud_mocks):
# This test differs from `...interrupt_during_create_flow_run` in that the flow
# run is created and the user has cancelled during metadata retrieval so we need
# to actually cancel the run
cloud_mocks.FlowView.from_flow_id.return_value = TEST_FLOW_VIEW
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
cloud_mocks.FlowRunView.from_flow_run_id.side_effect = KeyboardInterrupt
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert not result.exit_code
assert "Creating run for flow 'flow-name'..." in result.output
assert "Keyboard interrupt detected! Aborting..." in result.output
assert "Cancelled flow run." in result.output
cloud_mocks.Client().cancel_flow_run.assert_called_once_with(
flow_run_id="fake-run-id"
)
def test_run_cloud_respects_quiet(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
result = CliRunner().invoke(run, ["--id", "flow-id", "--quiet"])
assert not result.exit_code
assert result.output == "fake-run-id\n"
@pytest.mark.parametrize("watch", [True, False])
def test_run_cloud_watch(cloud_mocks, watch):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
result = CliRunner().invoke(
run, ["--id", "flow-id"] + (["--watch"] if watch else [])
)
assert not result.exit_code
if watch:
cloud_mocks.watch_flow_run.assert_called_once()
assert cloud_mocks.watch_flow_run.call_args[1]["flow_run_id"] == "fake-run-id"
else:
cloud_mocks.watch_flow_run.assert_not_called()
def test_run_cloud_watch_respects_no_logs(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
result = CliRunner().invoke(run, ["--id", "flow-id", "--watch", "--no-logs"])
assert not result.exit_code
cloud_mocks.watch_flow_run.assert_called_once()
assert cloud_mocks.watch_flow_run.call_args[1]["stream_logs"] is False
def test_run_cloud_lookup_by_flow_id(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert not result.exit_code
assert "Looking up flow metadata... Done" in result.output
cloud_mocks.FlowView.from_flow_id.assert_called_once_with("flow-id")
def test_run_cloud_lookup_by_flow_group_id(cloud_mocks):
cloud_mocks.FlowView.from_flow_id.side_effect = ValueError() # flow id is not found
cloud_mocks.FlowView.from_flow_group_id.return_value = TEST_FLOW_VIEW
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert not result.exit_code
assert "Looking up flow metadata... Done" in result.output
cloud_mocks.FlowView.from_flow_id.assert_called_once_with("flow-id")
@pytest.mark.parametrize("with_project", [True, False])
def test_run_cloud_lookup_by_name(cloud_mocks, with_project):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
result = CliRunner().invoke(
run,
["--name", "flow-name"]
+ (["--project", "project-name"] if with_project else []),
)
assert not result.exit_code
assert "Looking up flow metadata... Done" in result.output
expected = {"flow_name": "flow-name"}
if with_project:
expected["project_name"] = "project-name"
cloud_mocks.FlowView.from_flow_name.assert_called_once_with(**expected)
def test_run_cloud_handles_ids_not_found(cloud_mocks):
cloud_mocks.FlowView.from_flow_id.side_effect = ValueError() # flow id is not found
cloud_mocks.FlowView.from_flow_group_id.side_effect = ValueError()
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert result.exit_code
assert "Looking up flow metadata... Error" in result.output
assert "Failed to find flow id or flow group id" in result.output
assert "Traceback" not in result.output
def test_run_cloud_displays_name_lookup_errors(cloud_mocks):
cloud_mocks.FlowView.from_flow_name.side_effect = ValueError("Example error")
result = CliRunner().invoke(run, ["--name", "foo"])
assert result.exit_code
assert "Looking up flow metadata... Error" in result.output
# TODO: Note this error message could be wrapped for a better UX
assert "Example error" in result.output
def test_run_cloud_handles_project_without_name(cloud_mocks):
cloud_mocks.FlowView.from_flow_name.side_effect = ValueError("No results found")
result = CliRunner().invoke(run, ["--project", "foo"])
assert result.exit_code
assert "Looking up flow metadata... Error" in result.output
assert (
"Missing required option `--name`. Cannot look up a flow by project without "
"also passing a name." in result.output
)
def test_run_cloud_displays_flow_run_data(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
cloud_mocks.Client.return_value.get_cloud_url.return_value = "fake-url"
result = CliRunner().invoke(run, ["--id", "flow-id"])
assert not result.exit_code
assert (
textwrap.dedent(
"""
└── Name: flow-run-name
└── UUID: flow-run-id
└── Labels: ['label']
└── Parameters: {'param': 'value'}
└── Context: {'foo': 'bar'}
└── URL: fake-url
"""
)
in result.output
)
@pytest.mark.parametrize(
"run_result", [FAILED_FLOW_RUN_VIEW, SUCCESS_FLOW_RUN_VIEW, SUBMITTED_FLOW_RUN_VIEW]
)
@pytest.mark.parametrize("flag", ["--execute", "--watch"])
def test_run_cloud_exit_code_reflects_final_run_state_when_watched_or_executed(
cloud_mocks, flag, run_result
):
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
cloud_mocks.FlowRunView.from_flow_run_id.return_value = run_result
result = CliRunner().invoke(run, ["--id", "flow-id"] + [flag])
if run_result != SUCCESS_FLOW_RUN_VIEW:
assert result.exit_code == 1
else:
assert not result.exit_code
def test_run_cloud_execute_calls_subprocess(cloud_mocks):
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
result = CliRunner().invoke(run, ["--id", "flow-id", "--execute"])
assert not result.exit_code
assert "Executing flow run..." in result.output
cloud_mocks.execute_flow_run_in_subprocess.assert_called_once_with("fake-run-id")
def test_run_cloud_execute_respects_quiet(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
cloud_mocks.Client().create_flow_run.return_value = "fake-run-id"
def show_a_log(*args, **kwargs):
from prefect.utilities.logging import get_logger
get_logger().error("LOG MESSAGE!")
cloud_mocks.execute_flow_run_in_subprocess.side_effect = show_a_log
result = CliRunner().invoke(run, ["--id", "flow-id", "--quiet", "--execute"])
assert not result.exit_code
assert result.output == "fake-run-id\n"
def test_run_cloud_execute_respects_no_logs(cloud_mocks):
cloud_mocks.FlowRunView.from_flow_run_id.return_value = TEST_FLOW_RUN_VIEW
def show_a_log(*args, **kwargs):
from prefect.utilities.logging import get_logger
get_logger().error("LOG MESSAGE!")
cloud_mocks.execute_flow_run_in_subprocess.side_effect = show_a_log
result = CliRunner().invoke(run, ["--id", "flow-id", "--no-logs", "--execute"])
assert not result.exit_code
# CLI messages display
assert "Executing flow run..." in result.output
# Run logs do not
assert "LOG MESSAGE" not in result.output
| 33.760494
| 88
| 0.677028
|
4a0db90457d4f9525b58efecf37df52d6fa0493b
| 11,659
|
py
|
Python
|
tools/gen_struct_info.py
|
yishengjiang99/emscripten
|
add7cf2f0b76abb20460f0742c5402ca9b46f8d8
|
[
"MIT"
] | null | null | null |
tools/gen_struct_info.py
|
yishengjiang99/emscripten
|
add7cf2f0b76abb20460f0742c5402ca9b46f8d8
|
[
"MIT"
] | null | null | null |
tools/gen_struct_info.py
|
yishengjiang99/emscripten
|
add7cf2f0b76abb20460f0742c5402ca9b46f8d8
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# coding=utf-8
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""This tool extracts information about structs and defines from the C headers.
The JSON input format is as follows:
[
{
'file': 'some/header.h',
'structs': {
'struct_name': [
'field1',
'field2',
'field3',
{
'field4': [
'nested1',
'nested2',
{
'nested3': [
'deep_nested1',
...
]
}
...
]
},
'field5'
],
'other_struct': [
'field1',
'field2',
...
]
},
'defines': [
'DEFINE_1',
'DEFINE_2',
['f', 'FLOAT_DEFINE'],
'DEFINE_3',
...
]
},
{
'file': 'some/other/header.h',
...
}
]
Please note that the 'f' for 'FLOAT_DEFINE' is just the format passed to printf(), you can put anything printf() understands.
If you call this script with the flag "-f" and pass a header file, it will create an automated boilerplate for you.
The JSON output format is based on the return value of Runtime.generateStructInfo().
{
'structs': {
'struct_name': {
'__size__': <the struct's size>,
'field1': <field1's offset>,
'field2': <field2's offset>,
'field3': <field3's offset>,
'field4': {
'__size__': <field4's size>,
'nested1': <nested1's offset>,
...
},
...
}
},
'defines': {
'DEFINE_1': <DEFINE_1's value>,
...
}
}
"""
import sys
import os
import re
import json
import argparse
import tempfile
import subprocess
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tools import shared
QUIET = (__name__ != '__main__')
DEBUG = False
def show(msg):
if shared.DEBUG or not QUIET:
sys.stderr.write('gen_struct_info: %s\n' % msg)
# The following three functions generate C code. The output of the compiled code will be
# parsed later on and then put back together into a dict structure by parse_c_output().
#
# Example:
# c_descent('test1', code)
# c_set('item', 'i%i', '111', code)
# c_set('item2', 'i%i', '9', code)
# c_set('item3', 's%s', '"Hello"', code)
# c_ascent(code)
# c_set('outer', 'f%f', '0.999', code)
#
# Will result in:
# {
# 'test1': {
# 'item': 111,
# 'item2': 9,
# 'item3': 'Hello',
# },
# 'outer': 0.999
# }
def c_set(name, type_, value, code):
code.append('printf("K' + name + '\\n");')
code.append('printf("V' + type_ + '\\n", ' + value + ');')
def c_descent(name, code):
code.append('printf("D' + name + '\\n");')
def c_ascent(code):
code.append('printf("A\\n");')
def parse_c_output(lines):
result = {}
cur_level = result
parent = []
key = None
for line in lines:
arg = line[1:].strip()
if line[0] == 'K':
# This is a key
key = arg
elif line[0] == 'V':
# A value
if arg[0] == 'i':
arg = int(arg[1:])
elif arg[0] == 'f':
arg = float(arg[1:])
elif arg[0] == 's':
arg = arg[1:]
cur_level[key] = arg
elif line[0] == 'D':
# Remember the current level as the last parent.
parent.append(cur_level)
# We descend one level.
cur_level[arg] = {}
cur_level = cur_level[arg]
elif line[0] == 'A':
# We return to the parent dict. (One level up.)
cur_level = parent.pop()
return result
def gen_inspect_code(path, struct, code):
if path[0][-1] == '#':
path[0] = path[0][:-1]
prefix = ''
else:
prefix = 'struct '
c_descent(path[-1], code)
if len(path) == 1:
c_set('__size__', 'i%zu', 'sizeof (' + prefix + path[0] + ')', code)
else:
c_set('__size__', 'i%zu', 'sizeof ((' + prefix + path[0] + ' *)0)->' + '.'.join(path[1:]), code)
# c_set('__offset__', 'i%zu', 'offsetof(' + prefix + path[0] + ', ' + '.'.join(path[1:]) + ')', code)
for field in struct:
if isinstance(field, dict):
# We have to recurse to inspect the nested dict.
fname = list(field.keys())[0]
gen_inspect_code(path + [fname], field[fname], code)
else:
c_set(field, 'i%zu', 'offsetof(' + prefix + path[0] + ', ' + '.'.join(path[1:] + [field]) + ')', code)
c_ascent(code)
def inspect_headers(headers, cpp_opts):
code = ['#include <stdio.h>', '#include <stddef.h>']
for header in headers:
code.append('#include "' + header['name'] + '"')
code.append('int main() {')
c_descent('structs', code)
for header in headers:
for name, struct in header['structs'].items():
gen_inspect_code([name], struct, code)
c_ascent(code)
c_descent('defines', code)
for header in headers:
for name, type_ in header['defines'].items():
# Add the necessary python type, if missing.
if '%' not in type_:
if type_[-1] in ('d', 'i', 'u'):
# integer
type_ = 'i%' + type_
elif type_[-1] in ('f', 'F', 'e', 'E', 'g', 'G'):
# float
type_ = 'f%' + type_
elif type_[-1] in ('x', 'X', 'a', 'A', 'c', 's'):
# hexadecimal or string
type_ = 's%' + type_
c_set(name, type_, name, code)
code.append('return 0;')
code.append('}')
# Write the source code to a temporary file.
src_file = tempfile.mkstemp('.c')
show('Generating C code... ' + src_file[1])
os.write(src_file[0], shared.asbytes('\n'.join(code)))
js_file = tempfile.mkstemp('.js')
# Close all unneeded FDs.
os.close(src_file[0])
os.close(js_file[0])
# TODO(sbc): Switch to '-nostdlib -lcompiler_rt'
env = os.environ.copy()
env['EMCC_FORCE_STDLIBS'] = 'libcompiler_rt'
env['EMCC_ONLY_FORCED_STDLIBS'] = '1'
info = []
# Compile the program.
show('Compiling generated code...')
# -Oz optimizes enough to avoid warnings on code size/num locals
cmd = [shared.EMCC] + cpp_opts + ['-o', js_file[1], src_file[1],
'-O0',
'-Werror',
'-Wno-format',
'-I', shared.path_from_root(),
'-s', 'BOOTSTRAPPING_STRUCT_INFO=1',
'-s', 'STRICT',
# Use SINGLE_FILE=1 so there is only a single
# file to cleanup.
'-s', 'SINGLE_FILE']
# Default behavior for emcc is to warn for binaryen version check mismatches
# so we should try to match that behavior.
cmd += ['-Wno-error=version-check']
# TODO(sbc): Remove this one we remove the test_em_config_env_var test
cmd += ['-Wno-deprecated']
if shared.Settings.LTO:
cmd += ['-flto=' + shared.Settings.LTO]
show(shared.shlex_join(cmd))
try:
subprocess.check_call(cmd, env=env)
except subprocess.CalledProcessError as e:
sys.stderr.write('FAIL: Compilation failed!: %s\n' % e.cmd)
sys.exit(1)
# Run the compiled program.
show('Calling generated program... ' + js_file[1])
info = shared.run_js_tool(js_file[1], stdout=shared.PIPE).splitlines()
# Remove all temporary files.
os.unlink(src_file[1])
if os.path.exists(js_file[1]):
os.unlink(js_file[1])
# Parse the output of the program into a dict.
return parse_c_output(info)
def merge_info(target, src):
for key, value in src['defines'].items():
if key in target['defines']:
raise Exception('duplicate define: %s' % key)
target['defines'][key] = value
for key, value in src['structs'].items():
if key in target['structs']:
raise Exception('duplicate struct: %s' % key)
target['structs'][key] = value
def inspect_code(headers, cpp_opts):
if not DEBUG:
info = inspect_headers(headers, cpp_opts)
else:
info = {'defines': {}, 'structs': {}}
for header in headers:
merge_info(info, inspect_headers([header], cpp_opts))
return info
def parse_json(path):
header_files = []
with open(path, 'r') as stream:
# Remove comments before loading the JSON.
data = json.loads(re.sub(r'//.*\n', '', stream.read()))
if not isinstance(data, list):
data = [data]
for item in data:
for key in item.keys():
if key not in ['file', 'defines', 'structs']:
raise 'Unexpected key in json file: %s' % key
header = {'name': item['file'], 'structs': {}, 'defines': {}}
for name, data in item.get('structs', {}).items():
if name in header['structs']:
show('WARN: Description of struct "' + name + '" in file "' + item['file'] + '" replaces an existing description!')
header['structs'][name] = data
for part in item.get('defines', []):
if not isinstance(part, list):
# If no type is specified, assume integer.
part = ['i', part]
if part[1] in header['defines']:
show('WARN: Description of define "' + part[1] + '" in file "' + item['file'] + '" replaces an existing description!')
header['defines'][part[1]] = part[0]
header_files.append(header)
return header_files
def output_json(obj, stream=None):
if stream is None:
stream = sys.stdout
elif isinstance(stream, str):
stream = open(stream, 'w')
json.dump(obj, stream, indent=4, sort_keys=True)
stream.write('\n')
stream.close()
def main(args):
global QUIET
default_json_files = [
shared.path_from_root('src', 'struct_info.json'),
shared.path_from_root('src', 'struct_info_internal.json')
]
parser = argparse.ArgumentParser(description='Generate JSON infos for structs.')
parser.add_argument('json', nargs='*',
help='JSON file with a list of structs and their fields (defaults to src/struct_info.json)',
default=default_json_files)
parser.add_argument('-q', dest='quiet', action='store_true', default=False,
help='Don\'t output anything besides error messages.')
parser.add_argument('-o', dest='output', metavar='path', default=None,
help='Path to the JSON file that will be written. If omitted, the generated data will be printed to stdout.')
parser.add_argument('-I', dest='includes', metavar='dir', action='append', default=[],
help='Add directory to include search path')
parser.add_argument('-D', dest='defines', metavar='define', action='append', default=[],
help='Pass a define to the preprocessor')
parser.add_argument('-U', dest='undefines', metavar='undefine', action='append', default=[],
help='Pass an undefine to the preprocessor')
args = parser.parse_args(args)
QUIET = args.quiet
# Avoid parsing problems due to gcc specifc syntax.
cpp_opts = ['-D_GNU_SOURCE']
# Add the user options to the list as well.
for path in args.includes:
cpp_opts.append('-I' + path)
for arg in args.defines:
cpp_opts.append('-D' + arg)
for arg in args.undefines:
cpp_opts.append('-U' + arg)
# Look for structs in all passed headers.
info = {'defines': {}, 'structs': {}}
for f in args.json:
# This is a JSON file, parse it.
header_files = parse_json(f)
# Inspect all collected structs.
info_fragment = inspect_code(header_files, cpp_opts)
merge_info(info, info_fragment)
output_json(info, args.output)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| 28.161836
| 131
| 0.579381
|
4a0dbb298d0439d329080a5b81b3b6db17354993
| 53,390
|
py
|
Python
|
google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/services/adaptation/client.py
|
googleapis/googleapis-gen
|
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
|
[
"Apache-2.0"
] | 7
|
2021-02-21T10:39:41.000Z
|
2021-12-07T07:31:28.000Z
|
google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/services/adaptation/client.py
|
googleapis/googleapis-gen
|
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
|
[
"Apache-2.0"
] | 6
|
2021-02-02T23:46:11.000Z
|
2021-11-15T01:46:02.000Z
|
google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/services/adaptation/client.py
|
googleapis/googleapis-gen
|
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
|
[
"Apache-2.0"
] | 4
|
2021-01-28T23:25:45.000Z
|
2021-08-30T01:55:16.000Z
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.speech_v1p1beta1.services.adaptation import pagers
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation
from google.cloud.speech_v1p1beta1.types import resource
from google.protobuf import field_mask_pb2 # type: ignore
from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import AdaptationGrpcTransport
from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport
class AdaptationClientMeta(type):
"""Metaclass for the Adaptation client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]]
_transport_registry["grpc"] = AdaptationGrpcTransport
_transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport
def get_transport_class(cls,
label: str = None,
) -> Type[AdaptationTransport]:
"""Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class AdaptationClient(metaclass=AdaptationClientMeta):
"""Service that implements Google Cloud Speech Adaptation API."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "speech.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
AdaptationClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_info(info)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
AdaptationClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@property
def transport(self) -> AdaptationTransport:
"""Returns the transport used by the client instance.
Returns:
AdaptationTransport: The transport used by the client
instance.
"""
return self._transport
@staticmethod
def custom_class_path(project: str,location: str,custom_class: str,) -> str:
"""Returns a fully-qualified custom_class string."""
return "projects/{project}/locations/{location}/customClasses/{custom_class}".format(project=project, location=location, custom_class=custom_class, )
@staticmethod
def parse_custom_class_path(path: str) -> Dict[str,str]:
"""Parses a custom_class path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/customClasses/(?P<custom_class>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def phrase_set_path(project: str,location: str,phrase_set: str,) -> str:
"""Returns a fully-qualified phrase_set string."""
return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format(project=project, location=location, phrase_set=phrase_set, )
@staticmethod
def parse_phrase_set_path(path: str) -> Dict[str,str]:
"""Parses a phrase_set path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/phraseSets/(?P<phrase_set>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str, ) -> str:
"""Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(billing_account=billing_account, )
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str,str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_folder_path(folder: str, ) -> str:
"""Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder, )
@staticmethod
def parse_common_folder_path(path: str) -> Dict[str,str]:
"""Parse a folder path into its component segments."""
m = re.match(r"^folders/(?P<folder>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_organization_path(organization: str, ) -> str:
"""Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization, )
@staticmethod
def parse_common_organization_path(path: str) -> Dict[str,str]:
"""Parse a organization path into its component segments."""
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_project_path(project: str, ) -> str:
"""Returns a fully-qualified project string."""
return "projects/{project}".format(project=project, )
@staticmethod
def parse_common_project_path(path: str) -> Dict[str,str]:
"""Parse a project path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_location_path(project: str, location: str, ) -> str:
"""Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(project=project, location=location, )
@staticmethod
def parse_common_location_path(path: str) -> Dict[str,str]:
"""Parse a location path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
return m.groupdict() if m else {}
def __init__(self, *,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, AdaptationTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the adaptation client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, AdaptationTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")))
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
if is_mtls:
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, AdaptationTransport):
# transport is a AdaptationTransport instance.
if credentials or client_options.credentials_file:
raise ValueError("When providing a transport instance, "
"provide its credentials directly.")
if client_options.scopes:
raise ValueError(
"When providing a transport instance, provide its scopes "
"directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=True,
)
def create_phrase_set(self,
request: Union[cloud_speech_adaptation.CreatePhraseSetRequest, dict] = None,
*,
parent: str = None,
phrase_set: resource.PhraseSet = None,
phrase_set_id: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.PhraseSet:
r"""Create a set of phrase hints. Each item in the set
can be a single word or a multi-word phrase. The items
in the PhraseSet are favored by the recognition model
when you send a call that includes the PhraseSet.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.CreatePhraseSetRequest, dict]):
The request object. Message sent by the client for the
`CreatePhraseSet` method.
parent (str):
Required. The parent resource where this phrase set will
be created. Format:
{api_version}/projects/{project}/locations/{location}/phraseSets
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet):
Required. The phrase set to create.
This corresponds to the ``phrase_set`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
phrase_set_id (str):
Required. The ID to use for the phrase set, which will
become the final component of the phrase set's resource
name.
This value should be 4-63 characters, and valid
characters are /[a-z][0-9]-/.
This corresponds to the ``phrase_set_id`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.PhraseSet:
Provides "hints" to the speech
recognizer to favor specific words and
phrases in the results.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent, phrase_set, phrase_set_id])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.CreatePhraseSetRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.CreatePhraseSetRequest):
request = cloud_speech_adaptation.CreatePhraseSetRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
if phrase_set is not None:
request.phrase_set = phrase_set
if phrase_set_id is not None:
request.phrase_set_id = phrase_set_id
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.create_phrase_set]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def get_phrase_set(self,
request: Union[cloud_speech_adaptation.GetPhraseSetRequest, dict] = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.PhraseSet:
r"""Get a phrase set.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.GetPhraseSetRequest, dict]):
The request object. Message sent by the client for the
`GetPhraseSet` method.
name (str):
Required. The name of the phrase set to retrieve.
Format:
{api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.PhraseSet:
Provides "hints" to the speech
recognizer to favor specific words and
phrases in the results.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.GetPhraseSetRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.GetPhraseSetRequest):
request = cloud_speech_adaptation.GetPhraseSetRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_phrase_set]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def list_phrase_set(self,
request: Union[cloud_speech_adaptation.ListPhraseSetRequest, dict] = None,
*,
parent: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListPhraseSetPager:
r"""List phrase sets.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.ListPhraseSetRequest, dict]):
The request object. Message sent by the client for the
`ListPhraseSet` method.
parent (str):
Required. The parent, which owns this
collection of phrase set. Format:
projects/{project}/locations/{location}
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.services.adaptation.pagers.ListPhraseSetPager:
Message returned to the client by the ListPhraseSet
method.
Iterating over this object will yield results and
resolve additional pages automatically.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.ListPhraseSetRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.ListPhraseSetRequest):
request = cloud_speech_adaptation.ListPhraseSetRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list_phrase_set]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListPhraseSetPager(
method=rpc,
request=request,
response=response,
metadata=metadata,
)
# Done; return the response.
return response
def update_phrase_set(self,
request: Union[cloud_speech_adaptation.UpdatePhraseSetRequest, dict] = None,
*,
phrase_set: resource.PhraseSet = None,
update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.PhraseSet:
r"""Update a phrase set.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.UpdatePhraseSetRequest, dict]):
The request object. Message sent by the client for the
`UpdatePhraseSet` method.
phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet):
Required. The phrase set to update.
The phrase set's ``name`` field is used to identify the
set to be updated. Format:
{api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set}
This corresponds to the ``phrase_set`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
The list of fields to be updated.
This corresponds to the ``update_mask`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.PhraseSet:
Provides "hints" to the speech
recognizer to favor specific words and
phrases in the results.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([phrase_set, update_mask])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.UpdatePhraseSetRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.UpdatePhraseSetRequest):
request = cloud_speech_adaptation.UpdatePhraseSetRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if phrase_set is not None:
request.phrase_set = phrase_set
if update_mask is not None:
request.update_mask = update_mask
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.update_phrase_set]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("phrase_set.name", request.phrase_set.name),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def delete_phrase_set(self,
request: Union[cloud_speech_adaptation.DeletePhraseSetRequest, dict] = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Delete a phrase set.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.DeletePhraseSetRequest, dict]):
The request object. Message sent by the client for the
`DeletePhraseSet` method.
name (str):
Required. The name of the phrase set to delete. Format:
{api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.DeletePhraseSetRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.DeletePhraseSetRequest):
request = cloud_speech_adaptation.DeletePhraseSetRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete_phrase_set]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
def create_custom_class(self,
request: Union[cloud_speech_adaptation.CreateCustomClassRequest, dict] = None,
*,
parent: str = None,
custom_class: resource.CustomClass = None,
custom_class_id: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.CustomClass:
r"""Create a custom class.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.CreateCustomClassRequest, dict]):
The request object. Message sent by the client for the
`CreateCustomClass` method.
parent (str):
Required. The parent resource where this custom class
will be created. Format:
{api_version}/projects/{project}/locations/{location}/customClasses
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
custom_class (google.cloud.speech_v1p1beta1.types.CustomClass):
Required. The custom class to create.
This corresponds to the ``custom_class`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
custom_class_id (str):
Required. The ID to use for the custom class, which will
become the final component of the custom class' resource
name.
This value should be 4-63 characters, and valid
characters are /[a-z][0-9]-/.
This corresponds to the ``custom_class_id`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.CustomClass:
A set of words or phrases that
represents a common concept likely to
appear in your audio, for example a list
of passenger ship names. CustomClass
items can be substituted into
placeholders that you set in PhraseSet
phrases.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent, custom_class, custom_class_id])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.CreateCustomClassRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.CreateCustomClassRequest):
request = cloud_speech_adaptation.CreateCustomClassRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
if custom_class is not None:
request.custom_class = custom_class
if custom_class_id is not None:
request.custom_class_id = custom_class_id
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.create_custom_class]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def get_custom_class(self,
request: Union[cloud_speech_adaptation.GetCustomClassRequest, dict] = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.CustomClass:
r"""Get a custom class.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.GetCustomClassRequest, dict]):
The request object. Message sent by the client for the
`GetCustomClass` method.
name (str):
Required. The name of the custom class to retrieve.
Format:
{api_version}/projects/{project}/locations/{location}/customClasses/{custom_class}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.CustomClass:
A set of words or phrases that
represents a common concept likely to
appear in your audio, for example a list
of passenger ship names. CustomClass
items can be substituted into
placeholders that you set in PhraseSet
phrases.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.GetCustomClassRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.GetCustomClassRequest):
request = cloud_speech_adaptation.GetCustomClassRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_custom_class]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def list_custom_classes(self,
request: Union[cloud_speech_adaptation.ListCustomClassesRequest, dict] = None,
*,
parent: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListCustomClassesPager:
r"""List custom classes.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.ListCustomClassesRequest, dict]):
The request object. Message sent by the client for the
`ListCustomClasses` method.
parent (str):
Required. The parent, which owns this collection of
custom classes. Format:
{api_version}/projects/{project}/locations/{location}/customClasses
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.services.adaptation.pagers.ListCustomClassesPager:
Message returned to the client by the ListCustomClasses
method.
Iterating over this object will yield results and
resolve additional pages automatically.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.ListCustomClassesRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.ListCustomClassesRequest):
request = cloud_speech_adaptation.ListCustomClassesRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list_custom_classes]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListCustomClassesPager(
method=rpc,
request=request,
response=response,
metadata=metadata,
)
# Done; return the response.
return response
def update_custom_class(self,
request: Union[cloud_speech_adaptation.UpdateCustomClassRequest, dict] = None,
*,
custom_class: resource.CustomClass = None,
update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> resource.CustomClass:
r"""Update a custom class.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.UpdateCustomClassRequest, dict]):
The request object. Message sent by the client for the
`UpdateCustomClass` method.
custom_class (google.cloud.speech_v1p1beta1.types.CustomClass):
Required. The custom class to update.
The custom class's ``name`` field is used to identify
the custom class to be updated. Format:
{api_version}/projects/{project}/locations/{location}/customClasses/{custom_class}
This corresponds to the ``custom_class`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
The list of fields to be updated.
This corresponds to the ``update_mask`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.speech_v1p1beta1.types.CustomClass:
A set of words or phrases that
represents a common concept likely to
appear in your audio, for example a list
of passenger ship names. CustomClass
items can be substituted into
placeholders that you set in PhraseSet
phrases.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([custom_class, update_mask])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.UpdateCustomClassRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.UpdateCustomClassRequest):
request = cloud_speech_adaptation.UpdateCustomClassRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if custom_class is not None:
request.custom_class = custom_class
if update_mask is not None:
request.update_mask = update_mask
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.update_custom_class]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("custom_class.name", request.custom_class.name),
)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def delete_custom_class(self,
request: Union[cloud_speech_adaptation.DeleteCustomClassRequest, dict] = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Delete a custom class.
Args:
request (Union[google.cloud.speech_v1p1beta1.types.DeleteCustomClassRequest, dict]):
The request object. Message sent by the client for the
`DeleteCustomClass` method.
name (str):
Required. The name of the custom class to delete.
Format:
{api_version}/projects/{project}/locations/{location}/customClasses/{custom_class}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError('If the `request` argument is set, then none of '
'the individual field arguments should be set.')
# Minor optimization to avoid making a copy if the user passes
# in a cloud_speech_adaptation.DeleteCustomClassRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, cloud_speech_adaptation.DeleteCustomClassRequest):
request = cloud_speech_adaptation.DeleteCustomClassRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete_custom_class]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
"""Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
"""
self.transport.close()
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-speech",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = (
"AdaptationClient",
)
| 43.548124
| 157
| 0.613149
|
4a0dbbdbcf3220deb2156b84974a8c6059b1bb5a
| 3,752
|
py
|
Python
|
CQPixiv/pixiv/get.py
|
bbbboom/nonebot-plugin
|
e41c1d64baf39c7ec04dd37be6ca490369ccdadd
|
[
"MIT"
] | null | null | null |
CQPixiv/pixiv/get.py
|
bbbboom/nonebot-plugin
|
e41c1d64baf39c7ec04dd37be6ca490369ccdadd
|
[
"MIT"
] | null | null | null |
CQPixiv/pixiv/get.py
|
bbbboom/nonebot-plugin
|
e41c1d64baf39c7ec04dd37be6ca490369ccdadd
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from pixivpy3 import *
from . import utils
from .constant import *
import random
import json
class GetPictures():
def __init__(self, path, content):
self.api = ByPassSniApi()
self.api.require_appapi_hosts()
self.api.set_accept_language('zh-cn')
refresh_token = content.get('refresh_token')
if refresh_token == None or refresh_token == '':
self.api.login(content['account'], content['password'])
content['refresh_token'] = self.api.refresh_token
with open(path, 'w') as f:
f.write(json.dumps(content))
else:
# 如果有保存过的token则直接登录
self.api.auth(refresh_token=refresh_token)
async def __saveToken(path, content):
content['refresh_token'] = self.api.refresh_token
await utils.writeJson(path, content)
async def __getAllPictures(self, id):
result = {
"data": [],
"number": 0,
"next_url": []
}
offset = 0
mark = True
while mark:
json_result = self.api.user_illusts(id, offset = offset)
result['data'] += json_result['illusts']
result['number'] += 1
if json_result['next_url'] == None:
mark = False
result['next_url'].append(json_result['next_url'])
# print(json_result['next_url'])
offset += 30
return result
async def __organizePictures(self, result):
# 如果获取到的列表为空则跳过
if len(result['data']) <= 0:
raise Exception
newResult = {
"data": [],
"number": 0,
"count": 0
}
for i in result['data']:
newStructure = {
'id': i['id'],
'count': i['page_count'],
'url': [],
'url_large': [],
'cat_url': [],
'cat_url_large': []
}
newStructure['count'] = i['page_count']
newStructure['id'] = i['id']
# url
if 'original_image_url' in i['meta_single_page']:
newStructure['url'].append(i['meta_single_page']['original_image_url'])
newStructure['url_large'].append(i['image_urls']['large'])
else:
for j in i['meta_pages']:
newStructure['url'].append(j['image_urls']['original'])
newStructure['url_large'].append(j['image_urls']['large'])
# cat_url
for j in newStructure['url']:
newStructure['cat_url'].append(j.replace('i.pximg.net', 'i.pixiv.cat'))
for j in newStructure['url_large']:
newStructure['cat_url_large'].append(j.replace('i.pximg.net', 'i.pixiv.cat'))
newResult['data'].append(newStructure)
newResult['number'] += 1
newResult['count'] += newStructure['count']
return newResult
async def oneTimeIncome(self, id):
path = './pixiv/data/images/' + str(id) + '.json'
await utils.checkFolder(path)
newResult = await self.__organizePictures(await self.__getAllPictures(id))
await utils.writeJson(path, newResult)
@staticmethod
async def randomSelection(model = 'completelyRandom', id = ''):
path = './pixiv/data/images/'
if model == 'completelyRandom':
path = await utils.randomlyExtractedFromTheFolder(path)
if model == 'precise':
path += str(id) + '.json'
content = await utils.readJson(path)
if content == FAILURE:
return FAILURE
return random.choice(random.choice(content['data'])['cat_url'])
| 35.396226
| 93
| 0.53758
|
4a0dbc35e64f998c17c289ae282192bdc20bb682
| 12,935
|
py
|
Python
|
setup.py
|
pmreyes2/pyglow
|
4a4d51a210e788e50e3fca645d6af1ea0be4c8c5
|
[
"MIT"
] | 1
|
2020-12-22T08:51:18.000Z
|
2020-12-22T08:51:18.000Z
|
setup.py
|
pmreyes2/pyglow
|
4a4d51a210e788e50e3fca645d6af1ea0be4c8c5
|
[
"MIT"
] | 2
|
2017-04-07T22:10:01.000Z
|
2017-04-10T23:26:15.000Z
|
setup.py
|
pmreyes2/pyglow
|
4a4d51a210e788e50e3fca645d6af1ea0be4c8c5
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
import glob
import os
from io import open # For Python 2 compatibility
from numpy.distutils.core import setup, Extension
DL_MODELS = 'src/pyglow/models/dl_models'
KPAP_FILES = sorted(glob.glob('src/pyglow/kpap/*'))
DST_FILES = sorted(glob.glob('src/pyglow/dst/*'))
AE_FILES = sorted(glob.glob('src/pyglow/ae/*'))
def reencode(dosfile, target='utf-8'):
"""
Remove invalid unicode characters that appear in the comments
"""
with open(dosfile, 'r', encoding='cp1251', errors='ignore') as f:
content = f.read()
with open(dosfile, 'w', encoding=target) as f:
f.write(content)
return
# IGRF 11:
igrf11 = Extension(
name='igrf11py',
sources=[os.path.join(DL_MODELS, 'igrf11', fname) for fname in [
'igrf11_modified.f',
'sig_file_patched.pyf',
]],
)
# IGRF 12:
igrf12 = Extension(
name='igrf12py',
sources=[os.path.join(DL_MODELS, 'igrf12', fname) for fname in [
'igrf12_modified.f',
'sig_file_patched.pyf',
]],
)
# HWM 93:
hwm93 = Extension(
name='hwm93py',
sources=[os.path.join(DL_MODELS, 'hwm93', fname) for fname in [
'hwm93_modified.f',
'sig_file_patched.pyf',
]],
extra_f77_compile_args=['-std=legacy'],
)
# Rencode HWM07 sources:
hwm07_sources = [os.path.join(DL_MODELS, 'hwm07', fname) for fname in [
'hwm07e_modified.f90',
'apexcord.f90',
]]
for source in hwm07_sources:
reencode(source)
# Use the makefile to generate a signature
os.system('make -Cpyglow/models/dl_models/hwm07 sig')
# HWM07:
hwm07 = Extension(
name='hwm07py',
sources=hwm07_sources + [os.path.join(DL_MODELS, 'hwm07', 'sig_file.pyf')],
# f2py_options=['only: hwmqt :'], # where is the right place to put this?
)
# HWM14:
hwm14 = Extension(
name='hwm14py',
sources=[os.path.join(DL_MODELS, 'hwm14', fname) for fname in [
'hwm14.f90',
'sig_file.pyf',
]],
extra_f77_compile_args=['-std=legacy'],
)
# IRI 12:
iri12 = Extension(
name='iri12py',
sources=[os.path.join(DL_MODELS, 'iri12', fname) for fname in [
'cira.for',
'igrf.for',
'iridreg_modified.for',
'irifun.for',
'irisub.for',
'iritec.for',
'iriflip.for',
'sig_file_patched.pyf',
]],
extra_f77_compile_args=[
'-std=legacy',
'-w',
'-O2',
'-fbacktrace',
'-fno-automatic',
'-fPIC',
],
)
# IRI16:
iri16 = Extension(
name='iri16py',
sources=[os.path.join(DL_MODELS, 'iri16', fname) for fname in [
'cira.for',
'igrf.for',
'iridreg_modified.for',
'irifun.for',
'irisub.for',
'iritec.for',
'iriflip_modified.for',
'cosd_sind.for',
'sig_file_patched.pyf',
]],
extra_f77_compile_args=[
'-std=legacy',
'-w',
'-O2',
'-fbacktrace',
'-fno-automatic',
'-fPIC',
],
)
# MSIS00:
msis00 = Extension(
name='msis00py',
sources=[os.path.join(DL_MODELS, 'msis', fname) for fname in [
'nrlmsise00_sub_patched.for',
'sig_file_patched.pyf'
]],
extra_f77_compile_args=['-std=legacy'],
)
# Distutils setup:
setup(
name='pyglow',
url='https://github.com/timduly4/pyglow',
author='Timothy M. Duly',
author_email='timduly4@gmail.com',
packages=['pyglow'],
package_dir={'pyglow': 'src/pyglow'},
ext_modules=[
igrf11,
igrf12,
hwm93,
hwm07,
hwm14,
iri12,
iri16,
msis00,
],
data_files=[
('pyglow_trash', ['src/pyglow/models/Makefile']),
('pyglow_trash', ['src/pyglow/models/get_models.py']),
('pyglow_trash', ['src/pyglow/models/dl_models/hwm07/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/hwm93/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/igrf11/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/igrf12/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/iri12/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/iri16/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/msis/dummy.txt']),
('pyglow_trash', ['src/pyglow/models/dl_models/hwm14/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/hwm07/hwm07e.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/hwm07/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/hwm93/hwm93.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/hwm93/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/hwm93/sig.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf11/igrf11.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf11/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf11/sig.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf12/igrf12.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf12/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/igrf12/sig.patch']),
('pyglow_trash', [
'src/pyglow/models/f2py/iri12/delete_iriflip_comments.py'
]),
('pyglow_trash', ['src/pyglow/models/f2py/iri12/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/iri12/sig.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/iri12/iridreg.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/msis/Makefile']),
('pyglow_trash', ['src/pyglow/models/f2py/msis/nrlmsise00_sub.patch']),
('pyglow_trash', ['src/pyglow/models/f2py/msis/sig.patch']),
('pyglow/hwm07_data/', [
'src/pyglow/models/dl_models/hwm07/apexgrid.dat',
'src/pyglow/models/dl_models/hwm07/dwm07b_104i.dat',
'src/pyglow/models/dl_models/hwm07/hwm071308e.dat',
]),
(
'pyglow/hwm14_data/',
[
'src/pyglow/models/dl_models/hwm14/gd2qd.dat',
'src/pyglow/models/dl_models/hwm14/dwm07b_104i.dat',
'src/pyglow/models/dl_models/hwm14/hwm14-beta.bin',
'src/pyglow/models/dl_models/hwm14/hwm14.f90',
],
),
(
'pyglow/iri12_data/',
[
'src/pyglow/models/dl_models/iri12/apf107.dat',
'src/pyglow/models/dl_models/iri12/ccir11.asc',
'src/pyglow/models/dl_models/iri12/ccir12.asc',
'src/pyglow/models/dl_models/iri12/ccir13.asc',
'src/pyglow/models/dl_models/iri12/ccir14.asc',
'src/pyglow/models/dl_models/iri12/ccir15.asc',
'src/pyglow/models/dl_models/iri12/ccir16.asc',
'src/pyglow/models/dl_models/iri12/ccir17.asc',
'src/pyglow/models/dl_models/iri12/ccir18.asc',
'src/pyglow/models/dl_models/iri12/ccir19.asc',
'src/pyglow/models/dl_models/iri12/ccir20.asc',
'src/pyglow/models/dl_models/iri12/ccir21.asc',
'src/pyglow/models/dl_models/iri12/ccir22.asc',
'src/pyglow/models/dl_models/iri12/dgrf1945.dat',
'src/pyglow/models/dl_models/iri12/dgrf1950.dat',
'src/pyglow/models/dl_models/iri12/dgrf1955.dat',
'src/pyglow/models/dl_models/iri12/dgrf1960.dat',
'src/pyglow/models/dl_models/iri12/dgrf1965.dat',
'src/pyglow/models/dl_models/iri12/dgrf1970.dat',
'src/pyglow/models/dl_models/iri12/dgrf1975.dat',
'src/pyglow/models/dl_models/iri12/dgrf1980.dat',
'src/pyglow/models/dl_models/iri12/dgrf1985.dat',
'src/pyglow/models/dl_models/iri12/dgrf1990.dat',
'src/pyglow/models/dl_models/iri12/dgrf1995.dat',
'src/pyglow/models/dl_models/iri12/dgrf2000.dat',
'src/pyglow/models/dl_models/iri12/dgrf2005.dat',
'src/pyglow/models/dl_models/iri12/ig_rz_IPS.dat',
'src/pyglow/models/dl_models/iri12/ig_rz_SEC.dat',
'src/pyglow/models/dl_models/iri12/ig_rz.dat',
'src/pyglow/models/dl_models/iri12/igrf2010.dat',
'src/pyglow/models/dl_models/iri12/igrf2010s.dat',
'src/pyglow/models/dl_models/iri12/ursi11.asc',
'src/pyglow/models/dl_models/iri12/ursi12.asc',
'src/pyglow/models/dl_models/iri12/ursi13.asc',
'src/pyglow/models/dl_models/iri12/ursi14.asc',
'src/pyglow/models/dl_models/iri12/ursi15.asc',
'src/pyglow/models/dl_models/iri12/ursi16.asc',
'src/pyglow/models/dl_models/iri12/ursi17.asc',
'src/pyglow/models/dl_models/iri12/ursi18.asc',
'src/pyglow/models/dl_models/iri12/ursi19.asc',
'src/pyglow/models/dl_models/iri12/ursi20.asc',
'src/pyglow/models/dl_models/iri12/ursi21.asc',
'src/pyglow/models/dl_models/iri12/ursi22.asc',
],
),
(
'pyglow/iri16_data/',
[
'src/pyglow/models/dl_models/iri16/apf107.dat',
'src/pyglow/models/dl_models/iri16/ccir11.asc',
'src/pyglow/models/dl_models/iri16/ccir12.asc',
'src/pyglow/models/dl_models/iri16/ccir13.asc',
'src/pyglow/models/dl_models/iri16/ccir14.asc',
'src/pyglow/models/dl_models/iri16/ccir15.asc',
'src/pyglow/models/dl_models/iri16/ccir16.asc',
'src/pyglow/models/dl_models/iri16/ccir17.asc',
'src/pyglow/models/dl_models/iri16/ccir18.asc',
'src/pyglow/models/dl_models/iri16/ccir19.asc',
'src/pyglow/models/dl_models/iri16/ccir20.asc',
'src/pyglow/models/dl_models/iri16/ccir21.asc',
'src/pyglow/models/dl_models/iri16/ccir22.asc',
'src/pyglow/models/dl_models/iri16/dgrf1945.dat',
'src/pyglow/models/dl_models/iri16/dgrf1950.dat',
'src/pyglow/models/dl_models/iri16/dgrf1955.dat',
'src/pyglow/models/dl_models/iri16/dgrf1960.dat',
'src/pyglow/models/dl_models/iri16/dgrf1965.dat',
'src/pyglow/models/dl_models/iri16/dgrf1970.dat',
'src/pyglow/models/dl_models/iri16/dgrf1975.dat',
'src/pyglow/models/dl_models/iri16/dgrf1980.dat',
'src/pyglow/models/dl_models/iri16/dgrf1985.dat',
'src/pyglow/models/dl_models/iri16/dgrf1990.dat',
'src/pyglow/models/dl_models/iri16/dgrf1995.dat',
'src/pyglow/models/dl_models/iri16/dgrf2000.dat',
'src/pyglow/models/dl_models/iri16/dgrf2005.dat',
'src/pyglow/models/dl_models/iri16/dgrf2010.dat',
'src/pyglow/models/dl_models/iri16/ig_rz.dat',
'src/pyglow/models/dl_models/iri16/igrf2015.dat',
'src/pyglow/models/dl_models/iri16/igrf2015s.dat',
'src/pyglow/models/dl_models/iri16/mcsat11.dat',
'src/pyglow/models/dl_models/iri16/mcsat12.dat',
'src/pyglow/models/dl_models/iri16/mcsat13.dat',
'src/pyglow/models/dl_models/iri16/mcsat14.dat',
'src/pyglow/models/dl_models/iri16/mcsat15.dat',
'src/pyglow/models/dl_models/iri16/mcsat16.dat',
'src/pyglow/models/dl_models/iri16/mcsat17.dat',
'src/pyglow/models/dl_models/iri16/mcsat18.dat',
'src/pyglow/models/dl_models/iri16/mcsat19.dat',
'src/pyglow/models/dl_models/iri16/mcsat20.dat',
'src/pyglow/models/dl_models/iri16/mcsat21.dat',
'src/pyglow/models/dl_models/iri16/mcsat22.dat',
'src/pyglow/models/dl_models/iri16/ursi11.asc',
'src/pyglow/models/dl_models/iri16/ursi12.asc',
'src/pyglow/models/dl_models/iri16/ursi13.asc',
'src/pyglow/models/dl_models/iri16/ursi14.asc',
'src/pyglow/models/dl_models/iri16/ursi15.asc',
'src/pyglow/models/dl_models/iri16/ursi16.asc',
'src/pyglow/models/dl_models/iri16/ursi17.asc',
'src/pyglow/models/dl_models/iri16/ursi18.asc',
'src/pyglow/models/dl_models/iri16/ursi19.asc',
'src/pyglow/models/dl_models/iri16/ursi20.asc',
'src/pyglow/models/dl_models/iri16/ursi21.asc',
'src/pyglow/models/dl_models/iri16/ursi22.asc',
],
),
(
'pyglow/kpap/',
KPAP_FILES,
),
(
'pyglow/dst/',
DST_FILES,
),
(
'pyglow/ae/',
AE_FILES,
),
],
)
print("... All done!")
| 39.677914
| 79
| 0.588094
|
4a0dbd4148d0c6bbf0897eab8653f272d4fdb2f6
| 954
|
py
|
Python
|
backend/workspaces/Log/permissions.py
|
makakken/roseguarden
|
9a867f3d5e979b990bf474dcba81e5e9d0814c6a
|
[
"MIT"
] | null | null | null |
backend/workspaces/Log/permissions.py
|
makakken/roseguarden
|
9a867f3d5e979b990bf474dcba81e5e9d0814c6a
|
[
"MIT"
] | 50
|
2021-03-28T03:06:19.000Z
|
2021-10-18T12:36:16.000Z
|
backend/workspaces/Log/permissions.py
|
makakken/roseguarden
|
9a867f3d5e979b990bf474dcba81e5e9d0814c6a
|
[
"MIT"
] | 1
|
2021-07-30T07:12:46.000Z
|
2021-07-30T07:12:46.000Z
|
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__authors__ = ["Marcus Drobisch"]
__contact__ = "roseguarden@fabba.space"
__credits__ = []
__license__ = "GPLv3"
from core.workspaces.permission import Permission
# Define your Permissions here
class ViewLogs(Permission):
description = "Allow to see the logs"
| 31.8
| 78
| 0.778826
|
4a0dbdee01712f78718ddc814c2048e91e0240f7
| 102
|
py
|
Python
|
01 - Fundamentos/ex025.py
|
epedropaulo/MyPython
|
cdb3602a01aedac26047f5b11a36a2262d4cc2ea
|
[
"MIT"
] | null | null | null |
01 - Fundamentos/ex025.py
|
epedropaulo/MyPython
|
cdb3602a01aedac26047f5b11a36a2262d4cc2ea
|
[
"MIT"
] | null | null | null |
01 - Fundamentos/ex025.py
|
epedropaulo/MyPython
|
cdb3602a01aedac26047f5b11a36a2262d4cc2ea
|
[
"MIT"
] | null | null | null |
nome = input('Digite seu nome: ')
print(f'Seu nome tem Silva : {"silva" in nome.lower().split()}.')
| 34
| 66
| 0.627451
|
4a0dc03d6eee0a7ac2be7dc512f8b3a8544c3267
| 3,696
|
py
|
Python
|
NLPEngine/utils/markdown.py
|
hmi-digital/bot_platform
|
91a26e566b07fa309774d0333a6bccf3d64cccc5
|
[
"MIT"
] | null | null | null |
NLPEngine/utils/markdown.py
|
hmi-digital/bot_platform
|
91a26e566b07fa309774d0333a6bccf3d64cccc5
|
[
"MIT"
] | null | null | null |
NLPEngine/utils/markdown.py
|
hmi-digital/bot_platform
|
91a26e566b07fa309774d0333a6bccf3d64cccc5
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import re
import os
import codecs
import json
from typing import Text, Optional, Tuple, Match
from warnings import simplefilter
from utils import log_util
# ignore all warnings
simplefilter(action='ignore')
##Global parameters
scriptDir = os.path.dirname(__file__)
datapath = os.path.join(scriptDir, '..', 'training_data', 'intents')
INTENT = "intent"
SYNONYM = "synonym"
REGEX = "regex"
LOOKUP = "lookup"
available_sections = [INTENT, SYNONYM, REGEX, LOOKUP]
current_section = None
current_title = None
item_regex = re.compile(r"\s*[-*+]\s*(.+)")
comment_regex = re.compile(r"<!--[\s\S]*?--!*>", re.MULTILINE)
fname_regex = re.compile(r"\s*([^-*+]+)")
entity_regex = re.compile(
r"\[(?P<entity_text>[^\]]+?)\](\((?P<entity>[^:)]+?)(?:\:(?P<value>[^)]+))?\)|\{(?P<entity_dict>[^}]+?)\})"
)
ESCAPE_DCT = {"\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
ESCAPE = re.compile(r"[\b\f\n\r\t]")
GROUP_COMPLETE_MATCH = 0
current_section = ""
current_intent = ""
intent = []
utterance = []
def encode_string(s: Text) -> Text:
"""Return a encoded python string."""
def replace(match: Match) -> Text:
return ESCAPE_DCT[match.group(GROUP_COMPLETE_MATCH)]
return ESCAPE.sub(replace, s)
def find_section_header(line: Text) -> Optional[Tuple[Text, Text]]:
"""Checks if the current line contains a section header
and returns the section and the title."""
match = re.search(r"##\s*(.+?):(.+)", line)
if match is not None:
return match.group(1), match.group(2)
return None
def set_current_section(section: Text, title: Text) -> None:
"""Update parsing mode."""
if section not in available_sections:
log_util.log_errormsg(
f"[MARKDOWN] found markdown section {section} which is not in the allowed sections {', '.join(available_sections)}.")
raise ValueError(
f"[MARKDOWN] found markdown section {section} which is not in the allowed sections {', '.join(available_sections)}.")
global current_section, current_intent
current_section = section
current_intent = title
def parse_item(line: Text) -> None:
"""Parses an md list item line based on the current section type."""
match = re.match(item_regex, line)
if match:
item = match.group(1)
plain_text = re.sub(
entity_regex, lambda m: m.groupdict()["entity_text"], item
)
if current_section == INTENT:
utterance.append(plain_text)
intent.append(current_intent)
else:
pass
else:
pass
def process_data(domain: Text, locale: Text) -> None:
global utterance
global intent
#clear the list before loading
utterance.clear()
intent.clear()
try:
file = codecs.open(os.path.join(datapath, domain + '_' + locale + ".md"), 'r', 'utf-8')
lines = file.read().split("\n")
log_util.log_infomsg(f"[MARKDOWN] recieved data, total lines: {len(lines)}")
for line in lines:
line = line.strip()
header = find_section_header(line)
if header:
set_current_section(header[0], header[1])
else:
parse_item(line)
return utterance, intent
except FileNotFoundError:
log_util.log_errormsg(
f"[MARKDOWN] no file found for given domain {domain}, ensure that data is given in format .md.")
return json.loads(
'{"response":f"ERROR: no file found for given domain {domain}, ensure that data is given in format .md."}')
raise ValueError(f"no file found for given domain {domain}, ensure that data is given in format .md.")
| 31.862069
| 129
| 0.624459
|
4a0dc0d730996da43d5653f4750b201789d79232
| 11,763
|
py
|
Python
|
moto/config/exceptions.py
|
moseb/moto
|
d596560971ae289f102b9aecb9939b3c49a56ac5
|
[
"Apache-2.0"
] | 3
|
2020-08-04T20:29:41.000Z
|
2020-11-09T09:28:19.000Z
|
moto/config/exceptions.py
|
moseb/moto
|
d596560971ae289f102b9aecb9939b3c49a56ac5
|
[
"Apache-2.0"
] | 1
|
2016-02-11T14:54:01.000Z
|
2016-02-12T14:11:05.000Z
|
moto/config/exceptions.py
|
moseb/moto
|
d596560971ae289f102b9aecb9939b3c49a56ac5
|
[
"Apache-2.0"
] | 2
|
2017-03-02T05:59:52.000Z
|
2020-09-03T13:25:44.000Z
|
from __future__ import unicode_literals
from moto.core.exceptions import JsonRESTError
class NameTooLongException(JsonRESTError):
code = 400
def __init__(self, name, location):
message = (
"1 validation error detected: Value '{name}' at '{location}' failed to satisfy"
" constraint: Member must have length less than or equal to 256".format(
name=name, location=location
)
)
super(NameTooLongException, self).__init__("ValidationException", message)
class InvalidConfigurationRecorderNameException(JsonRESTError):
code = 400
def __init__(self, name):
message = "The configuration recorder name '{name}' is not valid, blank string.".format(
name=name
)
super(InvalidConfigurationRecorderNameException, self).__init__(
"InvalidConfigurationRecorderNameException", message
)
class MaxNumberOfConfigurationRecordersExceededException(JsonRESTError):
code = 400
def __init__(self, name):
message = (
"Failed to put configuration recorder '{name}' because the maximum number of "
"configuration recorders: 1 is reached.".format(name=name)
)
super(MaxNumberOfConfigurationRecordersExceededException, self).__init__(
"MaxNumberOfConfigurationRecordersExceededException", message
)
class InvalidRecordingGroupException(JsonRESTError):
code = 400
def __init__(self):
message = "The recording group provided is not valid"
super(InvalidRecordingGroupException, self).__init__(
"InvalidRecordingGroupException", message
)
class InvalidResourceTypeException(JsonRESTError):
code = 400
def __init__(self, bad_list, good_list):
message = (
"{num} validation error detected: Value '{bad_list}' at "
"'configurationRecorder.recordingGroup.resourceTypes' failed to satisfy constraint: "
"Member must satisfy constraint: [Member must satisfy enum value set: {good_list}]".format(
num=len(bad_list), bad_list=bad_list, good_list=good_list
)
)
# For PY2:
message = str(message)
super(InvalidResourceTypeException, self).__init__(
"ValidationException", message
)
class NoSuchConfigurationAggregatorException(JsonRESTError):
code = 400
def __init__(self, number=1):
if number == 1:
message = "The configuration aggregator does not exist. Check the configuration aggregator name and try again."
else:
message = (
"At least one of the configuration aggregators does not exist. Check the configuration aggregator"
" names and try again."
)
super(NoSuchConfigurationAggregatorException, self).__init__(
"NoSuchConfigurationAggregatorException", message
)
class NoSuchConfigurationRecorderException(JsonRESTError):
code = 400
def __init__(self, name):
message = "Cannot find configuration recorder with the specified name '{name}'.".format(
name=name
)
super(NoSuchConfigurationRecorderException, self).__init__(
"NoSuchConfigurationRecorderException", message
)
class InvalidDeliveryChannelNameException(JsonRESTError):
code = 400
def __init__(self, name):
message = "The delivery channel name '{name}' is not valid, blank string.".format(
name=name
)
super(InvalidDeliveryChannelNameException, self).__init__(
"InvalidDeliveryChannelNameException", message
)
class NoSuchBucketException(JsonRESTError):
"""We are *only* validating that there is value that is not '' here."""
code = 400
def __init__(self):
message = "Cannot find a S3 bucket with an empty bucket name."
super(NoSuchBucketException, self).__init__("NoSuchBucketException", message)
class InvalidNextTokenException(JsonRESTError):
code = 400
def __init__(self):
message = "The nextToken provided is invalid"
super(InvalidNextTokenException, self).__init__(
"InvalidNextTokenException", message
)
class InvalidS3KeyPrefixException(JsonRESTError):
code = 400
def __init__(self):
message = "The s3 key prefix '' is not valid, empty s3 key prefix."
super(InvalidS3KeyPrefixException, self).__init__(
"InvalidS3KeyPrefixException", message
)
class InvalidSNSTopicARNException(JsonRESTError):
"""We are *only* validating that there is value that is not '' here."""
code = 400
def __init__(self):
message = "The sns topic arn '' is not valid."
super(InvalidSNSTopicARNException, self).__init__(
"InvalidSNSTopicARNException", message
)
class InvalidDeliveryFrequency(JsonRESTError):
code = 400
def __init__(self, value, good_list):
message = (
"1 validation error detected: Value '{value}' at "
"'deliveryChannel.configSnapshotDeliveryProperties.deliveryFrequency' failed to satisfy "
"constraint: Member must satisfy enum value set: {good_list}".format(
value=value, good_list=good_list
)
)
super(InvalidDeliveryFrequency, self).__init__(
"InvalidDeliveryFrequency", message
)
class MaxNumberOfDeliveryChannelsExceededException(JsonRESTError):
code = 400
def __init__(self, name):
message = (
"Failed to put delivery channel '{name}' because the maximum number of "
"delivery channels: 1 is reached.".format(name=name)
)
super(MaxNumberOfDeliveryChannelsExceededException, self).__init__(
"MaxNumberOfDeliveryChannelsExceededException", message
)
class NoSuchDeliveryChannelException(JsonRESTError):
code = 400
def __init__(self, name):
message = "Cannot find delivery channel with specified name '{name}'.".format(
name=name
)
super(NoSuchDeliveryChannelException, self).__init__(
"NoSuchDeliveryChannelException", message
)
class NoAvailableConfigurationRecorderException(JsonRESTError):
code = 400
def __init__(self):
message = "Configuration recorder is not available to put delivery channel."
super(NoAvailableConfigurationRecorderException, self).__init__(
"NoAvailableConfigurationRecorderException", message
)
class NoAvailableDeliveryChannelException(JsonRESTError):
code = 400
def __init__(self):
message = "Delivery channel is not available to start configuration recorder."
super(NoAvailableDeliveryChannelException, self).__init__(
"NoAvailableDeliveryChannelException", message
)
class LastDeliveryChannelDeleteFailedException(JsonRESTError):
code = 400
def __init__(self, name):
message = (
"Failed to delete last specified delivery channel with name '{name}', because there, "
"because there is a running configuration recorder.".format(name=name)
)
super(LastDeliveryChannelDeleteFailedException, self).__init__(
"LastDeliveryChannelDeleteFailedException", message
)
class TooManyAccountSources(JsonRESTError):
code = 400
def __init__(self, length):
locations = ["com.amazonaws.xyz"] * length
message = (
"Value '[{locations}]' at 'accountAggregationSources' failed to satisfy constraint: "
"Member must have length less than or equal to 1".format(
locations=", ".join(locations)
)
)
super(TooManyAccountSources, self).__init__("ValidationException", message)
class DuplicateTags(JsonRESTError):
code = 400
def __init__(self):
super(DuplicateTags, self).__init__(
"InvalidInput",
"Duplicate tag keys found. Please note that Tag keys are case insensitive.",
)
class TagKeyTooBig(JsonRESTError):
code = 400
def __init__(self, tag, param="tags.X.member.key"):
super(TagKeyTooBig, self).__init__(
"ValidationException",
"1 validation error detected: Value '{}' at '{}' failed to satisfy "
"constraint: Member must have length less than or equal to 128".format(
tag, param
),
)
class TagValueTooBig(JsonRESTError):
code = 400
def __init__(self, tag):
super(TagValueTooBig, self).__init__(
"ValidationException",
"1 validation error detected: Value '{}' at 'tags.X.member.value' failed to satisfy "
"constraint: Member must have length less than or equal to 256".format(tag),
)
class InvalidParameterValueException(JsonRESTError):
code = 400
def __init__(self, message):
super(InvalidParameterValueException, self).__init__(
"InvalidParameterValueException", message
)
class InvalidTagCharacters(JsonRESTError):
code = 400
def __init__(self, tag, param="tags.X.member.key"):
message = "1 validation error detected: Value '{}' at '{}' failed to satisfy ".format(
tag, param
)
message += "constraint: Member must satisfy regular expression pattern: [\\\\p{L}\\\\p{Z}\\\\p{N}_.:/=+\\\\-@]+"
super(InvalidTagCharacters, self).__init__("ValidationException", message)
class TooManyTags(JsonRESTError):
code = 400
def __init__(self, tags, param="tags"):
super(TooManyTags, self).__init__(
"ValidationException",
"1 validation error detected: Value '{}' at '{}' failed to satisfy "
"constraint: Member must have length less than or equal to 50.".format(
tags, param
),
)
class InvalidResourceParameters(JsonRESTError):
code = 400
def __init__(self):
super(InvalidResourceParameters, self).__init__(
"ValidationException",
"Both Resource ID and Resource Name " "cannot be specified in the request",
)
class InvalidLimit(JsonRESTError):
code = 400
def __init__(self, value):
super(InvalidLimit, self).__init__(
"ValidationException",
"Value '{value}' at 'limit' failed to satisify constraint: Member"
" must have value less than or equal to 100".format(value=value),
)
class TooManyResourceIds(JsonRESTError):
code = 400
def __init__(self):
super(TooManyResourceIds, self).__init__(
"ValidationException",
"The specified list had more than 20 resource ID's. "
"It must have '20' or less items",
)
class ResourceNotDiscoveredException(JsonRESTError):
code = 400
def __init__(self, type, resource):
super(ResourceNotDiscoveredException, self).__init__(
"ResourceNotDiscoveredException",
"Resource {resource} of resourceType:{type} is unknown or has not been "
"discovered".format(resource=resource, type=type),
)
class TooManyResourceKeys(JsonRESTError):
code = 400
def __init__(self, bad_list):
message = (
"1 validation error detected: Value '{bad_list}' at "
"'resourceKeys' failed to satisfy constraint: "
"Member must have length less than or equal to 100".format(
bad_list=bad_list
)
)
# For PY2:
message = str(message)
super(TooManyResourceKeys, self).__init__("ValidationException", message)
| 31.878049
| 123
| 0.649239
|
4a0dc24b006f534a42a92acd54490f09032fdf1e
| 2,305
|
py
|
Python
|
magenta/models/gansynth/gansynth_pad_audio.py
|
SopiMlab/magenta
|
bab297194cbf5e033cab06a74b576befcc7b4601
|
[
"Apache-2.0"
] | null | null | null |
magenta/models/gansynth/gansynth_pad_audio.py
|
SopiMlab/magenta
|
bab297194cbf5e033cab06a74b576befcc7b4601
|
[
"Apache-2.0"
] | null | null | null |
magenta/models/gansynth/gansynth_pad_audio.py
|
SopiMlab/magenta
|
bab297194cbf5e033cab06a74b576befcc7b4601
|
[
"Apache-2.0"
] | 1
|
2020-04-27T12:57:08.000Z
|
2020-04-27T12:57:08.000Z
|
import argparse
import os
import re
import sys
parser = argparse.ArgumentParser()
parser.add_argument(
"in_dir"
)
parser.add_argument(
"out_dir"
)
parser.add_argument(
"--length",
type=int,
default=64000
)
parser.add_argument(
"--sample_rate",
type=int,
default=16000
)
parser.add_argument(
"--pitch",
type=int,
default=32
)
args = parser.parse_args()
import librosa
import numpy as np
import soundfile as sf
def print_err(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
sys.stderr.flush()
def splitext_all(name):
m = re.match("^(.*?)((?:\.[^.]*)*)$", name)
return (m.group(1), m.group(2))
def main():
try:
os.makedirs(args.out_dir)
except FileExistsError:
# ok
pass
counts = {}
def traverse(in_dir_path, prefix=()):
for in_item_name in os.listdir(in_dir_path):
in_item_path = os.path.join(in_dir_path, in_item_name)
if os.path.isdir(in_item_path):
traverse(in_item_path, prefix + (in_item_name,))
continue
ext = os.path.splitext(in_item_name)[1].lower()
if ext not in [".wav", ".aif", ".aiff", ".mp3"]:
continue
print_err("/".join(prefix+(in_item_name,)))
prefix_str = "-".join(prefix) if prefix else ""
out_identifier = re.sub(r"[^a-z0-9]+", "-", prefix_str.lower())
counts[out_identifier] = counts.setdefault(out_identifier, 0) + 1
out_file_name = "{}-{}_{}.wav".format(out_identifier, counts[out_identifier], args.pitch)
out_file_path = os.path.join(args.out_dir, out_file_name)
audio, sr = librosa.load(in_item_path, sr=args.sample_rate, mono=True)
audio_len = len(audio)
print_err(" length: {} samples".format(audio_len))
if audio_len > args.length:
print_err(" will be truncated")
out_audio = np.zeros(args.length, dtype=audio.dtype)
copy_stop_i = min(args.length, audio_len)
out_audio[:copy_stop_i] = librosa.util.normalize(audio[:copy_stop_i])
# librosa.output.write_wav(out_file_path, out_audio, sr=args.sample_rate, norm=True)
sf.write(out_file_path, out_audio, args.sample_rate, subtype="PCM_16")
print_err(" -> {}".format(out_file_name))
traverse(args.in_dir)
def console_entry_point():
main()
if __name__ == '__main__':
console_entry_point()
| 23.762887
| 95
| 0.661605
|
4a0dc343a90b14dd1d0a8922ef89fdbb3e6769f4
| 32,690
|
py
|
Python
|
tests/mobly/controllers/android_device_lib/adb_test.py
|
northwhisper/mobly
|
2af367e486d8aa0e0a587d87367ea101df3030ab
|
[
"Apache-2.0"
] | null | null | null |
tests/mobly/controllers/android_device_lib/adb_test.py
|
northwhisper/mobly
|
2af367e486d8aa0e0a587d87367ea101df3030ab
|
[
"Apache-2.0"
] | null | null | null |
tests/mobly/controllers/android_device_lib/adb_test.py
|
northwhisper/mobly
|
2af367e486d8aa0e0a587d87367ea101df3030ab
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import mock
import subprocess
from collections import OrderedDict
from future.tests.base import unittest
from mobly.controllers.android_device_lib import adb
# Mock parameters for instrumentation.
MOCK_INSTRUMENTATION_PACKAGE = 'com.my.instrumentation.tests'
MOCK_INSTRUMENTATION_RUNNER = 'com.my.instrumentation.runner'
MOCK_INSTRUMENTATION_OPTIONS = OrderedDict([
('option1', 'value1'),
('option2', 'value2'),
])
# Mock android instrumentation commands.
MOCK_BASIC_INSTRUMENTATION_COMMAND = ('am instrument -r -w com.my'
'.instrumentation.tests/com.android'
'.common.support.test.runner'
'.AndroidJUnitRunner')
MOCK_RUNNER_INSTRUMENTATION_COMMAND = ('am instrument -r -w com.my'
'.instrumentation.tests/com.my'
'.instrumentation.runner')
MOCK_OPTIONS_INSTRUMENTATION_COMMAND = ('am instrument -r -w -e option1 value1'
' -e option2 value2 com.my'
'.instrumentation.tests/com.android'
'.common.support.test.runner'
'.AndroidJUnitRunner')
# Mock Shell Command
MOCK_SHELL_COMMAND = 'ls'
MOCK_COMMAND_OUTPUT = '/system/bin/ls'.encode('utf-8')
MOCK_DEFAULT_STDOUT = 'out'
MOCK_DEFAULT_STDERR = 'err'
MOCK_DEFAULT_COMMAND_OUTPUT = MOCK_DEFAULT_STDOUT.encode('utf-8')
MOCK_ADB_SHELL_COMMAND_CHECK = 'adb shell command -v ls'
class AdbTest(unittest.TestCase):
"""Unit tests for mobly.controllers.android_device_lib.adb.
"""
def _mock_process(self, mock_psutil_process, mock_popen):
# the created proc object in adb._exec_cmd()
mock_proc = mock.Mock()
mock_popen.return_value = mock_proc
# the created process object in adb._exec_cmd()
mock_psutil_process.return_value = mock.Mock()
mock_proc.communicate = mock.Mock(
return_value=(MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8')))
mock_proc.returncode = 0
return (mock_psutil_process, mock_popen)
def _mock_execute_and_process_stdout_process(self, mock_popen):
# the created proc object in adb._execute_and_process_stdout()
mock_proc = mock.Mock()
mock_popen.return_value = mock_proc
mock_popen.return_value.stdout.readline.side_effect = ['']
mock_proc.communicate = mock.Mock(
return_value=('', MOCK_DEFAULT_STDERR.encode('utf-8')))
mock_proc.returncode = 0
return mock_popen
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_no_timeout_success(self, mock_run_command):
mock_run_command.return_value = (0,
MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8'))
out = adb.AdbProxy()._exec_cmd(
['fake_cmd'], shell=False, timeout=None, stderr=None)
self.assertEqual(MOCK_DEFAULT_STDOUT, out.decode('utf-8'))
mock_run_command.assert_called_with(
['fake_cmd'], shell=False, timeout=None)
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_error_with_serial(self, mock_run_command):
# Return 1 for retcode for error.
mock_run_command.return_value = (1,
MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8'))
mock_serial = 'ABCD1234'
with self.assertRaisesRegex(adb.AdbError,
'Error executing adb cmd .*') as context:
adb.AdbProxy(mock_serial).fake_cmd()
self.assertEqual(context.exception.serial, mock_serial)
self.assertIn(mock_serial, context.exception.cmd)
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_error_without_serial(self, mock_run_command):
# Return 1 for retcode for error.
mock_run_command.return_value = (1,
MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8'))
with self.assertRaisesRegex(adb.AdbError,
'Error executing adb cmd .*') as context:
adb.AdbProxy()._exec_cmd(
['fake_cmd'], shell=False, timeout=None, stderr=None)
self.assertFalse(context.exception.serial)
mock_run_command.assert_called_with(
['fake_cmd'], shell=False, timeout=None)
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_with_timeout_success(self, mock_run_command):
mock_run_command.return_value = (0,
MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8'))
out = adb.AdbProxy()._exec_cmd(
['fake_cmd'], shell=False, timeout=1, stderr=None)
self.assertEqual(MOCK_DEFAULT_STDOUT, out.decode('utf-8'))
mock_run_command.assert_called_with(
['fake_cmd'], shell=False, timeout=1)
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_timed_out(self, mock_run_command):
mock_run_command.side_effect = adb.psutil.TimeoutExpired('Timed out')
mock_serial = '1234Abcd'
with self.assertRaisesRegex(
adb.AdbTimeoutError, 'Timed out executing command "adb -s '
'1234Abcd fake-cmd" after 0.01s.') as context:
adb.AdbProxy(mock_serial).fake_cmd(timeout=0.01)
self.assertEqual(context.exception.serial, mock_serial)
self.assertIn(mock_serial, context.exception.cmd)
@mock.patch('mobly.utils.run_command')
def test_exec_cmd_timed_out_without_serial(self, mock_run_command):
mock_run_command.side_effect = adb.psutil.TimeoutExpired('Timed out')
with self.assertRaisesRegex(adb.AdbTimeoutError,
'Timed out executing command "adb '
'fake-cmd" after 0.01s.') as context:
adb.AdbProxy().fake_cmd(timeout=0.01)
def test_exec_cmd_with_negative_timeout_value(self):
with self.assertRaisesRegex(ValueError,
'Timeout is not a positive value: -1'):
adb.AdbProxy()._exec_cmd(
['fake_cmd'], shell=False, timeout=-1, stderr=None)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_reads_stdout(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.stdout.readline.side_effect = ['1', '2', '']
mock_handler = mock.MagicMock()
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock_handler)
self.assertEqual(mock_handler.call_count, 2)
mock_handler.assert_any_call('1')
mock_handler.assert_any_call('2')
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_reads_unexpected_stdout(
self, mock_popen):
unexpected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8')
self._mock_execute_and_process_stdout_process(mock_popen)
mock_handler = mock.MagicMock()
mock_popen.return_value.communicate = mock.Mock(
return_value=(unexpected_stdout, MOCK_DEFAULT_STDERR.encode(
'utf-8')))
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock_handler)
self.assertEqual(mock_handler.call_count, 1)
mock_handler.assert_called_with(unexpected_stdout)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('logging.debug')
def test_execute_and_process_stdout_logs_cmd(self, mock_debug_logger,
mock_popen):
raw_expected_stdout = ''
expected_stdout = '[elided, processed via handler]'
expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8')
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.communicate = mock.Mock(
return_value=(raw_expected_stdout, expected_stderr))
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock.MagicMock())
mock_debug_logger.assert_called_with(
'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd',
expected_stdout, expected_stderr, 0)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('logging.debug')
def test_execute_and_process_stdout_logs_cmd_with_unexpected_stdout(
self, mock_debug_logger, mock_popen):
raw_expected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8')
expected_stdout = '[unexpected stdout] %s' % raw_expected_stdout
expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8')
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.communicate = mock.Mock(
return_value=(raw_expected_stdout, expected_stderr))
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock.MagicMock())
mock_debug_logger.assert_called_with(
'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd',
expected_stdout, expected_stderr, 0)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_despite_cmd_exits(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.poll.side_effect = [None, 0]
mock_popen.return_value.stdout.readline.side_effect = [
'1', '2', '3', ''
]
mock_handler = mock.MagicMock()
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock_handler)
self.assertEqual(mock_handler.call_count, 3)
mock_handler.assert_any_call('1')
mock_handler.assert_any_call('2')
mock_handler.assert_any_call('3')
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_when_cmd_eof(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.stdout.readline.side_effect = [
'1', '2', '3', ''
]
mock_handler = mock.MagicMock()
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock_handler)
self.assertEqual(mock_handler.call_count, 3)
mock_handler.assert_any_call('1')
mock_handler.assert_any_call('2')
mock_handler.assert_any_call('3')
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_returns_stderr(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock.MagicMock())
self.assertEqual(MOCK_DEFAULT_STDERR, err.decode('utf-8'))
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_raises_adb_error(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.returncode = 1
with self.assertRaisesRegex(adb.AdbError,
'Error executing adb cmd .*'):
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock.MagicMock())
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_when_handler_crash(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
mock_popen.return_value.stdout.readline.side_effect = [
'1', '2', '3', ''
]
mock_handler = mock.MagicMock()
mock_handler.side_effect = ['', TypeError('fake crash'), '', '']
with self.assertRaisesRegex(TypeError, 'fake crash'):
err = adb.AdbProxy()._execute_and_process_stdout(
['fake_cmd'], shell=False, handler=mock_handler)
mock_popen.return_value.communicate.assert_called_once_with()
def test_construct_adb_cmd(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', 'arg1', shell=False)
self.assertEqual(adb_cmd, ['adb', 'shell', 'arg1'])
def test_construct_adb_cmd_with_one_command(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell ls /asdafsfd/asdf-asfd/asa', [], shell=False)
self.assertEqual(adb_cmd, ['adb', 'shell ls /asdafsfd/asdf-asfd/asa'])
def test_construct_adb_cmd_with_one_arg_command(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', 'ls /asdafsfd/asdf-asfd/asa', shell=False)
self.assertEqual(adb_cmd,
['adb', 'shell', 'ls /asdafsfd/asdf-asfd/asa'])
def test_construct_adb_cmd_with_one_arg_command_list(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['ls /asdafsfd/asdf-asfd/asa'], shell=False)
self.assertEqual(adb_cmd,
['adb', 'shell', 'ls /asdafsfd/asdf-asfd/asa'])
def test_construct_adb_cmd_with_special_characters(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['a b', '"blah"', r'\/\/'], shell=False)
self.assertEqual(adb_cmd, ['adb', 'shell', 'a b', '"blah"', r"\/\/"])
def test_construct_adb_cmd_with_serial(self):
adb_cmd = adb.AdbProxy('12345')._construct_adb_cmd(
'shell', 'arg1', shell=False)
self.assertEqual(adb_cmd, ['adb', '-s', '12345', 'shell', 'arg1'])
def test_construct_adb_cmd_with_list(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['arg1', 'arg2'], shell=False)
self.assertEqual(adb_cmd, ['adb', 'shell', 'arg1', 'arg2'])
def test_construct_adb_cmd_with_serial_with_list(self):
adb_cmd = adb.AdbProxy('12345')._construct_adb_cmd(
'shell', ['arg1', 'arg2'], shell=False)
self.assertEqual(adb_cmd,
['adb', '-s', '12345', 'shell', 'arg1', 'arg2'])
def test_construct_adb_cmd_with_shell_true(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', 'arg1 arg2', shell=True)
self.assertEqual(adb_cmd, '"adb" shell arg1 arg2')
def test_construct_adb_cmd_with_shell_true_with_one_command(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell ls /asdafsfd/asdf-asfd/asa', [], shell=True)
self.assertEqual(adb_cmd, '"adb" shell ls /asdafsfd/asdf-asfd/asa ')
def test_construct_adb_cmd_with_shell_true_with_one_arg_command(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', 'ls /asdafsfd/asdf-asfd/asa', shell=True)
self.assertEqual(adb_cmd, '"adb" shell ls /asdafsfd/asdf-asfd/asa')
def test_construct_adb_cmd_with_shell_true_with_one_arg_command_list(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['ls /asdafsfd/asdf-asfd/asa'], shell=True)
self.assertEqual(adb_cmd, '"adb" shell \'ls /asdafsfd/asdf-asfd/asa\'')
def test_construct_adb_cmd_with_shell_true_with_auto_quotes(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['a b', '"blah"', r'\/\/'], shell=True)
self.assertEqual(adb_cmd, '"adb" shell \'a b\' \'"blah"\' \'\\/\\/\'')
def test_construct_adb_cmd_with_shell_true_with_serial(self):
adb_cmd = adb.AdbProxy('12345')._construct_adb_cmd(
'shell', 'arg1 arg2', shell=True)
self.assertEqual(adb_cmd, '"adb" -s "12345" shell arg1 arg2')
def test_construct_adb_cmd_with_shell_true_with_list(self):
adb_cmd = adb.AdbProxy()._construct_adb_cmd(
'shell', ['arg1', 'arg2'], shell=True)
self.assertEqual(adb_cmd, '"adb" shell arg1 arg2')
def test_construct_adb_cmd_with_shell_true_with_serial_with_list(self):
adb_cmd = adb.AdbProxy('12345')._construct_adb_cmd(
'shell', ['arg1', 'arg2'], shell=True)
self.assertEqual(adb_cmd, '"adb" -s "12345" shell arg1 arg2')
def test_exec_adb_cmd(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
adb.AdbProxy().shell(['arg1', 'arg2'])
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', 'arg1', 'arg2'],
shell=False,
timeout=None,
stderr=None)
def test_exec_adb_cmd_with_shell_true(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
adb.AdbProxy().shell('arg1 arg2', shell=True)
mock_exec_cmd.assert_called_once_with(
'"adb" shell arg1 arg2', shell=True, timeout=None, stderr=None)
def test_exec_adb_cmd_formats_command(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
with mock.patch.object(
adb.AdbProxy,
'_construct_adb_cmd') as mock_construct_adb_cmd:
mock_adb_cmd = mock.MagicMock()
mock_adb_args = mock.MagicMock()
mock_construct_adb_cmd.return_value = mock_adb_cmd
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
adb.AdbProxy().shell(mock_adb_args)
mock_construct_adb_cmd.assert_called_once_with(
'shell', mock_adb_args, shell=False)
mock_exec_cmd.assert_called_once_with(
mock_adb_cmd, shell=False, timeout=None, stderr=None)
def test_exec_adb_cmd_formats_command_with_shell_true(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
with mock.patch.object(
adb.AdbProxy,
'_construct_adb_cmd') as mock_construct_adb_cmd:
mock_adb_cmd = mock.MagicMock()
mock_adb_args = mock.MagicMock()
mock_construct_adb_cmd.return_value = mock_adb_cmd
adb.AdbProxy().shell(mock_adb_args, shell=True)
mock_construct_adb_cmd.assert_called_once_with(
'shell', mock_adb_args, shell=True)
mock_exec_cmd.assert_called_once_with(
mock_adb_cmd, shell=True, timeout=None, stderr=None)
def test_execute_adb_and_process_stdout_formats_command(self):
with mock.patch.object(adb.AdbProxy, '_execute_and_process_stdout'
) as mock_execute_and_process_stdout:
with mock.patch.object(
adb.AdbProxy,
'_construct_adb_cmd') as mock_construct_adb_cmd:
mock_adb_cmd = mock.MagicMock()
mock_adb_args = mock.MagicMock()
mock_handler = mock.MagicMock()
mock_construct_adb_cmd.return_value = mock_adb_cmd
adb.AdbProxy()._execute_adb_and_process_stdout(
'shell', mock_adb_args, shell=False, handler=mock_handler)
mock_construct_adb_cmd.assert_called_once_with(
'shell', mock_adb_args, shell=False)
mock_execute_and_process_stdout.assert_called_once_with(
mock_adb_cmd, shell=False, handler=mock_handler)
@mock.patch('mobly.utils.run_command')
def test_exec_adb_cmd_with_stderr_pipe(self, mock_run_command):
mock_run_command.return_value = (0,
MOCK_DEFAULT_STDOUT.encode('utf-8'),
MOCK_DEFAULT_STDERR.encode('utf-8'))
stderr_redirect = io.BytesIO()
out = adb.AdbProxy().shell(
'arg1 arg2', shell=True, stderr=stderr_redirect)
self.assertEqual(MOCK_DEFAULT_STDOUT, out.decode('utf-8'))
self.assertEqual(MOCK_DEFAULT_STDERR,
stderr_redirect.getvalue().decode('utf-8'))
def test_getprop(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = b'blah'
self.assertEqual(adb.AdbProxy().getprop('haha'), 'blah')
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', 'getprop', 'haha'],
shell=False,
stderr=None,
timeout=adb.DEFAULT_GETPROP_TIMEOUT_SEC)
def test__parse_getprop_output_special_values(self):
mock_adb_output = (
b'[selinux.restorecon_recursive]: [/data/misc_ce/10]\n'
b'[selinux.abc]: [key: value]\n' # "key: value" as value
b'[persist.sys.boot.reason.history]: [reboot,adb,1558549857\n'
b'reboot,factory_reset,1558483886\n' # multi-line value
b'reboot,1558483823]\n'
b'[persist.something]: [haha\n'
b']\n'
b'[[wrapped.key]]: [[wrapped value]]\n'
b'[persist.byte]: [J\xaa\x8bb\xab\x9dP\x0f]\n' # non-decodable
)
parsed_props = adb.AdbProxy()._parse_getprop_output(mock_adb_output)
expected_output = {
'persist.sys.boot.reason.history':
('reboot,adb,1558549857\nreboot,factory_reset,1558483886\n'
'reboot,1558483823'),
'selinux.abc':
'key: value',
'persist.something':
'haha\n',
'selinux.restorecon_recursive':
'/data/misc_ce/10',
'[wrapped.key]':
'[wrapped value]',
'persist.byte':
'JbP\x0f',
}
self.assertEqual(parsed_props, expected_output)
def test__parse_getprop_output_malformat_output(self):
mock_adb_output = (
b'[selinux.restorecon_recursive][/data/misc_ce/10]\n' # Malformat
b'[persist.sys.boot.reason]: [reboot,adb,1558549857]\n'
b'[persist.something]: [haha]\n')
parsed_props = adb.AdbProxy()._parse_getprop_output(mock_adb_output)
expected_output = {
'persist.sys.boot.reason': 'reboot,adb,1558549857',
'persist.something': 'haha'
}
self.assertEqual(parsed_props, expected_output)
def test__parse_getprop_output_special_line_separator(self):
mock_adb_output = (
b'[selinux.restorecon_recursive][/data/misc_ce/10]\r\n' # Malformat
b'[persist.sys.boot.reason]: [reboot,adb,1558549857]\r\n'
b'[persist.something]: [haha]\r\n')
parsed_props = adb.AdbProxy()._parse_getprop_output(mock_adb_output)
expected_output = {
'persist.sys.boot.reason': 'reboot,adb,1558549857',
'persist.something': 'haha'
}
self.assertEqual(parsed_props, expected_output)
@mock.patch('time.sleep', return_value=mock.MagicMock())
def test_getprops(self, mock_sleep):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = (
b'\n[sendbug.preferred.domain]: [google.com]\n'
b'[sys.uidcpupower]: []\n'
b'[sys.wifitracing.started]: [1]\n'
b'[telephony.lteOnCdmaDevice]: [1]\n\n')
actual_output = adb.AdbProxy().getprops([
'sys.wifitracing.started', # "numeric" value
'sys.uidcpupower', # empty value
'sendbug.preferred.domain', # string value
'nonExistentProp'
])
self.assertEqual(actual_output, {
'sys.wifitracing.started': '1',
'sys.uidcpupower': '',
'sendbug.preferred.domain': 'google.com'
})
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', 'getprop'],
shell=False,
stderr=None,
timeout=adb.DEFAULT_GETPROP_TIMEOUT_SEC)
mock_sleep.assert_not_called()
@mock.patch('time.sleep', return_value=mock.MagicMock())
def test_getprops_when_empty_string_randomly_returned(self, mock_sleep):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.side_effect = [
b'', (b'\n[ro.build.id]: [AB42]\n'
b'[ro.build.type]: [userdebug]\n\n')
]
actual_output = adb.AdbProxy().getprops(['ro.build.id'])
self.assertEqual(actual_output, {
'ro.build.id': 'AB42',
})
self.assertEqual(mock_exec_cmd.call_count, 2)
mock_exec_cmd.assert_called_with(
['adb', 'shell', 'getprop'],
shell=False,
stderr=None,
timeout=adb.DEFAULT_GETPROP_TIMEOUT_SEC)
self.assertEqual(mock_sleep.call_count, 1)
mock_sleep.assert_called_with(1)
@mock.patch('time.sleep', return_value=mock.MagicMock())
def test_getprops_when_empty_string_always_returned(self, mock_sleep):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = b''
actual_output = adb.AdbProxy().getprops(['ro.build.id'])
self.assertEqual(actual_output, {})
self.assertEqual(mock_exec_cmd.call_count, 3)
mock_exec_cmd.assert_called_with(
['adb', 'shell', 'getprop'],
shell=False,
stderr=None,
timeout=adb.DEFAULT_GETPROP_TIMEOUT_SEC)
self.assertEqual(mock_sleep.call_count, 2)
mock_sleep.assert_called_with(1)
def test_forward(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
adb.AdbProxy().forward(MOCK_SHELL_COMMAND)
def test_instrument_without_parameters(self):
"""Verifies the AndroidDevice object's instrument command is correct in
the basic case.
"""
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
adb.AdbProxy().instrument(MOCK_INSTRUMENTATION_PACKAGE)
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', MOCK_BASIC_INSTRUMENTATION_COMMAND],
shell=False,
timeout=None,
stderr=None)
def test_instrument_with_runner(self):
"""Verifies the AndroidDevice object's instrument command is correct
with a runner specified.
"""
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
adb.AdbProxy().instrument(
MOCK_INSTRUMENTATION_PACKAGE,
runner=MOCK_INSTRUMENTATION_RUNNER)
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', MOCK_RUNNER_INSTRUMENTATION_COMMAND],
shell=False,
timeout=None,
stderr=None)
def test_instrument_with_options(self):
"""Verifies the AndroidDevice object's instrument command is correct
with options.
"""
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
adb.AdbProxy().instrument(
MOCK_INSTRUMENTATION_PACKAGE,
options=MOCK_INSTRUMENTATION_OPTIONS)
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', MOCK_OPTIONS_INSTRUMENTATION_COMMAND],
shell=False,
timeout=None,
stderr=None)
def test_instrument_with_handler(self):
"""Verifies the AndroidDevice object's instrument command is correct
with a handler passed in.
"""
def mock_handler(raw_line):
pass
with mock.patch.object(adb.AdbProxy, '_execute_and_process_stdout'
) as mock_execute_and_process_stdout:
adb.AdbProxy().instrument(
MOCK_INSTRUMENTATION_PACKAGE, handler=mock_handler)
mock_execute_and_process_stdout.assert_called_once_with(
['adb', 'shell', MOCK_BASIC_INSTRUMENTATION_COMMAND],
shell=False,
handler=mock_handler)
def test_instrument_with_handler_with_runner(self):
"""Verifies the AndroidDevice object's instrument command is correct
with a handler passed in and a runner specified.
"""
def mock_handler(raw_line):
pass
with mock.patch.object(adb.AdbProxy, '_execute_and_process_stdout'
) as mock_execute_and_process_stdout:
adb.AdbProxy().instrument(
MOCK_INSTRUMENTATION_PACKAGE,
runner=MOCK_INSTRUMENTATION_RUNNER,
handler=mock_handler)
mock_execute_and_process_stdout.assert_called_once_with(
['adb', 'shell', MOCK_RUNNER_INSTRUMENTATION_COMMAND],
shell=False,
handler=mock_handler)
def test_instrument_with_handler_with_options(self):
"""Verifies the AndroidDevice object's instrument command is correct
with a handler passed in and options.
"""
def mock_handler(raw_line):
pass
with mock.patch.object(adb.AdbProxy, '_execute_and_process_stdout'
) as mock_execute_and_process_stdout:
adb.AdbProxy().instrument(
MOCK_INSTRUMENTATION_PACKAGE,
options=MOCK_INSTRUMENTATION_OPTIONS,
handler=mock_handler)
mock_execute_and_process_stdout.assert_called_once_with(
['adb', 'shell', MOCK_OPTIONS_INSTRUMENTATION_COMMAND],
shell=False,
handler=mock_handler)
def test_has_shell_command_called_correctly(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
adb.AdbProxy().has_shell_command(MOCK_SHELL_COMMAND)
mock_exec_cmd.assert_called_once_with(
['adb', 'shell', 'command', '-v', MOCK_SHELL_COMMAND],
shell=False,
timeout=None,
stderr=None)
def test_has_shell_command_with_existing_command(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_COMMAND_OUTPUT
self.assertTrue(
adb.AdbProxy().has_shell_command(MOCK_SHELL_COMMAND))
def test_has_shell_command_with_missing_command_on_older_devices(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
mock_exec_cmd.side_effect = adb.AdbError(
MOCK_ADB_SHELL_COMMAND_CHECK, '', '', 0)
self.assertFalse(
adb.AdbProxy().has_shell_command(MOCK_SHELL_COMMAND))
def test_has_shell_command_with_missing_command_on_newer_devices(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT
mock_exec_cmd.side_effect = adb.AdbError(
MOCK_ADB_SHELL_COMMAND_CHECK, '', '', 1)
self.assertFalse(
adb.AdbProxy().has_shell_command(MOCK_SHELL_COMMAND))
if __name__ == '__main__':
unittest.main()
| 46.303116
| 80
| 0.631416
|
4a0dc4936d2df4fb989fe9f24a8345833a0d9389
| 677
|
py
|
Python
|
setup.py
|
okawo80085/rubypass
|
3cc69045c1bf401bb9cc38522eaea19cdd2e5034
|
[
"MIT"
] | null | null | null |
setup.py
|
okawo80085/rubypass
|
3cc69045c1bf401bb9cc38522eaea19cdd2e5034
|
[
"MIT"
] | null | null | null |
setup.py
|
okawo80085/rubypass
|
3cc69045c1bf401bb9cc38522eaea19cdd2e5034
|
[
"MIT"
] | 1
|
2020-05-03T17:42:55.000Z
|
2020-05-03T17:42:55.000Z
|
import setuptools
with open('README.md') as f:
ld = f.read()
setuptools.setup(
name="rubypass",
version="0.2.5.1",
description="A package made to extract video urls from 2 russian websites",
long_description=ld,
long_description_content_type="text/markdown",
author="okawo",
author_email="okawo.198@gmail.com",
url="https://github.com/okawo80085/rubypass",
packages=setuptools.find_packages(),
install_requires=['selenium'],
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
py_modules=['rubypass'],
python_requires='>=3',
)
| 26.038462
| 76
| 0.713442
|
4a0dc4eb49b422eb9c6582dbd83ee11a74c218ab
| 5,413
|
py
|
Python
|
do_like_javac/tools/infer.py
|
zcai1/do-like-javac
|
3eb4a43521ae181a9b777a589e477b0c6ab7cb6e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
do_like_javac/tools/infer.py
|
zcai1/do-like-javac
|
3eb4a43521ae181a9b777a589e477b0c6ab7cb6e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
do_like_javac/tools/infer.py
|
zcai1/do-like-javac
|
3eb4a43521ae181a9b777a589e477b0c6ab7cb6e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
import os,sys
import argparse
import subprocess
from . import common
argparser = argparse.ArgumentParser(add_help=False)
infer_group = argparser.add_argument_group('inference tool arguments')
infer_group.add_argument('-s', '--solver', metavar='<solver>',
action='store',default='checkers.inference.solver.DebugSolver',
help='solver to use on constraints')
infer_group.add_argument('-afud', '--afuOutputDir', metavar='<afud>',
action='store',default='afud/',
help='Annotation File Utilities output directory')
infer_group.add_argument('-m', '--mode', metavar='<mode>',
action='store',default='INFER',
help='Modes of operation: TYPECHECK, INFER, ROUNDTRIP,ROUNDTRIP_TYPECHECK')
infer_group.add_argument('-solverArgs', '--solverArgs', metavar='<solverArgs>',
action='store',default='backEndType=maxsatbackend.MaxSat',
help='arguments for solver')
infer_group.add_argument('-cfArgs', '--cfArgs', metavar='<cfArgs>',
action='store',default='',
help='arguments for checker framework')
infer_group.add_argument('--inPlace', action='store_true',
help='Whether or not the annoations should be inserted in the original source code')
infer_group.add_argument('--crashExit', action='store_true',
help='set it then dljc will early exit if it found a round of inference crashed during the iteration.')
def run(args, javac_commands, jars):
print(os.environ)
idx = 0
for jc in javac_commands:
jaif_file = "logs/infer_result_{}.jaif".format(idx)
cmd = get_tool_command(args, jc['javac_switches']['classpath'], jc['java_files'], jaif_file)
status = common.run_cmd(cmd, args, 'infer')
if args.crashExit and not status['return_code'] == 0:
print("----- CF Inference/Typecheck crashed! Terminates DLJC. -----")
sys.exit(1)
idx += 1
def get_tool_command(args, target_classpath, java_files, jaif_file="default.jaif"):
# the dist directory of CFI.
CFI_dist = os.path.join(os.path.split(os.path.realpath(__file__))[0], "../../../", 'checker-framework-inference', 'dist')
CFI_command = ['java']
java_version = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
# Compatible with Python3. In Python 2.7, type(java_version) == str; but in Python3, type(java_version) == bytes.
# After do-like-javac updates to Python 3, this code can still work.
if isinstance(java_version, bytes):
java_version = java_version.decode("utf-8")
# java_version is a String like this:
# 'openjdk version "1.8.0_222"
# OpenJDK Runtime Environment (build 1.8.0_222-8u222-b10-1ubuntu1~19.04.1-b10)
# OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)
# '
# We need to extract the version number from this String.
# split_version_number is a list of split version numbers in String type, e.g., ["1", "8", "0_222"].
# For Java 9+, it can simply be ["9"]. So in this case we should compare the first element directly.
split_version_number = []
for each_line in java_version.splitlines():
if each_line.startswith('openjdk version') or each_line.startswith('java version'):
split_version_number = each_line.split()[2].strip('"').split(".")
break
assert len(split_version_number) >= 1, 'No openjdk version info found. java_version: {}'.format(java_version)
is_jvm8 = split_version_number[0] == "8" if len(split_version_number) == 1 else split_version_number[1] == "8"
if is_jvm8:
print('Using Java 8, runtime bcp will be added.')
CFI_command += ['-DInferenceLauncher.runtime.bcp=' + os.path.join(CFI_dist, "javac.jar")]
cp = target_classpath + \
':' + os.path.join(CFI_dist, 'checker.jar') + \
':' + os.path.join(CFI_dist, 'plume.jar') + \
':' + os.path.join(CFI_dist, 'checker-framework-inference.jar')
if 'CLASSPATH' in os.environ:
cp += ':' + os.environ['CLASSPATH']
# os env classpath must be added to targetclasspath for running CFI in
# typecheck mode
target_classpath += ':' + os.environ['CLASSPATH']
# TODO: see if this is still needed:
# env_classpath must also have a project's dependent jars
# os.environ['CLASSPATH'] = target_classpath
CFI_command += [ # '-p', # printCommands before executing
'-classpath', cp,
'checkers.inference.InferenceLauncher']
if not args.cfArgs == "":
CFI_command += [ '--cfArgs', args.cfArgs]
CFI_command += [ '--checker', args.checker,
'--solver', args.solver,
'--solverArgs', args.solverArgs,
'--mode', args.mode,
'--hacks=true',
'--targetclasspath', target_classpath,
'--logLevel=INFO',
'--jaifFile', jaif_file]
if args.inPlace:
CFI_command += ['--inPlace=true']
else:
CFI_command += ['-afud', args.afuOutputDir]
CFI_command.extend(java_files)
return CFI_command
| 48.765766
| 127
| 0.609089
|
4a0dc5ed32e2181a454c167193008346af6f6fee
| 1,704
|
py
|
Python
|
test_efficientnet_v2/test_preprocessing_layer.py
|
sebastian-sz/efficientnet-v2-keras
|
b1d76b90a2a066ac5608aacb271af8ba67a09bca
|
[
"Apache-2.0"
] | 4
|
2021-08-21T14:10:31.000Z
|
2022-03-09T03:27:18.000Z
|
test_efficientnet_v2/test_preprocessing_layer.py
|
sebastian-sz/efficientnet-v2-keras
|
b1d76b90a2a066ac5608aacb271af8ba67a09bca
|
[
"Apache-2.0"
] | 5
|
2021-08-01T12:33:33.000Z
|
2022-02-03T11:15:37.000Z
|
test_efficientnet_v2/test_preprocessing_layer.py
|
sebastian-sz/efficientnet-v2-keras
|
b1d76b90a2a066ac5608aacb271af8ba67a09bca
|
[
"Apache-2.0"
] | null | null | null |
import tensorflow as tf
from absl.testing import absltest
from efficientnet_v2 import get_preprocessing_layer
class TestPreprocessingLayer(absltest.TestCase):
rng = tf.random.Generator.from_non_deterministic_state()
def test_bx_variants_preprocessing_layer(self):
def original_preprocess(image):
mean_rgb = [0.485 * 255, 0.456 * 255, 0.406 * 255]
stddev_rgb = [0.229 * 255, 0.224 * 255, 0.225 * 255]
image -= tf.constant(mean_rgb, shape=(1, 1, 3), dtype=image.dtype)
image /= tf.constant(stddev_rgb, shape=(1, 1, 3), dtype=image.dtype)
return image
input_frame = self.rng.uniform((1, 224, 224, 3), maxval=255)
layer = get_preprocessing_layer("b0")
original_preprocessed = original_preprocess(input_frame)
layer_preprocessed = layer(input_frame)
tf.debugging.assert_near(original_preprocessed, layer_preprocessed)
def test_smlxl_variants_preprocessing_layer(self):
def original_preprocess(image):
return (image - 128.0) / 128.0
input_frame = self.rng.uniform((1, 224, 224, 3), maxval=255)
layer = get_preprocessing_layer("s")
original_preprocessed = original_preprocess(input_frame)
layer_preprocessed = layer(input_frame)
tf.debugging.assert_near(original_preprocessed, layer_preprocessed)
def test_get_preprocessing_layer_function(self):
for variant in ["b0", "b1", "b2", "b3", "s", "m", "l", "xl"]:
get_preprocessing_layer(variant)
with self.assertRaises(ValueError):
get_preprocessing_layer("non-existing-variant")
if __name__ == "__main__":
absltest.main()
| 35.5
| 80
| 0.674883
|
4a0dc5f575d54efe0fcb26733b0e16ff71774321
| 9,325
|
py
|
Python
|
orquesta/tests/unit/conducting/test_workflow_conductor_context.py
|
trstruth/orquesta
|
e6ebbbeb2c661486067e659dc7552f0a986603a6
|
[
"Apache-2.0"
] | 3
|
2020-11-17T21:29:26.000Z
|
2021-03-17T13:56:16.000Z
|
orquesta/tests/unit/conducting/test_workflow_conductor_context.py
|
trstruth/orquesta
|
e6ebbbeb2c661486067e659dc7552f0a986603a6
|
[
"Apache-2.0"
] | 5
|
2021-03-02T01:41:36.000Z
|
2022-03-08T23:31:31.000Z
|
orquesta/tests/unit/conducting/test_workflow_conductor_context.py
|
trstruth/orquesta
|
e6ebbbeb2c661486067e659dc7552f0a986603a6
|
[
"Apache-2.0"
] | 15
|
2020-08-08T16:21:40.000Z
|
2022-03-17T04:45:51.000Z
|
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from orquesta import conducting
from orquesta import exceptions as exc
from orquesta.specs import native as native_specs
from orquesta import statuses
from orquesta.tests.unit import base as test_base
class WorkflowConductorContextTest(test_base.WorkflowConductorTest):
def test_bad_app_ctx_references(self):
wf_def = """
version: 1.0
input:
- a: <% ctx().x %>
vars:
- b: <% ctx().y %>
output:
- x: <% ctx().a %>
- y: <% ctx().b %>
- z: <% ctx().z %>
tasks:
task1:
action: core.noop
"""
expected_errors = [
{
'type': 'error',
'message': (
'YaqlEvaluationException: Unable to resolve key \'x\' in '
'expression \'<% ctx().x %>\' from context.'
)
},
{
'type': 'error',
'message': (
'YaqlEvaluationException: Unable to resolve key \'y\' in '
'expression \'<% ctx().y %>\' from context.'
)
}
]
spec = native_specs.WorkflowSpec(wf_def)
# Run the workflow.
conductor = conducting.WorkflowConductor(spec)
self.assertRaises(
exc.InvalidWorkflowStatusTransition,
conductor.request_workflow_status,
statuses.RUNNING
)
# Check workflow status and result.
self.assertEqual(conductor.get_workflow_status(), statuses.FAILED)
self.assertListEqual(conductor.errors, expected_errors)
self.assertIsNone(conductor.get_workflow_output())
def test_app_ctx_references(self):
app_ctx = {
'x': 'foobar',
'y': 'fubar',
'z': 'phobar'
}
wf_def = """
version: 1.0
input:
- a: <% ctx().x %>
vars:
- b: <% ctx().y %>
output:
- x: <% ctx().a %>
- y: <% ctx().b %>
- z: <% ctx().z %>
tasks:
task1:
action: core.noop
"""
expected_output = app_ctx
expected_errors = []
spec = native_specs.WorkflowSpec(wf_def)
self.assertDictEqual(spec.inspect(app_ctx=app_ctx), {})
# Run the workflow.
conductor = conducting.WorkflowConductor(spec, context=app_ctx)
conductor.request_workflow_status(statuses.RUNNING)
self.assertEqual(conductor.get_workflow_status(), statuses.RUNNING)
self.assertListEqual(conductor.errors, expected_errors)
# Complete tasks
self.forward_task_statuses(conductor, 'task1', [statuses.RUNNING, statuses.SUCCEEDED])
# Check workflow status and output.
self.assertEqual(conductor.get_workflow_status(), statuses.SUCCEEDED)
self.assertListEqual(conductor.errors, expected_errors)
self.assertDictEqual(conductor.get_workflow_output(), expected_output)
def test_ctx_yaql_queries(self):
wf_def = """
version: 1.0
input:
- vms
- vm1: <% ctx(vms).get(vm1) %>
- vm2: <% ctx().vms.get(vm2) %>
- vm3: <% ctx(vms)[vm3] %>
- vm4: <% ctx().vms[vm4] %>
vars:
- vm1: <% ctx(vms).get(vm1) %>
- vm2: <% ctx().vms.get(vm2) %>
- vm3: <% ctx(vms)[vm3] %>
- vm4: <% ctx().vms[vm4] %>
tasks:
task1:
action: mock.create
input:
vm1: <% ctx(vms).get(vm1) %>
vm2: <% ctx().vms.get(vm2) %>
vm3: <% ctx(vms)[vm3] %>
vm4: <% ctx().vms[vm4] %>
next:
- publish:
- vm1: <% ctx(vms).get(vm1) %>
- vm2: <% ctx().vms.get(vm2) %>
- vm3: <% ctx(vms)[vm3] %>
- vm4: <% ctx().vms[vm4] %>
output:
- vm1: <% ctx(vms).get(vm1) %>
- vm2: <% ctx().vms.get(vm2) %>
- vm3: <% ctx(vms)[vm3] %>
- vm4: <% ctx().vms[vm4] %>
"""
spec = native_specs.WorkflowSpec(wf_def)
self.assertDictEqual(spec.inspect(), {})
def test_ctx_ref_private_var(self):
app_ctx = {
'__xyz': 'phobar'
}
wf_def = """
version: 1.0
vars:
- foobar: fubar
tasks:
task1:
action: core.noop
next:
- publish:
- task1: <% ctx("__xyz") %>
output:
- data: <% ctx("__xyz") %>
"""
expected_inspection_errors = {
'context': [
{
'type': 'yaql',
'expression': '<% ctx("__xyz") %>',
'spec_path': 'output[0]',
'schema_path': 'properties.output',
'message': (
'Variable "__xyz" that is prefixed with double underscores '
'is considered a private variable and cannot be referenced.'
)
},
{
'type': 'yaql',
'expression': '<% ctx("__xyz") %>',
'spec_path': 'tasks.task1.next[0].publish[0]',
'schema_path': (
'properties.tasks.patternProperties.^\\w+$.'
'properties.next.items.properties.publish'
),
'message': (
'Variable "__xyz" that is prefixed with double underscores '
'is considered a private variable and cannot be referenced.'
)
}
]
}
expected_conducting_errors = [
{
'type': 'error',
'route': 0,
'task_id': 'task1',
'task_transition_id': 'continue__t0',
'message': (
'YaqlEvaluationException: Unable to evaluate expression '
'\'<% ctx("__xyz") %>\'. VariableInaccessibleError: The '
'variable "__xyz" is for internal use and inaccessible.'
)
},
{
'type': 'error',
'message': (
'YaqlEvaluationException: Unable to evaluate expression '
'\'<% ctx("__xyz") %>\'. VariableInaccessibleError: The '
'variable "__xyz" is for internal use and inaccessible.'
)
}
]
spec = native_specs.WorkflowSpec(wf_def)
self.assertDictEqual(spec.inspect(app_ctx=app_ctx), expected_inspection_errors)
# Run the workflow.
conductor = conducting.WorkflowConductor(spec, context=app_ctx)
conductor.request_workflow_status(statuses.RUNNING)
self.assertEqual(conductor.get_workflow_status(), statuses.RUNNING)
# Complete tasks
self.forward_task_statuses(conductor, 'task1', [statuses.RUNNING, statuses.SUCCEEDED])
# Check workflow status and output.
self.assertEqual(conductor.get_workflow_status(), statuses.FAILED)
self.assertListEqual(conductor.errors, expected_conducting_errors)
self.assertIsNone(conductor.get_workflow_output())
def test_ctx_get_all(self):
app_ctx = {
'__xyz': 'phobar'
}
wf_def = """
version: 1.0
vars:
- foobar: fubar
tasks:
task1:
action: core.noop
next:
- publish:
- task1: <% ctx() %>
output:
- data: <% ctx() %>
"""
# Ensure the private variables prefixed with double underscores are not included.
expected_output = {'data': {'foobar': 'fubar', 'task1': {'foobar': 'fubar'}}}
expected_errors = []
spec = native_specs.WorkflowSpec(wf_def)
self.assertDictEqual(spec.inspect(app_ctx=app_ctx), {})
# Run the workflow.
conductor = conducting.WorkflowConductor(spec, context=app_ctx)
conductor.request_workflow_status(statuses.RUNNING)
self.assertEqual(conductor.get_workflow_status(), statuses.RUNNING)
# Complete tasks
self.forward_task_statuses(conductor, 'task1', [statuses.RUNNING, statuses.SUCCEEDED])
# Check workflow status and output.
self.assertEqual(conductor.get_workflow_status(), statuses.SUCCEEDED)
self.assertListEqual(conductor.errors, expected_errors)
self.assertDictEqual(conductor.get_workflow_output(), expected_output)
| 31.717687
| 94
| 0.518284
|
4a0dc68ab3ec4cb58bf501710bf94eb349bfe1a5
| 5,719
|
py
|
Python
|
networks.py
|
kamildar/cyclegan
|
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
|
[
"MIT"
] | 1
|
2019-01-02T07:43:28.000Z
|
2019-01-02T07:43:28.000Z
|
networks.py
|
kamildar/cyclegan
|
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
|
[
"MIT"
] | null | null | null |
networks.py
|
kamildar/cyclegan
|
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
|
[
"MIT"
] | null | null | null |
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
# dim = None
# dropout = None
# norm_lay = None
activation = nn.LeakyReLU(0.1)
bias = False
# for square images
def conv_size(input_size, kernel_size, stride, padding):
out = int((input_size + 2 * padding - kernel_size) / stride) + 1
return out
# base resnet block
# conv > ?dropout > conv
# possible params
# kernel_size, padding, bias, reflection type
class ResnetBlock(nn.Module):
def __init__(self, dim, norm_lay, dropout):
super().__init__()
self.conv_seq = self.conv_block(dim, norm_lay, dropout)
def conv_block(self, dim, norm_lay, dropout):
conv_block = []
conv_block += [
nn.ReflectionPad2d(1),
nn.Conv2d(dim, dim, kernel_size=3, padding=0, bias=bias),
norm_lay(dim),
activation
]
if dropout is not None:
conv_block += [nn.Dropout(dropout)]
conv_block += [
nn.ReflectionPad2d(1),
nn.Conv2d(dim, dim, kernel_size=3, padding=0, bias=bias),
norm_lay(dim)
]
return nn.Sequential(*conv_block)
def forward(self, input):
output = input + self.conv_seq(input)
return output
# generative block via resnet
# conv > downconv* > resnet block* > transp conv* > conv
# possible params
# first/last conv: ksize, pad, stride
# down/trans conv: number, conv params
class ResnetGenerator(nn.Module):
def __init__(self,
input_nc,
output_nc,
gen_filters,
norm_lay,
dropout,
n_blocks):
super().__init__()
self._input_nc = input_nc
self._output_nc = output_nc
self._gen_filters = gen_filters
resnet_seq = [
nn.ReflectionPad2d(3),
nn.Conv2d(input_nc, gen_filters,
kernel_size=7, padding=0, bias=bias),
norm_lay(gen_filters),
activation
]
n_downsampling = 2
for i in range(n_downsampling):
power = 2 ** i
resnet_seq += [
nn.Conv2d(
gen_filters * power,
gen_filters * power * 2,
kernel_size=3,
stride=2,
padding=1,
bias=bias
),
norm_lay(gen_filters * power * 2),
activation
]
power = 2 ** n_downsampling
for i in range(n_blocks):
resnet_seq += [
ResnetBlock(
gen_filters * power,
norm_lay,
dropout)
]
for i in range(n_downsampling):
power = 2 ** (n_downsampling - i)
resnet_seq += [
nn.ConvTranspose2d(
gen_filters * power,
int(gen_filters * power / 2),
kernel_size=3,
stride=2,
padding=1,
output_padding=1
),
norm_lay(int(gen_filters * power / 2)),
activation
]
resnet_seq += [nn.ReflectionPad2d(3)]
resnet_seq += [nn.Conv2d(gen_filters, output_nc,
kernel_size=7,
padding=0,
bias=bias)]
resnet_seq += [nn.Tanh()]
self._resnet_seq = nn.Sequential(*resnet_seq)
def forward(self, input):
output = self._resnet_seq(input)
return output
class Discriminator(nn.Module):
def __init__(self,
input_nc,
discr_filters,
max_power,
n_layers,
norm_lay,
start_size,
out_linear=10):
super().__init__()
self._input_nc = input_nc
size = start_size
ksize = 4
strd = 1
pad = 1
discr_body = [
nn.Conv2d(input_nc, discr_filters,
kernel_size=ksize,
stride=strd,
padding=pad),
norm_lay(discr_filters),
activation
]
filters = np.linspace(discr_filters,
discr_filters * max_power,
num=n_layers + 1,
dtype=int).tolist()
prev_filter = discr_filters
for interm_filter in filters[1:]:
discr_body += [
nn.Conv2d(
prev_filter,
interm_filter,
kernel_size=ksize,
stride=strd,
padding=pad
),
norm_lay(interm_filter),
activation
]
prev_filter = interm_filter
discr_body += [
nn.Conv2d(
prev_filter,
1,
kernel_size=ksize,
stride=strd,
padding=pad
)
]
for i in range(n_layers + 2):
size = conv_size(size, ksize, strd, pad)
self._linear_size = size * size
discr_head = [nn.Linear(size * size, out_linear)]
if out_linear != 1:
discr_head += [nn.Linear(out_linear, 1)]
self.body = nn.Sequential(*discr_body)
self.head = nn.Sequential(*discr_head)
def forward(self, input):
body_out = self.body(input)
output = self.head(body_out.view(-1, self._linear_size))
return F.sigmoid(output)
| 27.233333
| 69
| 0.483651
|
4a0dc6eff055b40e472ef4ebcd68ca873228d8bb
| 5,510
|
py
|
Python
|
setup.py
|
imaginary-unit/opendr
|
c9d7ed9f2352850b5570cacf452196224d9b2f7d
|
[
"MIT"
] | null | null | null |
setup.py
|
imaginary-unit/opendr
|
c9d7ed9f2352850b5570cacf452196224d9b2f7d
|
[
"MIT"
] | null | null | null |
setup.py
|
imaginary-unit/opendr
|
c9d7ed9f2352850b5570cacf452196224d9b2f7d
|
[
"MIT"
] | null | null | null |
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
from setuptools import setup
from distutils.extension import Extension
import numpy
import platform
import os
from version import version
try:
from Cython.Build import cythonize
have_cython = True
except:
cythonize = lambda x : x
have_cython = False
# setuptools DWIM monkey-patch madness
# http://mail.python.org/pipermail/distutils-sig/2007-September/thread.html#8204
# import sys
# if 'setuptools.extension' in sys.modules:
# m = sys.modules['setuptools.extension']
# m.Extension.__dict__ = m._Extension.__dict__
context_dir = os.path.join(os.path.dirname(__file__), 'contexts')
def download_osmesa():
import os, re, zipfile
from utils import wget
mesa_dir = os.path.join(context_dir,'OSMesa')
if not os.path.exists(mesa_dir):
sysinfo = platform.uname()
osmesa_fname = 'OSMesa.%s.%s.zip' % (sysinfo[0], sysinfo[-2])
zip_fname = os.path.join(context_dir, osmesa_fname)
if not os.path.exists(zip_fname):
print("Downloading %s" % osmesa_fname)
# MPI url: http://files.is.tue.mpg.de/mloper/opendr/osmesa/%s
# BL url: https://s3.amazonaws.com/bodylabs-assets/public/osmesa/%s
wget('http://files.is.tue.mpg.de/mloper/opendr/osmesa/%s' % (osmesa_fname,), dest_fname=zip_fname)
assert(os.path.exists(zip_fname))
with zipfile.ZipFile(zip_fname, 'r') as z:
for f in [x for x in z.namelist() if re.search('[ah]$', x)]:
z.extract(f, path=context_dir)
assert(os.path.exists(mesa_dir))
def autogen_opengl_sources():
import os
sources = [ os.path.join(context_dir, x) for x in ['_constants.py', '_functions.pyx'] ]
if not all([ os.path.exists(x) for x in sources ]):
print("Autogenerating opengl sources")
from contexts import autogen
autogen.main()
for x in sources:
assert(os.path.exists(x))
def setup_opendr(ext_modules):
ext_modules=cythonize(ext_modules)
try: # hack
ext_modules[0]._convert_pyx_sources_to_lang = lambda : None
except: pass
setup(name='opendr',
version=version,
packages = ['opendr', 'opendr.contexts', 'opendr.test_dr'],
package_dir = {'opendr': '.'},
author = 'Matthew Loper',
author_email = 'matt.loper@gmail.com',
url = 'http://github.com/mattloper/opendr',
ext_package='opendr',
package_data={'opendr': ['test_dr/nasa*']},
install_requires=['Cython', 'chumpy >= 0.58', 'matplotlib'],
description='opendr',
ext_modules=ext_modules,
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Science/Research',
'Topic :: Multimedia :: Graphics :: 3D Rendering',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux'
],
)
def mesa_ext():
libraries = ['OSMesa', 'GL', 'GLU']
extra_args = []
if platform.system()=='Darwin': # deprecated, probably don't need osmesa libs on mac
libraries.append('talloc')
extra_args.append('-Qunused-arguments')
else:
extra_args.append('-lstdc++')
return Extension("contexts.ctx_mesa", ['contexts/ctx_mesa.pyx'] if have_cython else ['contexts/ctx_mesa.c'],
language="c",
library_dirs=['contexts/OSMesa/lib'],
depends=['contexts/_constants.py'],
define_macros = [('__OSMESA__', 1)],
include_dirs=['.', numpy.get_include(), 'contexts/OSMesa/include'],
libraries=libraries,
extra_compile_args=extra_args,
extra_link_args=extra_args)
def mac_ext():
return Extension("contexts.ctx_mac", ['contexts/ctx_mac.pyx', 'contexts/ctx_mac_internal.c'] if have_cython else ['contexts/ctx_mac.c', 'contexts/ctx_mac_internal.c'],
language="c",
depends=['contexts/_constants.py', 'contexts/ctx_mac_internal.h'],
include_dirs=['.', numpy.get_include()],
extra_compile_args=['-Qunused-arguments'],
extra_link_args=['-Qunused-arguments'])
def main():
from contexts.fix_warnings import fix_warnings
fix_warnings()
# Get osmesa and some processed files ready
download_osmesa()
autogen_opengl_sources()
# Get context extensions ready & build
if platform.system() == 'Darwin':
setup_opendr([mac_ext()])
else:
setup_opendr([mesa_ext()])
if __name__ == '__main__':
main()
| 36.013072
| 171
| 0.601452
|
4a0dc792848919a9377d7217857e5048aade4481
| 13,509
|
py
|
Python
|
experimental/python/gui/object_polyline.py
|
x2nie/Embroidermodder
|
9db132d43c820b55056eb2b40bd3c86372c3dbd3
|
[
"Zlib"
] | null | null | null |
experimental/python/gui/object_polyline.py
|
x2nie/Embroidermodder
|
9db132d43c820b55056eb2b40bd3c86372c3dbd3
|
[
"Zlib"
] | null | null | null |
experimental/python/gui/object_polyline.py
|
x2nie/Embroidermodder
|
9db132d43c820b55056eb2b40bd3c86372c3dbd3
|
[
"Zlib"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
===================================
|module_summary| object_polyline.py
===================================
TOWRITE
Classes summary:
================
============================ ============================
:class:`~PolylineObject` TOWRITE
============================ ============================
---------------------------------------------------------
|
"""
#-Imports.---------------------------------------------------------------------
#--PySide/PyQt Imports.
if PYSIDE:
## from PySide import QtCore, QtGui
# or... Improve performace with less dots...
from PySide.QtCore import qDebug, Qt, QLineF, QPointF, QObject
from PySide.QtGui import QGraphicsItem, QPainter, QPainterPath, QStyle, QMessageBox, QTransform
elif PYQT4:
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
## from PyQt4 import QtCore, QtGui
# or... Improve performace with less dots...
from PyQt4.QtCore import qDebug, Qt, QLineF, QPointF, QObject
from PyQt4.QtGui import QGraphicsItem, QPainter, QPainterPath, QStyle, QMessageBox, QTransform
#--Local Imports.
from hacks import overloaded, signature
from object_base import BaseObject
from object_data import (OBJ_TYPE, OBJ_TYPE_POLYLINE, OBJ_NAME, ENABLE_LWT,
ENABLE_REAL, OBJ_RUBBER_POLYLINE, OBJ_RUBBER_GRIP, OBJ_RUBBER_OFF,
OBJ_NAME_POLYLINE)
# C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++
#include "object-polyline.h"
#include "object-data.h"
#include <QPainter>
#include <QStyleOption>
#include <QGraphicsScene>
#include <QMessageBox>
# C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++
class PolylineObject(BaseObject):
"""
Subclass of `BaseObject`_
TOWRITE
"""
Type = OBJ_TYPE_POLYLINE
def __init__(self, x, y, p, rgb, parent=None):
#OVERLOADED IMPL?# PolylineObject::PolylineObject(PolylineObject* obj, QGraphicsItem* parent) : BaseObject(parent)
"""
Default class constructor.
:param `x`: TOWRITE
:type `x`: qreal
:param `y`: TOWRITE
:type `y`: qreal
:param `p`: TOWRITE
:type `p`: `QPainterPath`_
:param `rgb`: TOWRITE
:type `rgb`: QRgb
:param `parent`: TOWRITE
:type `parent`: `QGraphicsItem`_
"""
super(PolylineObject, self).__init__(parent)
qDebug("PolylineObject Constructor()")
self.normalPath = QPainterPath()
self.gripIndex = int()
self.init(x, y, p, rgb, Qt.SolidLine) # TODO: getCurrentLineType
#OVERLOADED IMPL?# if obj:
#OVERLOADED IMPL?# self.init(obj.objectX(), obj.objectY(), obj.objectCopyPath(), obj.objectColorRGB(), Qt.SolidLine) # TODO: getCurrentLineType
#OVERLOADED IMPL?# self.setRotation(obj.rotation())
#OVERLOADED IMPL?# self.setScale(obj.scale())
def __del__(self):
"""Class destructor."""
qDebug("PolylineObject Destructor()")
def init(self, x, y, p, rgb, lineType):
"""
TOWRITE
:param `x`: TOWRITE
:type `x`: qreal
:param `y`: TOWRITE
:type `y`: qreal
:param `p`: TOWRITE
:type `p`: `QPainterPath`_
:param `rgb`: TOWRITE
:type `rgb`: QRgb
:param `lineType`: TOWRITE
:type `lineType`: Qt.PenStyle
"""
self.setData(OBJ_TYPE, self.type())
self.setData(OBJ_NAME, OBJ_NAME_POLYLINE)
# WARNING: DO NOT enable QGraphicsItem::ItemIsMovable. If it is enabled,
# WARNING: and the item is double clicked, the scene will erratically move the item while zooming.
# WARNING: All movement has to be handled explicitly by us, not by the scene.
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.gripIndex = -1
self.updatePath(p)
self.setObjectPos(x,y)
self.setObjectColorRGB(rgb)
self.setObjectLineType(lineType)
self.setObjectLineWeight(0.35) # TODO: pass in proper lineweight
self.setPen(self.objectPen())
def updatePath(self, p):
"""
TOWRITE
:param `p`: TOWRITE
:type `p`: `QPainterPath`_
"""
self.normalPath = p
reversePath = self.normalPath.toReversed() # QPainterPath
reversePath.connectPath(self.normalPath)
self.setObjectPath(reversePath)
def paint(self, painter, option, widget):
"""
TOWRITE
:param `painter`: TOWRITE
:type `painter`: `QPainter`_
:param `option`: TOWRITE
:type `option`: `QStyleOptionGraphicsItem`_
:param `widget`: TOWRITE
:type `widget`: `QWidget`_
"""
objScene = self.scene() # QGraphicsScene*
if not objScene:
return
paintPen = self.pen() # QPen
painter.setPen(paintPen)
self.updateRubber(painter)
if option.state & QStyle.State_Selected:
paintPen.setStyle(Qt.DashLine)
if objScene.property(ENABLE_LWT): # .toBool()
paintPen = self.lineWeightPen()
painter.setPen(paintPen)
painter.drawPath(self.normalPath)
if (objScene.property(ENABLE_LWT) and objScene.property(ENABLE_REAL)): # .toBool()
self.realRender(painter, self.normalPath)
def updateRubber(self, painter=None):
"""
TOWRITE
:param `painter`: TOWRITE
:type `painter`: `QPainter`_
"""
rubberMode = self.objectRubberMode() # int
if rubberMode == OBJ_RUBBER_POLYLINE:
self.setObjectPos(self.objectRubberPoint("POLYLINE_POINT_0"))
rubberLine = QLineF(self.normalPath.currentPosition(), self.mapFromScene(self.objectRubberPoint("")))
if painter:
self.drawRubberLine(rubberLine, painter, "VIEW_COLOR_CROSSHAIR")
ok = False # bool
numStr = self.objectRubberText("POLYLINE_NUM_POINTS") # QString
if not numStr:
return
try:
num = int(numStr)
except ValueError:
return
appendStr = '' # QString
rubberPath = QPainterPath()
for i in range(1, num): # for(int i = 1; i <= num; i++)
appendStr = "POLYLINE_POINT_" + "%s" % i # QString().setNum(i);
appendPoint = self.mapFromScene(self.objectRubberPoint(appendStr)) # QPointF
rubberPath.lineTo(appendPoint)
self.updatePath(rubberPath)
# Ensure the path isn't updated until the number of points is changed again.
self.setObjectRubberText("POLYLINE_NUM_POINTS", "")
elif rubberMode == OBJ_RUBBER_GRIP:
if painter:
elemCount = self.normalPath.elementCount() # int
gripPoint = self.objectRubberPoint("GRIP_POINT") # QPointF
if self.gripIndex == -1:
self.gripIndex = self.findIndex(gripPoint)
if self.gripIndex == -1:
return
if not self.gripIndex: # First.
ef = self.normalPath.elementAt(1) # QPainterPath::Element
efPoint = QPointF(ef.x, ef.y) # QPointF
painter.drawLine(efPoint, self.mapFromScene(self.objectRubberPoint("")))
elif self.gripIndex == elemCount - 1: # Last.
el = self.normalPath.elementAt(self.gripIndex - 1) # QPainterPath::Element
elPoint = QPointF(el.x, el.y) # QPointF
painter.drawLine(elPoint, self.mapFromScene(self.objectRubberPoint("")))
else: # Middle.
em = self.normalPath.elementAt(self.gripIndex - 1) # QPainterPath::Element
en = self.normalPath.elementAt(self.gripIndex + 1) # QPainterPath::Element
emPoint = QPointF(em.x, em.y) # QPointF
enPoint = QPointF(en.x, en.y) # QPointF
painter.drawLine(emPoint, self.mapFromScene(self.objectRubberPoint("")))
painter.drawLine(enPoint, self.mapFromScene(self.objectRubberPoint("")))
rubLine = QLineF(self.mapFromScene(gripPoint), self.mapFromScene(self.objectRubberPoint("")))
self.drawRubberLine(rubLine, painter, "VIEW_COLOR_CROSSHAIR")
def vulcanize(self):
"""
TOWRITE
"""
qDebug("PolylineObject vulcanize()")
self.updateRubber()
self.setObjectRubberMode(OBJ_RUBBER_OFF)
if not self.normalPath.elementCount():
QMessageBox.critical(0, QObject.tr("Empty Polyline Error"), QObject.tr("The polyline added contains no points. The command that created this object has flawed logic."))
def mouseSnapPoint(self, mousePoint):
"""
Returns the closest snap point to the mouse point.
:param `mousePoint`: TOWRITE
:type `mousePoint`: `QPointF`_
:rtype: `QPointF`_
"""
element = self.normalPath.elementAt(0) # QPainterPath::Element
closestPoint = self.mapToScene(QPointF(element.x, element.y)) # QPointF
closestDist = QLineF(mousePoint, closestPoint).length() # qreal
elemCount = self.normalPath.elementCount() # int
for i in range(0, elemCount): # for(int i = 0; i < elemCount; ++i)
element = self.normalPath.elementAt(i)
elemPoint = self.mapToScene(element.x, element.y) # QPointF
elemDist = QLineF(mousePoint, elemPoint).length() # qreal
if elemDist < closestDist:
closestPoint = elemPoint
closestDist = elemDist
return closestPoint
def allGripPoints(self):
"""
TOWRITE
:rtype: QList<QPointF>
"""
## QList<QPointF> gripPoints;
## QPainterPath::Element element;
## for(int i = 0; i < self.normalPath.elementCount(); ++i)
##
## element = self.normalPath.elementAt(i);
## gripPoints << mapToScene(element.x, element.y);
gripPoints = []
element = QPainterPath.Element
for i in range(0, self.normalPath.elementCount()):
element = self.normalPath.elementAt(i)
gripPoints.append(self.mapToScene(element.x, element.y))
return gripPoints
def findIndex(self, point):
"""
TOWRITE
:param `point`: TOWRITE
:type `point`: `QPointF`_
:rtype: int
"""
elemCount = self.normalPath.elementCount() # int
# NOTE: Points here are in item coordinates
itemPoint = self.mapFromScene(point) # QPointF
for i in range(0, elemCount): # for(int i = 0; i < elemCount; i++)
e = self.normalPath.elementAt(i) # QPainterPath::Element
elemPoint = QPointF(e.x, e.y) # QPointF
if itemPoint == elemPoint:
return i
return -1
def gripEdit(self, before, after):
"""
TOWRITE
:param `before`: TOWRITE
:type `before`: `QPointF`_
:param `after`: TOWRITE
:type `after`: `QPointF`_
"""
self.gripIndex = self.findIndex(before)
if self.gripIndex == -1:
return
a = self.mapFromScene(after) # QPointF
self.normalPath.setElementPositionAt(self.gripIndex, a.x(), a.y())
self.updatePath(self.normalPath)
self.gripIndex = -1
def objectCopyPath(self):
"""
TOWRITE
:rtype: `QPainterPath`_
"""
return self.normalPath
def objectSavePath(self):
"""
TOWRITE
:rtype: `QPainterPath`_
"""
s = self.scale() # qreal
trans = QTransform()
trans.rotate(self.rotation())
trans.scale(s, s)
return trans.map(self.normalPath)
def objectPos(self):
"""
TOWRITE
:return: TOWRITE
:rtype: `QPointF`_
"""
return self.scenePos()
def objectX(self):
"""
TOWRITE
:return: TOWRITE
:rtype: float
"""
return self.scenePos().x()
def objectY(self):
"""
TOWRITE
:return: TOWRITE
:rtype: float
"""
return self.scenePos().y()
# pythonic setObjectPos overload
@signature(QPointF)
def setObjectPosFromPoint(self, point):
"""
TOWRITE
:param `point`: TOWRITE
:type `point`: `QPointF`_
"""
self.setPos(point.x(), point.y())
# pythonic setObjectPos overload
@signature(float, float)
def setObjectPosFromXY(self, x, y):
"""
TOWRITE
:param `x`: TOWRITE
:type `x`: float
:param y`: TOWRITE
:type `y`: float
"""
self.setPos(x, y)
@overloaded(setObjectPosFromPoint, setObjectPosFromXY)
def setObjectPos(self, *args):
""" TOWRITE """
pass
def setObjectX(self, x):
"""
TOWRITE
:param `x`: TOWRITE
:type `x`: float
"""
self.setObjectPos(x, self.objectY())
def setObjectY(self, y):
"""
TOWRITE
:param `y`: TOWRITE
:type `y`: float
"""
self.setObjectPos(self.objectX(), y)
# kate: bom off; indent-mode python; indent-width 4; replace-trailing-space-save on;
| 30.77221
| 180
| 0.563698
|
4a0dc87f79ebbbb98c21b70eb9a3a6008a89e138
| 313
|
py
|
Python
|
xoeuf/tests/test_timespan/tests/__init__.py
|
merchise-autrement/xoeuf
|
583a0faa345480e73110d467203eefd142b0a710
|
[
"BSD-3-Clause"
] | 3
|
2015-05-16T04:40:14.000Z
|
2016-01-26T05:36:20.000Z
|
xoeuf/tests/test_timespan/tests/__init__.py
|
merchise-autrement/xoeuf
|
583a0faa345480e73110d467203eefd142b0a710
|
[
"BSD-3-Clause"
] | null | null | null |
xoeuf/tests/test_timespan/tests/__init__.py
|
merchise-autrement/xoeuf
|
583a0faa345480e73110d467203eefd142b0a710
|
[
"BSD-3-Clause"
] | 1
|
2017-03-23T23:08:50.000Z
|
2017-03-23T23:08:50.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) Merchise Autrement [~º/~] and Contributors
# All rights reserved.
#
# This is free software; you can do what the LICENCE file allows you to.
#
from . import test_timespan # noqa
| 31.3
| 72
| 0.533546
|
4a0dc92c173b72057b2c9faa36d80f4568eb6fdf
| 274
|
py
|
Python
|
Outros/distancia-euclidiana-dois-pontos.py
|
da-ferreira/algorithms_and_data_structures
|
fc79008cee5b3b65e3d9ae2ed542c79f061c77d1
|
[
"MIT"
] | null | null | null |
Outros/distancia-euclidiana-dois-pontos.py
|
da-ferreira/algorithms_and_data_structures
|
fc79008cee5b3b65e3d9ae2ed542c79f061c77d1
|
[
"MIT"
] | null | null | null |
Outros/distancia-euclidiana-dois-pontos.py
|
da-ferreira/algorithms_and_data_structures
|
fc79008cee5b3b65e3d9ae2ed542c79f061c77d1
|
[
"MIT"
] | null | null | null |
"""
Implementacao da distancia euclidiana de dois pontos em um plano.
"""
def euclidian_distance(x1, y1, x2, y2):
from math import sqrt
distancia = (abs(x2 - x1) ** 2) + (abs(y2 - y1) ** 2)
distancia = sqrt(distancia)
return distancia
| 18.266667
| 66
| 0.59854
|
4a0dc949ca233d31d0c6762f2cb67c3fdfb797ef
| 6,064
|
py
|
Python
|
sdk/python/pulumi_azure_native/cdn/v20150601/get_origin.py
|
sebtelko/pulumi-azure-native
|
711ec021b5c73da05611c56c8a35adb0ce3244e4
|
[
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure_native/cdn/v20150601/get_origin.py
|
sebtelko/pulumi-azure-native
|
711ec021b5c73da05611c56c8a35adb0ce3244e4
|
[
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure_native/cdn/v20150601/get_origin.py
|
sebtelko/pulumi-azure-native
|
711ec021b5c73da05611c56c8a35adb0ce3244e4
|
[
"Apache-2.0"
] | null | null | null |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = [
'GetOriginResult',
'AwaitableGetOriginResult',
'get_origin',
]
@pulumi.output_type
class GetOriginResult:
"""
CDN origin is the source of the content being delivered via CDN. When the edge nodes represented by an endpoint do not have the requested content cached, they attempt to fetch it from one or more of the configured origins.
"""
def __init__(__self__, host_name=None, http_port=None, https_port=None, id=None, name=None, provisioning_state=None, resource_state=None, type=None):
if host_name and not isinstance(host_name, str):
raise TypeError("Expected argument 'host_name' to be a str")
pulumi.set(__self__, "host_name", host_name)
if http_port and not isinstance(http_port, int):
raise TypeError("Expected argument 'http_port' to be a int")
pulumi.set(__self__, "http_port", http_port)
if https_port and not isinstance(https_port, int):
raise TypeError("Expected argument 'https_port' to be a int")
pulumi.set(__self__, "https_port", https_port)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if resource_state and not isinstance(resource_state, str):
raise TypeError("Expected argument 'resource_state' to be a str")
pulumi.set(__self__, "resource_state", resource_state)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="hostName")
def host_name(self) -> str:
"""
The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.
"""
return pulumi.get(self, "host_name")
@property
@pulumi.getter(name="httpPort")
def http_port(self) -> Optional[int]:
"""
The value of the HTTP port. Must be between 1 and 65535.
"""
return pulumi.get(self, "http_port")
@property
@pulumi.getter(name="httpsPort")
def https_port(self) -> Optional[int]:
"""
The value of the https port. Must be between 1 and 65535.
"""
return pulumi.get(self, "https_port")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource ID
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
Provisioning status of the origin.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="resourceState")
def resource_state(self) -> str:
"""
Resource status of the origin.
"""
return pulumi.get(self, "resource_state")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type
"""
return pulumi.get(self, "type")
class AwaitableGetOriginResult(GetOriginResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetOriginResult(
host_name=self.host_name,
http_port=self.http_port,
https_port=self.https_port,
id=self.id,
name=self.name,
provisioning_state=self.provisioning_state,
resource_state=self.resource_state,
type=self.type)
def get_origin(endpoint_name: Optional[str] = None,
origin_name: Optional[str] = None,
profile_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOriginResult:
"""
CDN origin is the source of the content being delivered via CDN. When the edge nodes represented by an endpoint do not have the requested content cached, they attempt to fetch it from one or more of the configured origins.
:param str endpoint_name: Name of the endpoint within the CDN profile.
:param str origin_name: Name of the origin, an arbitrary value but it needs to be unique under endpoint
:param str profile_name: Name of the CDN profile within the resource group.
:param str resource_group_name: Name of the resource group within the Azure subscription.
"""
__args__ = dict()
__args__['endpointName'] = endpoint_name
__args__['originName'] = origin_name
__args__['profileName'] = profile_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:cdn/v20150601:getOrigin', __args__, opts=opts, typ=GetOriginResult).value
return AwaitableGetOriginResult(
host_name=__ret__.host_name,
http_port=__ret__.http_port,
https_port=__ret__.https_port,
id=__ret__.id,
name=__ret__.name,
provisioning_state=__ret__.provisioning_state,
resource_state=__ret__.resource_state,
type=__ret__.type)
| 37.202454
| 226
| 0.652704
|
4a0dca985887d508c4ca21014e7e7514a9f51ce8
| 383
|
py
|
Python
|
tests/test_recursive_def.py
|
satgi/pygraphy
|
014883ea35dcd6d0288730140d80681cf251a783
|
[
"MIT"
] | 98
|
2019-07-11T09:08:12.000Z
|
2022-02-12T04:32:55.000Z
|
tests/test_recursive_def.py
|
satgi/pygraphy
|
014883ea35dcd6d0288730140d80681cf251a783
|
[
"MIT"
] | 27
|
2019-07-17T09:25:59.000Z
|
2020-07-20T07:50:15.000Z
|
tests/test_recursive_def.py
|
satgi/pygraphy
|
014883ea35dcd6d0288730140d80681cf251a783
|
[
"MIT"
] | 11
|
2019-07-16T12:01:15.000Z
|
2022-03-04T08:08:10.000Z
|
from __future__ import annotations
import pygraphy
from typing import Optional
class WhereInput(pygraphy.Input):
_and: Optional[WhereInput] = None
class Query(pygraphy.Query):
@pygraphy.field
def foo(self, arg: WhereInput) -> int:
return 0
class Schema(pygraphy.Schema):
query: Optional[Query]
def test_recursive_definition():
print(str(Schema))
| 16.652174
| 42
| 0.723238
|
4a0dcb18155d5fb35ff25af026c103c7bd909c4a
| 1,057
|
py
|
Python
|
conftest.py
|
jonathonmellor/mimesis-stats
|
c5e82600da32d6e32bb21925aef15ec429c940bb
|
[
"MIT"
] | 4
|
2021-09-23T11:11:55.000Z
|
2021-12-29T17:33:19.000Z
|
conftest.py
|
jonathonmellor/mimesis-stats
|
c5e82600da32d6e32bb21925aef15ec429c940bb
|
[
"MIT"
] | 27
|
2021-09-05T18:35:01.000Z
|
2022-02-26T23:57:04.000Z
|
conftest.py
|
jonathonmellor/mimesis-stats
|
c5e82600da32d6e32bb21925aef15ec429c940bb
|
[
"MIT"
] | null | null | null |
from typing import Any
import pytest
from mimesis_stats.providers.base_stats import BaseStatsDataProvider
from mimesis_stats.stats_schema import StatsField
@pytest.fixture
def common_seed():
return 42
@pytest.fixture
def dummy_field(dummy_provider):
return StatsField(seed=42, providers=[dummy_provider])
@pytest.fixture
def dummy_provider():
class DummyProvider(BaseStatsDataProvider):
"""
Basic provider used for testing
Methods
-------
one
returns 1
characters
returns "ABC"
dictionary
returns {"collins": "defines"}
"""
class Meta:
name = "dummy"
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@staticmethod
def one():
return 1
@staticmethod
def characters():
return "ABC"
@staticmethod
def dictionary():
return {"collins": "defines"}
return DummyProvider
| 19.574074
| 68
| 0.59035
|
4a0dcb653dbdff7e77ef666aab86dfca8edb789e
| 6,837
|
py
|
Python
|
auditmiddleware/__init__.py
|
Pagolin/openstack-audit-middleware
|
f7917408684f82da6e64b77fc906514accae04ea
|
[
"Apache-2.0"
] | 9
|
2018-01-05T18:57:09.000Z
|
2022-02-09T17:19:14.000Z
|
auditmiddleware/__init__.py
|
Pagolin/openstack-audit-middleware
|
f7917408684f82da6e64b77fc906514accae04ea
|
[
"Apache-2.0"
] | 26
|
2017-10-12T13:04:09.000Z
|
2022-03-11T02:03:57.000Z
|
auditmiddleware/__init__.py
|
Pagolin/openstack-audit-middleware
|
f7917408684f82da6e64b77fc906514accae04ea
|
[
"Apache-2.0"
] | 4
|
2018-01-17T15:50:42.000Z
|
2021-06-01T06:21:39.000Z
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Build open standard audit information based on incoming requests.
AuditMiddleware filter should be placed after
keystonemiddleware.auth_token in the pipeline so that it can utilise the
information the Identity server provides.
"""
from auditmiddleware import _api
from auditmiddleware import _notifier
import copy
import datetime
import functools
from oslo_config import cfg
from oslo_context import context as oslo_context
from oslo_log import log as logging
import pycadf
import pytz
import webob.dec
_LOG = None
AUDIT_MIDDLEWARE_GROUP = 'audit_middleware_notifications'
_AUDIT_OPTS = [
cfg.StrOpt('driver',
help='The Driver to handle sending notifications. Possible '
'values are messaging, messagingv2, routing, log, test, '
'noop. If not specified, then value from '
'oslo_messaging_notifications conf section is used.'),
cfg.ListOpt('topics',
help='List of AMQP topics used for OpenStack notifications. If'
' not specified, then value from '
' oslo_messaging_notifications conf section is used.'),
cfg.StrOpt('transport_url',
secret=True,
help='A URL representing messaging driver to use for '
'notification. If not specified, we fall back to the same '
'configuration used for RPC.'),
cfg.IntOpt('mem_queue_size',
help='Size of the in-memory queue that is used to buffer '
'messages that have not yet been accepted by the '
'transport'),
]
CONF = cfg.CONF
CONF.register_opts(_AUDIT_OPTS, group=AUDIT_MIDDLEWARE_GROUP)
# see https://bugs.launchpad.net/pycadf/+bug/1738737
def patched_get_utc_now(timezone=None):
"""Return the current UTC time.
:param timezone: an optional timezone param to offset time to.
"""
utc_datetime = pytz.utc.localize(datetime.datetime.utcnow())
if timezone is not None:
try:
utc_datetime = utc_datetime.astimezone(pytz.timezone(timezone))
except Exception as e:
_LOG.exception('Error translating timezones: %s ', e)
return utc_datetime.isoformat()
# monkey patch pycadfs flawed timestamp formatter
pycadf.timestamp.get_utc_now = patched_get_utc_now
def _log_and_ignore_error(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception:
_LOG.exception('An exception occurred processing '
'the API call with args: {0}{1}'
.format(args, kwargs))
return wrapper
class ConfigError(BaseException):
"""Exception for configuration errors."""
pass
class AuditMiddleware(object):
"""Create an audit event based on request/response.
The audit middleware takes in various configuration options such as the
ability to skip audit of certain requests. The full list of options can
be discovered here:
https://github.com/sapcc/openstack-audit-middleware/blob/master/README.md
"""
def __init__(self, app, **conf):
"""Initialize the middleware based on the application config.
Parameters:
app: the web application exteneded by this middleware
conf: the application specific configuration parameters as dict
"""
self._application = app
self._conf = CONF
global _LOG
_LOG = logging.getLogger(conf.get('log_name', __name__))
self._ignore_req_list = [x.upper().strip() for x in
conf.get('ignore_req_list', '').split(',')]
self._cadf_audit = _api.OpenStackAuditMiddleware(
conf.get('audit_map_file'),
conf.get('record_payloads', False),
conf.get('metrics_enabled', False),
_LOG)
self._notifier = _notifier.create_notifier(self._conf, _LOG,
conf.get('metrics_enabled',
False))
_LOG.debug("audit middleware config: %s", conf)
@_log_and_ignore_error
def _process_request(self, request, response=None):
"""Create & push events for request/response pair."""
events = self._cadf_audit.create_events(request, response)
if events:
# currently there is nothing useful in the context
request.environ['audit.context'] = {}
for e in events:
ctx = request.environ['audit.context']
self._notifier.notify(ctx, e.as_dict())
@webob.dec.wsgify
def __call__(self, req):
"""Here is the actual application call that we are "decorating"."""
if req.method in self._ignore_req_list:
return req.get_response(self._application)
# Cannot use a RequestClass on wsgify above because the `req` object is
# a `WebOb.Request` when this method is called so the RequestClass is
# ignored by the wsgify wrapper.
ctx = oslo_context.get_admin_context().to_dict()
req.environ['audit.context'] = ctx
try:
response = req.get_response(self._application)
except Exception:
self._process_request(req)
raise
else:
self._process_request(req, response)
return response
def _list_opts():
"""Return a list of oslo_config options available in audit middleware.
The returned list includes all oslo_config options which may be registered
at runtime by the project.
Each element of the list is a tuple. The first element is the name of the
group under which the list of elements in the second element will be
registered. A group name of None corresponds to the [DEFAULT] group in
config files.
:returns: a list of (group_name, opts) tuples
"""
return [(AUDIT_MIDDLEWARE_GROUP, copy.deepcopy(_AUDIT_OPTS))]
def filter_factory(global_conf, **local_conf):
"""Return a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def audit_filter(app):
return AuditMiddleware(app, **conf)
return audit_filter
| 35.609375
| 79
| 0.65321
|
4a0dcd8e3ead0769eb7708ba66a11a6050050bfa
| 283
|
py
|
Python
|
Exercises3/R-3.13.py
|
opnsesame/Data-Structures-and-Algorithms-Exercises
|
62f4066c6370225a41295ecb08e05258b08f6d7e
|
[
"Apache-2.0"
] | null | null | null |
Exercises3/R-3.13.py
|
opnsesame/Data-Structures-and-Algorithms-Exercises
|
62f4066c6370225a41295ecb08e05258b08f6d7e
|
[
"Apache-2.0"
] | null | null | null |
Exercises3/R-3.13.py
|
opnsesame/Data-Structures-and-Algorithms-Exercises
|
62f4066c6370225a41295ecb08e05258b08f6d7e
|
[
"Apache-2.0"
] | null | null | null |
'''
Show that if d(n) is O( f (n)) and f (n) is O(g(n)), then d(n) is O(g(n)).
'''
d(n) is O(f(n)) so there is a c and n0 when d(n) <= cf(n) for all n>n0
f(n) is O(g(n)) so there is a k and m0 when f(n) <= kg(n) for all n>n0
d(n) <= cf(n) <= c(k(g(n)))= c*k(g(n))
so d(n) is O(g(n))
| 35.375
| 74
| 0.501767
|
4a0dce65c6958c432c1a77468667606ca70694c9
| 1,130
|
py
|
Python
|
gran/utils/logger.py
|
longland-m/wikigen
|
459ba7bf9d3ca9584de65388cc9b9a15fa16a69f
|
[
"MIT"
] | null | null | null |
gran/utils/logger.py
|
longland-m/wikigen
|
459ba7bf9d3ca9584de65388cc9b9a15fa16a69f
|
[
"MIT"
] | 2
|
2021-08-25T16:04:29.000Z
|
2022-02-10T01:50:44.000Z
|
gran/utils/logger.py
|
longland-m/wikigen
|
459ba7bf9d3ca9584de65388cc9b9a15fa16a69f
|
[
"MIT"
] | null | null | null |
# From GRAN repo, with no changes
import logging
def setup_logging(log_level, log_file, logger_name="exp_logger"):
""" Setup logging """
numeric_level = getattr(logging, log_level.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError("Invalid log level: %s" % log_level)
logging.basicConfig(
filename=log_file,
filemode="w",
format="%(levelname)-5s | %(asctime)s | File %(filename)-20s | Line %(lineno)-5d | %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
level=numeric_level)
# define a Handler which writes messages to the sys.stderr
console = logging.StreamHandler()
console.setLevel(numeric_level)
# set a format which is simpler for console use
formatter = logging.Formatter(
"%(levelname)-5s | %(asctime)s | %(filename)-25s | line %(lineno)-5d: %(message)s"
)
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger(logger_name).addHandler(console)
return get_logger(logger_name)
def get_logger(logger_name="exp_logger"):
return logging.getLogger(logger_name)
| 31.388889
| 102
| 0.700885
|
4a0dce7958a3ca1523d3fd2c8e32325fe308a02a
| 5,030
|
py
|
Python
|
examples/protoss/warpgate_push.py
|
james-m-tubbs/python-sc2
|
6753cbbf745bc5b64f6882d4d0cbd31998e584ea
|
[
"MIT"
] | null | null | null |
examples/protoss/warpgate_push.py
|
james-m-tubbs/python-sc2
|
6753cbbf745bc5b64f6882d4d0cbd31998e584ea
|
[
"MIT"
] | null | null | null |
examples/protoss/warpgate_push.py
|
james-m-tubbs/python-sc2
|
6753cbbf745bc5b64f6882d4d0cbd31998e584ea
|
[
"MIT"
] | null | null | null |
import sc2
from sc2 import Race, Difficulty
from sc2.player import Bot, Computer
class WarpGateBot(sc2.BotAI):
def __init__(self):
self.warpgate_started = False
self.proxy_built = False
def select_target(self, state):
return self.enemy_start_locations[0]
async def warp_new_units(self, proxy):
for warpgate in self.units(WARPGATE).ready:
abilities = await self.get_available_abilities(warpgate)
# all the units have the same cooldown anyway so let's just look at ZEALOT
if AbilityId.WARPGATETRAIN_ZEALOT in abilities:
pos = proxy.position.to2.random_on_distance(4)
placement = await self.find_placement(AbilityId.WARPGATETRAIN_STALKER, pos, placement_step=1)
if placement is None:
#return ActionResult.CantFindPlacementLocation
print("can't place")
return
await self.do(warpgate.warp_in(STALKER, placement))
async def on_step(self, iteration):
await self.distribute_workers()
if not self.units(NEXUS).ready.exists:
for worker in self.workers:
await self.do(worker.attack(self.enemy_start_locations[0]))
return
else:
nexus = self.units(NEXUS).ready.random
if self.supply_left < 2 and not self.already_pending(PYLON):
if self.can_afford(PYLON):
await self.build(PYLON, near=nexus)
return
if self.workers.amount < self.units(NEXUS).amount*22 and nexus.noqueue:
if self.can_afford(PROBE):
await self.do(nexus.train(PROBE))
elif self.units(PYLON).amount < 5 and not self.already_pending(PYLON):
if self.can_afford(PYLON):
await self.build(PYLON, near=nexus.position.towards(self.game_info.map_center, 5))
if self.units(PYLON).ready.exists:
proxy = self.units(PYLON).closest_to(self.enemy_start_locations[0])
pylon = self.units(PYLON).ready.random
if self.units(GATEWAY).ready.exists:
if not self.units(CYBERNETICSCORE).exists:
if self.can_afford(CYBERNETICSCORE) and not self.already_pending(CYBERNETICSCORE):
await self.build(CYBERNETICSCORE, near=pylon)
if self.can_afford(GATEWAY) and self.units(WARPGATE).amount < 4 and self.units(GATEWAY).amount < 4:
await self.build(GATEWAY, near=pylon)
for nexus in self.units(NEXUS).ready:
vgs = self.state.vespene_geyser.closer_than(20.0, nexus)
for vg in vgs:
if not self.can_afford(ASSIMILATOR):
break
worker = self.select_build_worker(vg.position)
if worker is None:
break
if not self.units(ASSIMILATOR).closer_than(1.0, vg).exists:
await self.do(worker.build(ASSIMILATOR, vg))
if self.units(CYBERNETICSCORE).ready.exists and self.can_afford(RESEARCH_WARPGATE) and not self.warpgate_started:
ccore = self.units(CYBERNETICSCORE).ready.first
await self.do(ccore(RESEARCH_WARPGATE))
self.warpgate_started = True
for gateway in self.units(GATEWAY).ready:
abilities = await self.get_available_abilities(gateway)
if AbilityId.MORPH_WARPGATE in abilities and self.can_afford(AbilityId.MORPH_WARPGATE):
await self.do(gateway(MORPH_WARPGATE))
if self.proxy_built:
await self.warp_new_units(proxy)
if self.units(STALKER).amount > 3:
for vr in self.units(STALKER).ready.idle:
await self.do(vr.attack(self.select_target(self.state)))
if self.units(CYBERNETICSCORE).amount >= 1 and not self.proxy_built and self.can_afford(PYLON):
p = self.game_info.map_center.towards(self.enemy_start_locations[0], 20)
await self.build(PYLON, near=p)
self.proxy_built = True
if not self.units(CYBERNETICSCORE).ready.exists:
if not nexus.has_buff(BuffId.CHRONOBOOSTENERGYCOST):
abilities = await self.get_available_abilities(nexus)
if AbilityId.EFFECT_CHRONOBOOSTENERGYCOST in abilities:
await self.do(nexus(AbilityId.EFFECT_CHRONOBOOSTENERGYCOST, nexus))
else:
ccore = self.units(CYBERNETICSCORE).ready.first
if not ccore.has_buff(BuffId.CHRONOBOOSTENERGYCOST):
abilities = await self.get_available_abilities(nexus)
if AbilityId.EFFECT_CHRONOBOOSTENERGYCOST in abilities:
await self.do(nexus(AbilityId.EFFECT_CHRONOBOOSTENERGYCOST, ccore))
def main():
sc2.run_game(sc2.maps.get("(2)CatalystLE"), [
Bot(Race.Protoss, WarpGateBot()),
Computer(Race.Protoss, Difficulty.Easy)
], realtime=False)
if __name__ == '__main__':
main()
| 42.627119
| 121
| 0.631412
|
4a0dcebfd0acc6bf59772b9d4964ca70eb50550e
| 2,065
|
py
|
Python
|
sdk/python/pulumi_alicloud/cr/_inputs.py
|
pulumi/pulumi-alicloud
|
9c34d84b4588a7c885c6bec1f03b5016e5a41683
|
[
"ECL-2.0",
"Apache-2.0"
] | 42
|
2019-03-18T06:34:37.000Z
|
2022-03-24T07:08:57.000Z
|
sdk/python/pulumi_alicloud/cr/_inputs.py
|
pulumi/pulumi-alicloud
|
9c34d84b4588a7c885c6bec1f03b5016e5a41683
|
[
"ECL-2.0",
"Apache-2.0"
] | 152
|
2019-04-15T21:03:44.000Z
|
2022-03-29T18:00:57.000Z
|
sdk/python/pulumi_alicloud/cr/_inputs.py
|
pulumi/pulumi-alicloud
|
9c34d84b4588a7c885c6bec1f03b5016e5a41683
|
[
"ECL-2.0",
"Apache-2.0"
] | 3
|
2020-08-26T17:30:07.000Z
|
2021-07-05T01:37:45.000Z
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'RepoDomainListArgs',
]
@pulumi.input_type
class RepoDomainListArgs:
def __init__(__self__, *,
internal: Optional[pulumi.Input[str]] = None,
public: Optional[pulumi.Input[str]] = None,
vpc: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] internal: Domain of internal endpoint, only in some regions.
:param pulumi.Input[str] public: Domain of public endpoint.
:param pulumi.Input[str] vpc: Domain of vpc endpoint.
"""
if internal is not None:
pulumi.set(__self__, "internal", internal)
if public is not None:
pulumi.set(__self__, "public", public)
if vpc is not None:
pulumi.set(__self__, "vpc", vpc)
@property
@pulumi.getter
def internal(self) -> Optional[pulumi.Input[str]]:
"""
Domain of internal endpoint, only in some regions.
"""
return pulumi.get(self, "internal")
@internal.setter
def internal(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "internal", value)
@property
@pulumi.getter
def public(self) -> Optional[pulumi.Input[str]]:
"""
Domain of public endpoint.
"""
return pulumi.get(self, "public")
@public.setter
def public(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "public", value)
@property
@pulumi.getter
def vpc(self) -> Optional[pulumi.Input[str]]:
"""
Domain of vpc endpoint.
"""
return pulumi.get(self, "vpc")
@vpc.setter
def vpc(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "vpc", value)
| 29.5
| 93
| 0.610654
|
4a0dcfd0c132c85ae12147192a2f62fc3dec551b
| 67,603
|
py
|
Python
|
tests/alerts_test.py
|
ziedkaaniche/elastalert
|
3856f329ceeefc94d41e84d1a311822b963ad2fb
|
[
"Apache-2.0"
] | null | null | null |
tests/alerts_test.py
|
ziedkaaniche/elastalert
|
3856f329ceeefc94d41e84d1a311822b963ad2fb
|
[
"Apache-2.0"
] | null | null | null |
tests/alerts_test.py
|
ziedkaaniche/elastalert
|
3856f329ceeefc94d41e84d1a311822b963ad2fb
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
import base64
import datetime
import json
import subprocess
import mock
import pytest
from elastalert.alerts import AlertaAlerter
from elastalert.alerts import Alerter
from elastalert.alerts import BasicMatchString
from elastalert.alerts import CommandAlerter
from elastalert.alerts import EmailAlerter
from elastalert.alerts import HipChatAlerter
from elastalert.alerts import HTTPPostAlerter
from elastalert.alerts import MsTeamsAlerter
from elastalert.alerts import PagerDutyAlerter
from elastalert.alerts import SlackAlerter
from elastalert.alerts import StrideAlerter
from elastalert.loaders import FileRulesLoader
from elastalert.opsgenie import OpsGenieAlerter
from elastalert.util import ts_add
from elastalert.util import ts_now
class mock_rule:
def get_match_str(self, event):
return str(event)
def test_basic_match_string(ea):
ea.rules[0]['top_count_keys'] = ['username']
match = {'@timestamp': '1918-01-17', 'field': 'value', 'top_events_username': {'bob': 10, 'mallory': 5}}
alert_text = str(BasicMatchString(ea.rules[0], match))
assert 'anytest' in alert_text
assert 'some stuff happened' in alert_text
assert 'username' in alert_text
assert 'bob: 10' in alert_text
assert 'field: value' in alert_text
# Non serializable objects don't cause errors
match['non-serializable'] = {open: 10}
alert_text = str(BasicMatchString(ea.rules[0], match))
# unicode objects dont cause errors
match['snowman'] = '☃'
alert_text = str(BasicMatchString(ea.rules[0], match))
# Pretty printed objects
match.pop('non-serializable')
match['object'] = {'this': {'that': [1, 2, "3"]}}
alert_text = str(BasicMatchString(ea.rules[0], match))
assert '"this": {\n "that": [\n 1,\n 2,\n "3"\n ]\n }' in alert_text
ea.rules[0]['alert_text'] = 'custom text'
alert_text = str(BasicMatchString(ea.rules[0], match))
assert 'custom text' in alert_text
assert 'anytest' not in alert_text
ea.rules[0]['alert_text_type'] = 'alert_text_only'
alert_text = str(BasicMatchString(ea.rules[0], match))
assert 'custom text' in alert_text
assert 'some stuff happened' not in alert_text
assert 'username' not in alert_text
assert 'field: value' not in alert_text
ea.rules[0]['alert_text_type'] = 'exclude_fields'
alert_text = str(BasicMatchString(ea.rules[0], match))
assert 'custom text' in alert_text
assert 'some stuff happened' in alert_text
assert 'username' in alert_text
assert 'field: value' not in alert_text
def test_email():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com', 'owner': 'owner_value',
'alert_subject': 'Test alert for {0}, owned by {1}', 'alert_subject_args': ['test_term', 'owner'], 'snowman': '☃'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'From: testfrom@test.test' in body
assert 'Subject: Test alert for test_value, owned by owner_value' in body
def test_email_from_field():
rule = {'name': 'test alert', 'email': ['testing@test.test'], 'email_add_domain': 'example.com',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_from_field': 'data.user', 'owner': 'owner_value'}
# Found, without @
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'data': {'user': 'qlo'}}])
assert mock_smtp.mock_calls[4][1][1] == ['qlo@example.com']
# Found, with @
rule['email_add_domain'] = '@example.com'
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'data': {'user': 'qlo'}}])
assert mock_smtp.mock_calls[4][1][1] == ['qlo@example.com']
# Found, list
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'data': {'user': ['qlo', 'foo']}}])
assert mock_smtp.mock_calls[4][1][1] == ['qlo@example.com', 'foo@example.com']
# Not found
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'data': {'foo': 'qlo'}}])
assert mock_smtp.mock_calls[4][1][1] == ['testing@test.test']
# Found, wrong type
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'data': {'user': 17}}])
assert mock_smtp.mock_calls[4][1][1] == ['testing@test.test']
def test_email_with_unicode_strings():
rule = {'name': 'test alert', 'email': 'testing@test.test', 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com', 'owner': 'owner_value',
'alert_subject': 'Test alert for {0}, owned by {1}', 'alert_subject_args': ['test_term', 'owner'], 'snowman': '☃'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(mock.ANY, ['testing@test.test'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'From: testfrom@test.test' in body
assert 'Subject: Test alert for test_value, owned by owner_value' in body
def test_email_with_auth():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'alert_subject': 'Test alert for {0}', 'alert_subject_args': ['test_term'], 'smtp_auth_file': 'file.txt',
'rule_file': '/tmp/foo.yaml'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
with mock.patch('elastalert.alerts.yaml_loader') as mock_open:
mock_open.return_value = {'user': 'someone', 'password': 'hunter2'}
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().login('someone', 'hunter2'),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
def test_email_with_cert_key():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'alert_subject': 'Test alert for {0}', 'alert_subject_args': ['test_term'], 'smtp_auth_file': 'file.txt',
'smtp_cert_file': 'dummy/cert.crt', 'smtp_key_file': 'dummy/client.key', 'rule_file': '/tmp/foo.yaml'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
with mock.patch('elastalert.alerts.yaml_loader') as mock_open:
mock_open.return_value = {'user': 'someone', 'password': 'hunter2'}
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile='dummy/cert.crt', keyfile='dummy/client.key'),
mock.call().login('someone', 'hunter2'),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
def test_email_with_cc():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'cc': 'tester@testing.testing'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test', 'tester@testing.testing'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'CC: tester@testing.testing' in body
assert 'From: testfrom@test.test' in body
def test_email_with_bcc():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'bcc': 'tester@testing.testing'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test', 'tester@testing.testing'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'CC: tester@testing.testing' not in body
assert 'From: testfrom@test.test' in body
def test_email_with_cc_and_bcc():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'], 'from_addr': 'testfrom@test.test',
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'cc': ['test1@test.com', 'test2@test.com'], 'bcc': 'tester@testing.testing'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value'}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(
mock.ANY,
[
'testing@test.test',
'test@test.test',
'test1@test.com',
'test2@test.com',
'tester@testing.testing'
],
mock.ANY
),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'CC: test1@test.com,test2@test.com' in body
assert 'From: testfrom@test.test' in body
def test_email_with_args():
rule = {
'name': 'test alert',
'email': ['testing@test.test', 'test@test.test'],
'from_addr': 'testfrom@test.test',
'type': mock_rule(),
'timestamp_field': '@timestamp',
'email_reply_to': 'test@example.com',
'alert_subject': 'Test alert for {0} {1}',
'alert_subject_args': ['test_term', 'test.term'],
'alert_text': 'Test alert for {0} and {1} {2}',
'alert_text_args': ['test_arg1', 'test_arg2', 'test.arg3'],
'alert_missing_value': '<CUSTOM MISSING VALUE>'
}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value', 'test_arg1': 'testing', 'test': {'term': ':)', 'arg3': '☃'}}])
expected = [mock.call('localhost'),
mock.call().ehlo(),
mock.call().has_extn('STARTTLS'),
mock.call().starttls(certfile=None, keyfile=None),
mock.call().sendmail(mock.ANY, ['testing@test.test', 'test@test.test'], mock.ANY),
mock.call().quit()]
assert mock_smtp.mock_calls == expected
body = mock_smtp.mock_calls[4][1][2]
# Extract the MIME encoded message body
body_text = base64.b64decode(body.split('\n\n')[-1][:-1]).decode('utf-8')
assert 'testing' in body_text
assert '<CUSTOM MISSING VALUE>' in body_text
assert '☃' in body_text
assert 'Reply-To: test@example.com' in body
assert 'To: testing@test.test' in body
assert 'From: testfrom@test.test' in body
assert 'Subject: Test alert for test_value :)' in body
def test_email_query_key_in_subject():
rule = {'name': 'test alert', 'email': ['testing@test.test', 'test@test.test'],
'type': mock_rule(), 'timestamp_field': '@timestamp', 'email_reply_to': 'test@example.com',
'query_key': 'username'}
with mock.patch('elastalert.alerts.SMTP') as mock_smtp:
mock_smtp.return_value = mock.Mock()
alert = EmailAlerter(rule)
alert.alert([{'test_term': 'test_value', 'username': 'werbenjagermanjensen'}])
body = mock_smtp.mock_calls[4][1][2]
lines = body.split('\n')
found_subject = False
for line in lines:
if line.startswith('Subject'):
assert 'werbenjagermanjensen' in line
found_subject = True
assert found_subject
def test_opsgenie_basic():
rule = {'name': 'testOGalert', 'opsgenie_key': 'ogkey',
'opsgenie_account': 'genies', 'opsgenie_addr': 'https://api.opsgenie.com/v2/alerts',
'opsgenie_recipients': ['lytics'], 'type': mock_rule()}
with mock.patch('requests.post') as mock_post:
alert = OpsGenieAlerter(rule)
alert.alert([{'@timestamp': '2014-10-31T00:00:00'}])
print(("mock_post: {0}".format(mock_post._mock_call_args_list)))
mcal = mock_post._mock_call_args_list
print(('mcal: {0}'.format(mcal[0])))
assert mcal[0][0][0] == ('https://api.opsgenie.com/v2/alerts')
assert mock_post.called
assert mcal[0][1]['headers']['Authorization'] == 'GenieKey ogkey'
assert mcal[0][1]['json']['source'] == 'ElastAlert'
assert mcal[0][1]['json']['responders'] == [{'username': 'lytics', 'type': 'user'}]
assert mcal[0][1]['json']['source'] == 'ElastAlert'
def test_opsgenie_frequency():
rule = {'name': 'testOGalert', 'opsgenie_key': 'ogkey',
'opsgenie_account': 'genies', 'opsgenie_addr': 'https://api.opsgenie.com/v2/alerts',
'opsgenie_recipients': ['lytics'], 'type': mock_rule(),
'filter': [{'query': {'query_string': {'query': '*hihi*'}}}],
'alert': 'opsgenie'}
with mock.patch('requests.post') as mock_post:
alert = OpsGenieAlerter(rule)
alert.alert([{'@timestamp': '2014-10-31T00:00:00'}])
assert alert.get_info()['recipients'] == rule['opsgenie_recipients']
print(("mock_post: {0}".format(mock_post._mock_call_args_list)))
mcal = mock_post._mock_call_args_list
print(('mcal: {0}'.format(mcal[0])))
assert mcal[0][0][0] == ('https://api.opsgenie.com/v2/alerts')
assert mock_post.called
assert mcal[0][1]['headers']['Authorization'] == 'GenieKey ogkey'
assert mcal[0][1]['json']['source'] == 'ElastAlert'
assert mcal[0][1]['json']['responders'] == [{'username': 'lytics', 'type': 'user'}]
assert mcal[0][1]['json']['source'] == 'ElastAlert'
assert mcal[0][1]['json']['source'] == 'ElastAlert'
def test_opsgenie_alert_routing():
rule = {'name': 'testOGalert', 'opsgenie_key': 'ogkey',
'opsgenie_account': 'genies', 'opsgenie_addr': 'https://api.opsgenie.com/v2/alerts',
'opsgenie_recipients': ['{RECEIPIENT_PREFIX}'], 'opsgenie_recipients_args': {'RECEIPIENT_PREFIX': 'recipient'},
'type': mock_rule(),
'filter': [{'query': {'query_string': {'query': '*hihi*'}}}],
'alert': 'opsgenie',
'opsgenie_teams': ['{TEAM_PREFIX}-Team'], 'opsgenie_teams_args': {'TEAM_PREFIX': 'team'}}
with mock.patch('requests.post'):
alert = OpsGenieAlerter(rule)
alert.alert([{'@timestamp': '2014-10-31T00:00:00', 'team': "Test", 'recipient': "lytics"}])
assert alert.get_info()['teams'] == ['Test-Team']
assert alert.get_info()['recipients'] == ['lytics']
def test_opsgenie_default_alert_routing():
rule = {'name': 'testOGalert', 'opsgenie_key': 'ogkey',
'opsgenie_account': 'genies', 'opsgenie_addr': 'https://api.opsgenie.com/v2/alerts',
'opsgenie_recipients': ['{RECEIPIENT_PREFIX}'], 'opsgenie_recipients_args': {'RECEIPIENT_PREFIX': 'recipient'},
'type': mock_rule(),
'filter': [{'query': {'query_string': {'query': '*hihi*'}}}],
'alert': 'opsgenie',
'opsgenie_teams': ['{TEAM_PREFIX}-Team'],
'opsgenie_default_receipients': ["devops@test.com"], 'opsgenie_default_teams': ["Test"]
}
with mock.patch('requests.post'):
alert = OpsGenieAlerter(rule)
alert.alert([{'@timestamp': '2014-10-31T00:00:00', 'team': "Test"}])
assert alert.get_info()['teams'] == ['{TEAM_PREFIX}-Team']
assert alert.get_info()['recipients'] == ['devops@test.com']
def test_kibana(ea):
rule = {'filter': [{'query': {'query_string': {'query': 'xy:z'}}}],
'name': 'Test rule!',
'es_host': 'test.testing',
'es_port': 12345,
'timeframe': datetime.timedelta(hours=1),
'index': 'logstash-test',
'include': ['@timestamp'],
'timestamp_field': '@timestamp'}
match = {'@timestamp': '2014-10-10T00:00:00'}
with mock.patch("elastalert.elastalert.elasticsearch_client") as mock_es:
mock_create = mock.Mock(return_value={'_id': 'ABCDEFGH'})
mock_es_inst = mock.Mock()
mock_es_inst.index = mock_create
mock_es_inst.host = 'test.testing'
mock_es_inst.port = 12345
mock_es.return_value = mock_es_inst
link = ea.generate_kibana_db(rule, match)
assert 'http://test.testing:12345/_plugin/kibana/#/dashboard/temp/ABCDEFGH' == link
# Name and index
dashboard = json.loads(mock_create.call_args_list[0][1]['body']['dashboard'])
assert dashboard['index']['default'] == 'logstash-test'
assert 'Test rule!' in dashboard['title']
# Filters and time range
filters = dashboard['services']['filter']['list']
assert 'xy:z' in filters['1']['query']
assert filters['1']['type'] == 'querystring'
time_range = filters['0']
assert time_range['from'] == ts_add(match['@timestamp'], -rule['timeframe'])
assert time_range['to'] == ts_add(match['@timestamp'], datetime.timedelta(minutes=10))
# Included fields active in table
assert dashboard['rows'][1]['panels'][0]['fields'] == ['@timestamp']
def test_command():
# Test command as list with a formatted arg
rule = {'command': ['/bin/test/', '--arg', '%(somefield)s']}
alert = CommandAlerter(rule)
match = {'@timestamp': '2014-01-01T00:00:00',
'somefield': 'foobarbaz',
'nested': {'field': 1}}
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with(['/bin/test', '--arg', 'foobarbaz'], stdin=subprocess.PIPE, shell=False)
# Test command as string with formatted arg (old-style string format)
rule = {'command': '/bin/test/ --arg %(somefield)s'}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test --arg foobarbaz', stdin=subprocess.PIPE, shell=False)
# Test command as string without formatted arg (old-style string format)
rule = {'command': '/bin/test/foo.sh'}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test/foo.sh', stdin=subprocess.PIPE, shell=True)
# Test command as string with formatted arg (new-style string format)
rule = {'command': '/bin/test/ --arg {match[somefield]}', 'new_style_string_format': True}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test --arg foobarbaz', stdin=subprocess.PIPE, shell=False)
rule = {'command': '/bin/test/ --arg {match[nested][field]}', 'new_style_string_format': True}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test --arg 1', stdin=subprocess.PIPE, shell=False)
# Test command as string without formatted arg (new-style string format)
rule = {'command': '/bin/test/foo.sh', 'new_style_string_format': True}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test/foo.sh', stdin=subprocess.PIPE, shell=True)
rule = {'command': '/bin/test/foo.sh {{bar}}', 'new_style_string_format': True}
alert = CommandAlerter(rule)
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
alert.alert([match])
assert mock_popen.called_with('/bin/test/foo.sh {bar}', stdin=subprocess.PIPE, shell=True)
# Test command with pipe_match_json
rule = {'command': ['/bin/test/', '--arg', '%(somefield)s'],
'pipe_match_json': True}
alert = CommandAlerter(rule)
match = {'@timestamp': '2014-01-01T00:00:00',
'somefield': 'foobarbaz'}
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
mock_subprocess = mock.Mock()
mock_popen.return_value = mock_subprocess
mock_subprocess.communicate.return_value = (None, None)
alert.alert([match])
assert mock_popen.called_with(['/bin/test', '--arg', 'foobarbaz'], stdin=subprocess.PIPE, shell=False)
assert mock_subprocess.communicate.called_with(input=json.dumps(match))
# Test command with fail_on_non_zero_exit
rule = {'command': ['/bin/test/', '--arg', '%(somefield)s'],
'fail_on_non_zero_exit': True}
alert = CommandAlerter(rule)
match = {'@timestamp': '2014-01-01T00:00:00',
'somefield': 'foobarbaz'}
with pytest.raises(Exception) as exception:
with mock.patch("elastalert.alerts.subprocess.Popen") as mock_popen:
mock_subprocess = mock.Mock()
mock_popen.return_value = mock_subprocess
mock_subprocess.wait.return_value = 1
alert.alert([match])
assert mock_popen.called_with(['/bin/test', '--arg', 'foobarbaz'], stdin=subprocess.PIPE, shell=False)
assert "Non-zero exit code while running command" in str(exception)
def test_ms_teams():
rule = {
'name': 'Test Rule',
'type': 'any',
'ms_teams_webhook_url': 'http://test.webhook.url',
'ms_teams_alert_summary': 'Alert from ElastAlert',
'alert_subject': 'Cool subject',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = MsTeamsAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'@type': 'MessageCard',
'@context': 'http://schema.org/extensions',
'summary': rule['ms_teams_alert_summary'],
'title': rule['alert_subject'],
'text': BasicMatchString(rule, match).__str__()
}
mock_post_request.assert_called_once_with(
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_ms_teams_uses_color_and_fixed_width_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'ms_teams_webhook_url': 'http://test.webhook.url',
'ms_teams_alert_summary': 'Alert from ElastAlert',
'ms_teams_alert_fixed_width': True,
'ms_teams_theme_color': '#124578',
'alert_subject': 'Cool subject',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = MsTeamsAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = BasicMatchString(rule, match).__str__()
body = body.replace('`', "'")
body = "```{0}```".format('```\n\n```'.join(x for x in body.split('\n'))).replace('\n``````', '')
expected_data = {
'@type': 'MessageCard',
'@context': 'http://schema.org/extensions',
'summary': rule['ms_teams_alert_summary'],
'title': rule['alert_subject'],
'themeColor': '#124578',
'text': body
}
mock_post_request.assert_called_once_with(
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_slack_uses_custom_title():
rule = {
'name': 'Test Rule',
'type': 'any',
'slack_webhook_url': 'http://please.dontgohere.slack',
'alert_subject': 'Cool subject',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = SlackAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'username': 'elastalert',
'channel': '',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['alert_subject'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none'
}
mock_post_request.assert_called_once_with(
rule['slack_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=False,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_slack_uses_custom_timeout():
rule = {
'name': 'Test Rule',
'type': 'any',
'slack_webhook_url': 'http://please.dontgohere.slack',
'alert_subject': 'Cool subject',
'alert': [],
'slack_timeout': 20
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = SlackAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'username': 'elastalert',
'channel': '',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['alert_subject'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none'
}
mock_post_request.assert_called_once_with(
rule['slack_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=False,
timeout=20
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_slack_uses_rule_name_when_custom_title_is_not_provided():
rule = {
'name': 'Test Rule',
'type': 'any',
'slack_webhook_url': ['http://please.dontgohere.slack'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = SlackAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'username': 'elastalert',
'channel': '',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['name'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none',
}
mock_post_request.assert_called_once_with(
rule['slack_webhook_url'][0],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=False,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_slack_uses_custom_slack_channel():
rule = {
'name': 'Test Rule',
'type': 'any',
'slack_webhook_url': ['http://please.dontgohere.slack'],
'slack_channel_override': '#test-alert',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = SlackAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'username': 'elastalert',
'channel': '#test-alert',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['name'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none',
}
mock_post_request.assert_called_once_with(
rule['slack_webhook_url'][0],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=False,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_slack_uses_list_of_custom_slack_channel():
rule = {
'name': 'Test Rule',
'type': 'any',
'slack_webhook_url': ['http://please.dontgohere.slack'],
'slack_channel_override': ['#test-alert', '#test-alert2'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = SlackAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data1 = {
'username': 'elastalert',
'channel': '#test-alert',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['name'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none'
}
expected_data2 = {
'username': 'elastalert',
'channel': '#test-alert2',
'icon_emoji': ':ghost:',
'attachments': [
{
'color': 'danger',
'title': rule['name'],
'text': BasicMatchString(rule, match).__str__(),
'mrkdwn_in': ['text', 'pretext'],
'fields': []
}
],
'text': '',
'parse': 'none'
}
mock_post_request.assert_called_with(
rule['slack_webhook_url'][0],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=False,
timeout=10
)
assert expected_data1 == json.loads(mock_post_request.call_args_list[0][1]['data'])
assert expected_data2 == json.loads(mock_post_request.call_args_list[1][1]['data'])
def test_http_alerter_with_payload():
rule = {
'name': 'Test HTTP Post Alerter With Payload',
'type': 'any',
'http_post_url': 'http://test.webhook.url',
'http_post_payload': {'posted_name': 'somefield'},
'http_post_static_payload': {'name': 'somestaticname'},
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = HTTPPostAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'posted_name': 'foobarbaz',
'name': 'somestaticname'
}
mock_post_request.assert_called_once_with(
rule['http_post_url'],
data=mock.ANY,
headers={'Content-Type': 'application/json', 'Accept': 'application/json;charset=utf-8'},
proxies=None,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_http_alerter_with_payload_all_values():
rule = {
'name': 'Test HTTP Post Alerter With Payload',
'type': 'any',
'http_post_url': 'http://test.webhook.url',
'http_post_payload': {'posted_name': 'somefield'},
'http_post_static_payload': {'name': 'somestaticname'},
'http_post_all_values': True,
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = HTTPPostAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'posted_name': 'foobarbaz',
'name': 'somestaticname',
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
mock_post_request.assert_called_once_with(
rule['http_post_url'],
data=mock.ANY,
headers={'Content-Type': 'application/json', 'Accept': 'application/json;charset=utf-8'},
proxies=None,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_http_alerter_without_payload():
rule = {
'name': 'Test HTTP Post Alerter Without Payload',
'type': 'any',
'http_post_url': 'http://test.webhook.url',
'http_post_static_payload': {'name': 'somestaticname'},
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = HTTPPostAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz',
'name': 'somestaticname'
}
mock_post_request.assert_called_once_with(
rule['http_post_url'],
data=mock.ANY,
headers={'Content-Type': 'application/json', 'Accept': 'application/json;charset=utf-8'},
proxies=None,
timeout=10
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Test PD Rule',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': '',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with('https://events.pagerduty.com/generic/2010-04-15/create_event.json',
data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_v2():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_api_version': 'v2',
'pagerduty_v2_payload_class': 'ping failure',
'pagerduty_v2_payload_component': 'mysql',
'pagerduty_v2_payload_group': 'app-stack',
'pagerduty_v2_payload_severity': 'error',
'pagerduty_v2_payload_source': 'mysql.host.name',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'payload': {
'class': 'ping failure',
'component': 'mysql',
'group': 'app-stack',
'severity': 'error',
'source': 'mysql.host.name',
'summary': 'Test PD Rule',
'custom_details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n'
},
'timestamp': '2017-01-01T00:00:00'
},
'event_action': 'trigger',
'dedup_key': '',
'routing_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with('https://events.pagerduty.com/v2/enqueue',
data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_custom_incident_key():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_incident_key': 'custom key',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Test PD Rule',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': 'custom key',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_custom_incident_key_with_args():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_incident_key': 'custom {0}',
'pagerduty_incident_key_args': ['somefield'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Test PD Rule',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': 'custom foobarbaz',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_custom_alert_subject():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'alert_subject': 'Hungry kittens',
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_incident_key': 'custom {0}',
'pagerduty_incident_key_args': ['somefield'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Hungry kittens',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': 'custom foobarbaz',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_custom_alert_subject_with_args():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'alert_subject': '{0} kittens',
'alert_subject_args': ['somefield'],
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_incident_key': 'custom {0}',
'pagerduty_incident_key_args': ['someotherfield'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'Stinky',
'someotherfield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Stinky kittens',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: Stinky\nsomeotherfield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': 'custom foobarbaz',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_pagerduty_alerter_custom_alert_subject_with_args_specifying_trigger():
rule = {
'name': 'Test PD Rule',
'type': 'any',
'alert_subject': '{0} kittens',
'alert_subject_args': ['somefield'],
'pagerduty_service_key': 'magicalbadgers',
'pagerduty_event_type': 'trigger',
'pagerduty_client_name': 'ponies inc.',
'pagerduty_incident_key': 'custom {0}',
'pagerduty_incident_key_args': ['someotherfield'],
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = PagerDutyAlerter(rule)
match = {
'@timestamp': '2017-01-01T00:00:00',
'somefield': 'Stinkiest',
'someotherfield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'client': 'ponies inc.',
'description': 'Stinkiest kittens',
'details': {
'information': 'Test PD Rule\n\n@timestamp: 2017-01-01T00:00:00\nsomefield: Stinkiest\nsomeotherfield: foobarbaz\n'
},
'event_type': 'trigger',
'incident_key': 'custom foobarbaz',
'service_key': 'magicalbadgers',
}
mock_post_request.assert_called_once_with(alert.url, data=mock.ANY, headers={'content-type': 'application/json'}, proxies=None)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
def test_alert_text_kw(ea):
rule = ea.rules[0].copy()
rule['alert_text'] = '{field} at {time}'
rule['alert_text_kw'] = {
'@timestamp': 'time',
'field': 'field',
}
match = {'@timestamp': '1918-01-17', 'field': 'value'}
alert_text = str(BasicMatchString(rule, match))
body = '{field} at {@timestamp}'.format(**match)
assert body in alert_text
def test_alert_text_global_substitution(ea):
rule = ea.rules[0].copy()
rule['owner'] = 'the owner from rule'
rule['priority'] = 'priority from rule'
rule['abc'] = 'abc from rule'
rule['alert_text'] = 'Priority: {0}; Owner: {1}; Abc: {2}'
rule['alert_text_args'] = ['priority', 'owner', 'abc']
match = {
'@timestamp': '2016-01-01',
'field': 'field_value',
'abc': 'abc from match',
}
alert_text = str(BasicMatchString(rule, match))
assert 'Priority: priority from rule' in alert_text
assert 'Owner: the owner from rule' in alert_text
# When the key exists in both places, it will come from the match
assert 'Abc: abc from match' in alert_text
def test_alert_text_kw_global_substitution(ea):
rule = ea.rules[0].copy()
rule['foo_rule'] = 'foo from rule'
rule['owner'] = 'the owner from rule'
rule['abc'] = 'abc from rule'
rule['alert_text'] = 'Owner: {owner}; Foo: {foo}; Abc: {abc}'
rule['alert_text_kw'] = {
'owner': 'owner',
'foo_rule': 'foo',
'abc': 'abc',
}
match = {
'@timestamp': '2016-01-01',
'field': 'field_value',
'abc': 'abc from match',
}
alert_text = str(BasicMatchString(rule, match))
assert 'Owner: the owner from rule' in alert_text
assert 'Foo: foo from rule' in alert_text
# When the key exists in both places, it will come from the match
assert 'Abc: abc from match' in alert_text
def test_resolving_rule_references(ea):
rule = {
'name': 'test_rule',
'type': mock_rule(),
'owner': 'the_owner',
'priority': 2,
'list_of_things': [
'1',
'$owner$',
[
'11',
'$owner$',
],
],
'nested_dict': {
'nested_one': '1',
'nested_owner': '$owner$',
},
'resolved_string_reference': '$owner$',
'resolved_int_reference': '$priority$',
'unresolved_reference': '$foo$',
}
alert = Alerter(rule)
assert 'the_owner' == alert.rule['resolved_string_reference']
assert 2 == alert.rule['resolved_int_reference']
assert '$foo$' == alert.rule['unresolved_reference']
assert 'the_owner' == alert.rule['list_of_things'][1]
assert 'the_owner' == alert.rule['list_of_things'][2][1]
assert 'the_owner' == alert.rule['nested_dict']['nested_owner']
def test_stride_plain_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = "{0}\n\n@timestamp: {1}\nsomefield: {2}".format(
rule['name'], match['@timestamp'], match['somefield']
)
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': body}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_stride_underline_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert_text': '<u>Underline Text</u>',
'alert_text_type': 'alert_text_only',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = "Underline Text"
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': body, 'marks': [
{'type': 'underline'}
]}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_stride_bold_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert_text': '<b>Bold Text</b>',
'alert_text_type': 'alert_text_only',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = "Bold Text"
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': body, 'marks': [
{'type': 'strong'}
]}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_stride_strong_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert_text': '<strong>Bold Text</strong>',
'alert_text_type': 'alert_text_only',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = "Bold Text"
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': body, 'marks': [
{'type': 'strong'}
]}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_stride_hyperlink():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert_text': '<a href="http://stride.com">Link</a>',
'alert_text_type': 'alert_text_only',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
body = "Link"
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': body, 'marks': [
{'type': 'link', 'attrs': {'href': 'http://stride.com'}}
]}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_stride_html():
rule = {
'name': 'Test Rule',
'type': 'any',
'stride_access_token': 'token',
'stride_cloud_id': 'cloud_id',
'stride_conversation_id': 'conversation_id',
'alert_subject': 'Cool subject',
'alert_text': '<b>Alert</b>: we found something. <a href="http://stride.com">Link</a>',
'alert_text_type': 'alert_text_only',
'alert': []
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = StrideAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {'body': {'version': 1, 'type': "doc", 'content': [
{'type': "panel", 'attrs': {'panelType': "warning"}, 'content': [
{'type': 'paragraph', 'content': [
{'type': 'text', 'text': 'Alert', 'marks': [
{'type': 'strong'}
]},
{'type': 'text', 'text': ': we found something. '},
{'type': 'text', 'text': 'Link', 'marks': [
{'type': 'link', 'attrs': {'href': 'http://stride.com'}}
]}
]}
]}
]}}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json',
'Authorization': 'Bearer {}'.format(rule['stride_access_token'])},
verify=True,
proxies=None
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_hipchat_body_size_limit_text():
rule = {
'name': 'Test Rule',
'type': 'any',
'hipchat_auth_token': 'token',
'hipchat_room_id': 'room_id',
'hipchat_message_format': 'text',
'alert_subject': 'Cool subject',
'alert_text': 'Alert: we found something.\n\n{message}',
'alert_text_type': 'alert_text_only',
'alert': [],
'alert_text_kw': {
'@timestamp': 'time',
'message': 'message',
},
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = HipChatAlerter(rule)
match = {
'@timestamp': '2018-01-01T00:00:00',
'message': 'foo bar\n' * 5000,
}
body = alert.create_alert_body([match])
assert len(body) <= 10000
def test_hipchat_body_size_limit_html():
rule = {
'name': 'Test Rule',
'type': 'any',
'hipchat_auth_token': 'token',
'hipchat_room_id': 'room_id',
'hipchat_message_format': 'html',
'alert_subject': 'Cool subject',
'alert_text': 'Alert: we found something.\n\n{message}',
'alert_text_type': 'alert_text_only',
'alert': [],
'alert_text_kw': {
'@timestamp': 'time',
'message': 'message',
},
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = HipChatAlerter(rule)
match = {
'@timestamp': '2018-01-01T00:00:00',
'message': 'foo bar\n' * 5000,
}
body = alert.create_alert_body([match])
assert len(body) <= 10000
def test_alerta_no_auth(ea):
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'timestamp_field': '@timestamp',
'alerta_api_skip_ssl': True,
'alerta_attributes_keys': ["hostname", "TimestampEvent", "senderIP"],
'alerta_attributes_values': ["%(key)s", "%(logdate)s", "%(sender_ip)s"],
'alerta_correlate': ["ProbeUP", "ProbeDOWN"],
'alerta_event': "ProbeUP",
'alerta_group': "Health",
'alerta_origin': "Elastalert",
'alerta_severity': "debug",
'alerta_text': "Probe %(hostname)s is UP at %(logdate)s GMT",
'alerta_value': "UP",
'type': 'any',
'alerta_use_match_timestamp': True,
'alert': 'alerta'
}
match = {
'@timestamp': '2014-10-10T00:00:00',
# 'key': ---- missing field on purpose, to verify that simply the text is left empty
# 'logdate': ---- missing field on purpose, to verify that simply the text is left empty
'sender_ip': '1.1.1.1',
'hostname': 'aProbe'
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = AlertaAlerter(rule)
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
"origin": "Elastalert",
"resource": "elastalert",
"severity": "debug",
"service": ["elastalert"],
"tags": [],
"text": "Probe aProbe is UP at <MISSING VALUE> GMT",
"value": "UP",
"createTime": "2014-10-10T00:00:00.000000Z",
"environment": "Production",
"rawData": "Test Alerta rule!\n\n@timestamp: 2014-10-10T00:00:00\nhostname: aProbe\nsender_ip: 1.1.1.1\n",
"timeout": 86400,
"correlate": ["ProbeUP", "ProbeDOWN"],
"group": "Health",
"attributes": {"senderIP": "1.1.1.1", "hostname": "<MISSING VALUE>", "TimestampEvent": "<MISSING VALUE>"},
"type": "elastalert",
"event": "ProbeUP"
}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
headers={
'content-type': 'application/json'},
verify=False
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_alerta_auth(ea):
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'alerta_api_key': '123456789ABCDEF',
'timeframe': datetime.timedelta(hours=1),
'timestamp_field': '@timestamp',
'alerta_severity': "debug",
'type': 'any',
'alerta_use_match_timestamp': True,
'alert': 'alerta'
}
match = {
'@timestamp': '2014-10-10T00:00:00',
'sender_ip': '1.1.1.1',
'hostname': 'aProbe'
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = AlertaAlerter(rule)
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
verify=True,
headers={
'content-type': 'application/json',
'Authorization': 'Key {}'.format(rule['alerta_api_key'])})
def test_alerta_new_style(ea):
rule = {
'name': 'Test Alerta rule!',
'alerta_api_url': 'http://elastalerthost:8080/api/alert',
'timeframe': datetime.timedelta(hours=1),
'timestamp_field': '@timestamp',
'alerta_attributes_keys': ["hostname", "TimestampEvent", "senderIP"],
'alerta_attributes_values': ["{hostname}", "{logdate}", "{sender_ip}"],
'alerta_correlate': ["ProbeUP", "ProbeDOWN"],
'alerta_event': "ProbeUP",
'alerta_group': "Health",
'alerta_origin': "Elastalert",
'alerta_severity': "debug",
'alerta_text': "Probe {hostname} is UP at {logdate} GMT",
'alerta_value': "UP",
'alerta_new_style_string_format': True,
'type': 'any',
'alerta_use_match_timestamp': True,
'alert': 'alerta'
}
match = {
'@timestamp': '2014-10-10T00:00:00',
# 'key': ---- missing field on purpose, to verify that simply the text is left empty
# 'logdate': ---- missing field on purpose, to verify that simply the text is left empty
'sender_ip': '1.1.1.1',
'hostname': 'aProbe'
}
rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = AlertaAlerter(rule)
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
"origin": "Elastalert",
"resource": "elastalert",
"severity": "debug",
"service": ["elastalert"],
"tags": [],
"text": "Probe aProbe is UP at <MISSING VALUE> GMT",
"value": "UP",
"createTime": "2014-10-10T00:00:00.000000Z",
"environment": "Production",
"rawData": "Test Alerta rule!\n\n@timestamp: 2014-10-10T00:00:00\nhostname: aProbe\nsender_ip: 1.1.1.1\n",
"timeout": 86400,
"correlate": ["ProbeUP", "ProbeDOWN"],
"group": "Health",
"attributes": {"senderIP": "1.1.1.1", "hostname": "aProbe", "TimestampEvent": "<MISSING VALUE>"},
"type": "elastalert",
"event": "ProbeUP"
}
mock_post_request.assert_called_once_with(
alert.url,
data=mock.ANY,
verify=True,
headers={
'content-type': 'application/json'}
)
assert expected_data == json.loads(
mock_post_request.call_args_list[0][1]['data'])
def test_alert_subject_size_limit_no_args(ea):
rule = {
'name': 'test_rule',
'type': mock_rule(),
'owner': 'the_owner',
'priority': 2,
'alert_subject': 'A very long subject',
'alert_subject_max_len': 5
}
alert = Alerter(rule)
alertSubject = alert.create_custom_title([{'test_term': 'test_value', '@timestamp': '2014-10-31T00:00:00'}])
assert 5 == len(alertSubject)
def test_alert_subject_size_limit_with_args(ea):
rule = {
'name': 'test_rule',
'type': mock_rule(),
'owner': 'the_owner',
'priority': 2,
'alert_subject': 'Test alert for {0} {1}',
'alert_subject_args': ['test_term', 'test.term'],
'alert_subject_max_len': 6
}
alert = Alerter(rule)
alertSubject = alert.create_custom_title([{'test_term': 'test_value', '@timestamp': '2014-10-31T00:00:00'}])
assert 6 == len(alertSubject)
| 36.700869
| 131
| 0.585299
|
4a0dd03af234bfe74680ebf2db6eb9bd802ac142
| 5,878
|
py
|
Python
|
chemmltoolkit/proteins/protein.py
|
Andy-Wilkinson/ChemMLToolk
|
83efc7ea66d2def860a3e04ccd70d77fb689fddc
|
[
"MIT"
] | 1
|
2019-10-30T03:43:24.000Z
|
2019-10-30T03:43:24.000Z
|
chemmltoolkit/proteins/protein.py
|
Andy-Wilkinson/ChemMLToolk
|
83efc7ea66d2def860a3e04ccd70d77fb689fddc
|
[
"MIT"
] | 2
|
2021-11-28T21:09:30.000Z
|
2021-11-28T21:09:39.000Z
|
chemmltoolkit/proteins/protein.py
|
Andy-Wilkinson/ChemMLToolkit
|
83efc7ea66d2def860a3e04ccd70d77fb689fddc
|
[
"MIT"
] | null | null | null |
from __future__ import annotations
from typing import Generator, List, Optional, TextIO, Tuple, Union
import gzip
from enum import Flag
from pathlib import Path
import Bio.PDB as biopdb
from Bio.PDB.Structure import Structure as bpStructure
from Bio.PDB.Chain import Chain as bpChain
from Bio.PDB.Residue import Residue as bpResidue
from Bio.PDB.Polypeptide import standard_aa_names
from Bio.PDB.Polypeptide import three_to_one
import oddt
class ResidueType(Flag):
RESIDUE = 1
HETERORESIDUE = 2
WATER = 4
ALL = RESIDUE | HETERORESIDUE | WATER
def get_id_str(self):
return ' ' if ResidueType.RESIDUE in self else '' + \
'H' if ResidueType.HETERORESIDUE in self else '' + \
'W' if ResidueType.HETERORESIDUE in self else ''
def _save(entity: Union[Protein, Chain, Residue],
filename: Union[str, Path, TextIO]) -> None:
if isinstance(filename, Path):
filename = str(filename)
io = biopdb.PDBIO()
io.set_structure(entity.as_biopython())
io.save(filename)
class Protein():
def __init__(self, id: str):
self.id = id
self.filename: Optional[Path] = None
self._biopython: Optional[bpStructure] = None
self._oddt: Optional[oddt.toolkit.Molecule] = None
@property
def name(self) -> str:
return self.id
def as_biopython(self) -> bpStructure:
if not self._biopython:
if self.filename:
file_open = gzip.open if self.filename.suffix == '.gz' \
else open
with file_open(self.filename, 'rt', encoding='ascii') as file:
parser = biopdb.PDBParser()
self._biopython = parser.get_structure(None, file)
else:
raise Exception('No filename is specified.')
return self._biopython
def as_oddt(self) -> oddt.toolkit.Molecule:
if not self._oddt:
if self.filename:
mol = next(oddt.toolkit.readfile('pdb', str(self.filename)))
mol.protein = True
self._oddt = mol
else:
raise Exception('No filename is specified.')
return self._oddt
def get_chain(self, chain_id: str) -> Chain:
return Chain(self, chain_id)
def get_chains(self) -> Generator[Chain, None, None]:
chains = self.as_biopython().get_chains()
return (Chain(self, c.id, biopython=c) for c in chains)
def save(self, filename: Union[str, Path, TextIO]):
_save(self, filename)
@staticmethod
def from_file(filename: Union[str, Path]) -> Protein:
if isinstance(filename, str):
filename = Path(filename)
filename_unzip = filename.stem if filename.suffix in ['.gz'] \
else filename
name = Path(filename_unzip).stem
protein = Protein(name)
protein.filename = filename
return protein
class Chain():
def __init__(self, protein: Protein, id: str,
biopython: Optional[bpChain] = None):
self.protein = protein
self.id = id
self._biopython = biopython
@property
def name(self) -> str:
return f'{self.protein.name}_{self.id}'
def as_biopython(self) -> bpChain:
if not self._biopython:
structure = self.protein.as_biopython()
chains = [c for c in structure.get_chains() if c.id == self.id]
self._biopython = chains[0]
return self._biopython
def get_residue(self,
residue_number: int) -> Optional[Residue]:
for r in self.as_biopython().get_residues():
if r.id[1] == residue_number:
return Residue(self, r.id, biopython=r)
return None
def get_residues(self,
residue_type: ResidueType = ResidueType.ALL,
residue_names: Optional[List[str]] = None,
) -> Generator[Residue, None, None]:
def filter(r: bpResidue):
return r.id[0][0] in residue_ids \
and (r.resname in residue_names if residue_names else True)
residue_ids = residue_type.get_id_str()
residues = self.as_biopython().get_residues()
return (Residue(self, r.id, biopython=r) for r in residues
if filter(r))
def get_sequence(self):
def _three_to_one(s: str):
return three_to_one(s) if s in standard_aa_names else '?'
residues = self.as_biopython().get_residues()
sequence = [_three_to_one(residue.get_resname())
for residue in residues]
sequence = ''.join(sequence)
return sequence
def save(self, filename: Union[str, Path, TextIO]):
_save(self, filename)
def __repr__(self):
return f'<Chain id={self.id}>'
class Residue():
def __init__(self, chain: Chain, id: Tuple[str, int, str],
biopython: Optional[bpResidue] = None):
self.chain = chain
self.id = id
self._biopython = biopython
@property
def name(self) -> str:
return f'{self.chain.name}_{self.residue_id}'
@property
def num_atoms(self):
return sum(1 for _ in self.as_biopython().get_atoms())
@property
def residue_id(self):
return f'{self.residue_name}{self.id[1]}'
@property
def residue_name(self):
return self.as_biopython().resname
def as_biopython(self) -> bpResidue:
if not self._biopython:
chain = self.chain.as_biopython()
residues = [r for r in chain.get_residues() if r.id == self.id]
self._biopython = residues[0]
return self._biopython
def save(self, filename: Union[str, Path, TextIO]):
_save(self, filename)
def __repr__(self):
return f'<Residue id={self.id}>'
| 30.774869
| 78
| 0.604287
|
4a0dd1552f0674c42d95c7916bf7cd3dd6363c6e
| 992
|
py
|
Python
|
non-tts-utilities/ttslua-file-generator/lib/files.py
|
larikk/TTS-YGO
|
8c1718a01e97e9e972ba0c16c47d14c56354b5d5
|
[
"MIT"
] | 1
|
2022-03-31T01:18:01.000Z
|
2022-03-31T01:18:01.000Z
|
non-tts-utilities/ttslua-file-generator/lib/files.py
|
larikk/TTS-YGO
|
8c1718a01e97e9e972ba0c16c47d14c56354b5d5
|
[
"MIT"
] | null | null | null |
non-tts-utilities/ttslua-file-generator/lib/files.py
|
larikk/TTS-YGO
|
8c1718a01e97e9e972ba0c16c47d14c56354b5d5
|
[
"MIT"
] | null | null | null |
import os
import re
import inspect
imageMappingsFolder = "../../../ygo-assets/product-textures/mappings/"
def write(folder, name, content):
if folder[-1] != "/": folder += "/"
path = folder + name
with open(path, "w") as f: f.write(content)
def compileDeckList(folder, prefix):
files = sorted(os.listdir(folder))
files = filter(lambda f: re.match(r"^[0-9]{3}-.+\.ttslua$", f), files)
files = map(lambda f: f.split(".")[0], files)
files = map(lambda f: f'require("TTS-YGO/{prefix}/{f}"),', files)
sep = "\n "
content = f"""\
-- autogenerated
return {{
{sep.join(files)}
}}
"""
write(folder, "_all.ttslua", content)
def getImageMappings(file):
lines = []
with open(imageMappingsFolder + file, "r") as f:
lines = [l.rstrip() for l in f.readlines()]
mappings = dict()
for l in lines:
vs = l.split(",")
code = vs[0].split("-")[1]
image = vs[1]
mappings[code] = image
return mappings
| 24.8
| 74
| 0.577621
|
4a0dd15594686cab7be6bbbe0c70c7935944cdc0
| 2,287
|
py
|
Python
|
test/ryu/vsw-602_mp_group_stats.py
|
iMasaruOki/lagopus
|
69c303b65acbc2d4661691c190c42946654de1b3
|
[
"Apache-2.0"
] | 281
|
2015-01-06T13:36:14.000Z
|
2022-03-14T03:29:46.000Z
|
test/ryu/vsw-602_mp_group_stats.py
|
iMasaruOki/lagopus
|
69c303b65acbc2d4661691c190c42946654de1b3
|
[
"Apache-2.0"
] | 115
|
2015-01-06T11:09:21.000Z
|
2020-11-26T11:44:23.000Z
|
test/ryu/vsw-602_mp_group_stats.py
|
lagopus/lagopus
|
69c303b65acbc2d4661691c190c42946654de1b3
|
[
"Apache-2.0"
] | 108
|
2015-01-06T05:12:01.000Z
|
2022-01-02T03:28:50.000Z
|
from ryu.base.app_manager import RyuApp
from ryu.controller.ofp_event import EventOFPSwitchFeatures
from ryu.controller.ofp_event import EventOFPGroupStatsReply
from ryu.controller.handler import set_ev_cls
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.ofproto.ofproto_v1_2 import OFPG_ANY
from ryu.ofproto.ofproto_v1_3 import OFP_VERSION
from ryu.lib.mac import haddr_to_bin
class App(RyuApp):
OFP_VERSIONS = [OFP_VERSION]
def __init__(self, *args, **kwargs):
super(App, self).__init__(*args, **kwargs)
@set_ev_cls(EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
[self.install_sample(datapath, n) for n in [0]]
def install_sample(self, datapath, table_id):
parser = datapath.ofproto_parser
ofproto = datapath.ofproto
self.logger.info("=== start ===")
for i in range(10000):
port = 1
max_len = 2000
actions = [parser.OFPActionOutput(port, max_len)]
weight = 100
watch_port = 0
watch_group = 0
buckets = [parser.OFPBucket(weight, watch_port, watch_group,
actions)]
group_id = i
req = parser.OFPGroupMod(datapath, ofproto.OFPGC_ADD,
ofproto.OFPGT_SELECT, group_id, buckets)
datapath.send_msg(req)
self.logger.info("=== end ===")
req = parser.OFPGroupStatsRequest(datapath, 0, ofproto.OFPG_ALL)
datapath.send_msg(req)
@set_ev_cls(EventOFPGroupStatsReply, MAIN_DISPATCHER)
def group_stats_reply_handler(self, ev):
global c
groups = []
for stat in ev.msg.body:
groups.append('length=%d group_id=%d '
'ref_count=%d packet_count=%d byte_count=%d '
'duration_sec=%d duration_nsec=%d' %
(stat.length, stat.group_id,
stat.ref_count, stat.packet_count,
stat.byte_count, stat.duration_sec,
stat.duration_nsec))
self.logger.info('GroupStats: %s', groups)
| 38.116667
| 77
| 0.615654
|
4a0dd21db451f9b3205175ed56207d6253dd1adf
| 422
|
py
|
Python
|
test/commands/TSID_ColoradoWaterHBGuest/ironpython/test.py
|
OpenCDSS/cdss-app-tstool-test
|
38f03731b4c76cf0ff2a354752a8cf4da4a2815b
|
[
"CC-BY-4.0"
] | null | null | null |
test/commands/TSID_ColoradoWaterHBGuest/ironpython/test.py
|
OpenCDSS/cdss-app-tstool-test
|
38f03731b4c76cf0ff2a354752a8cf4da4a2815b
|
[
"CC-BY-4.0"
] | 74
|
2019-02-08T08:37:59.000Z
|
2022-03-24T22:17:22.000Z
|
test/commands/TSID_ColoradoWaterHBGuest/ironpython/test.py
|
OpenCDSS/cdss-app-tstool-test
|
38f03731b4c76cf0ff2a354752a8cf4da4a2815b
|
[
"CC-BY-4.0"
] | null | null | null |
# Test web services
import wsdlprovider as wsdl
url = "http://www.dwr.state.co.us/HBGuest/HBGuestWebService.asmx?WSDL"
service = wsdl.GetWebservice(url)
def getAuthentication():
header = service.HBAuthenticationHeader()
header.Token = "WirQg1zN"
return header
# Main code
status = service.HbStatusHeader()
districtArray = service.GetHBGuestWaterDistrictCompletedEventHandler(getAuthentication(), status)
| 23.444444
| 97
| 0.777251
|
4a0dd3d06610015a5a57dd6277aeaceb753bc5b5
| 12,828
|
py
|
Python
|
training/train_cancer_cnn_Resnet_pretrained.py
|
ramon349/quip_cancer_segmentation
|
e5299a4fa572d5b420670f4960a7f7bf3b51af3f
|
[
"BSD-3-Clause"
] | 11
|
2019-06-14T16:51:05.000Z
|
2022-03-02T14:14:43.000Z
|
training/train_cancer_cnn_Resnet_pretrained.py
|
ramon349/quip_cancer_segmentation
|
e5299a4fa572d5b420670f4960a7f7bf3b51af3f
|
[
"BSD-3-Clause"
] | 4
|
2019-06-14T21:15:22.000Z
|
2019-07-09T06:49:22.000Z
|
training/train_cancer_cnn_Resnet_pretrained.py
|
ramon349/quip_cancer_segmentation
|
e5299a4fa572d5b420670f4960a7f7bf3b51af3f
|
[
"BSD-3-Clause"
] | 8
|
2019-06-14T19:44:45.000Z
|
2021-06-16T08:01:58.000Z
|
import argparse
from torchvision import transforms
import time
import os, sys
from time import strftime
from sklearn.metrics import mean_squared_error, accuracy_score, hamming_loss, roc_curve, auc, f1_score
from tumor_utils import *
import copy
from torch.utils.data import DataLoader, Dataset
import random
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=1e-2, type=float, help='learning rate')
parser.add_argument('--net_type', default='RESNET_34_cancer_350px_lr_1e-2_decay_5_jitter_val6slides_harder_tcga', type=str, help='model')
parser.add_argument('--color', default = 'none', type = str, help='color normalization option')
parser.add_argument('--depth', default=34, choices=[18, 34, 50,101, 152], type=int, help='depth of model')
parser.add_argument('--weight_decay', default=1e-4, type=float, help='weight decay')
parser.add_argument('--finetune', '-f', action='store_true', help='Fine tune pretrained model')
parser.add_argument('--trainer', default='adam', type=str, help='optimizer')
parser.add_argument('--batch_size', default=256, type=int)
parser.add_argument('--num_workers', default=8, type=int)
parser.add_argument('--num_epochs', default=20, type=int, help='Number of epochs in training')
parser.add_argument('--lr_decay_epoch', default=10, type = int)
parser.add_argument('--max_lr_decay', default = 60, type = int)
parser.add_argument('--check_after', default=1,
type=int, help='check the network after check_after epoch')
parser.add_argument('--train_from', default=1,
choices=[0, 1, 2],
type=int,
help="training from beginning (1) or from the most recent ckpt (0)")
parser.add_argument('--frozen_until', '-fu', type=int, default=20,
help="freeze until --frozen_util block")
parser.add_argument('--val_ratio', default=0.1, type=float,
help="number of training samples per class")
parser.add_argument('--note', type=str, default='none', help="note while running the code")
parser.add_argument('--data', type=str, default='none', help="path to the folder containing all subfolders of training/testing data", required=False)
parser.add_argument('--data_list', type=str, default='none', help="text file containing the training/testing folder", required=False)
args = parser.parse_args()
rand_seed = 26700
if rand_seed is not None:
np.random.seed(rand_seed)
torch.manual_seed(rand_seed)
torch.cuda.manual_seed(rand_seed)
use_gpu = torch.cuda.is_available()
print('Using GPU: ', use_gpu)
device = torch.device("cuda:0")
classn = 1
freq_print = 100 # print stats every {} batches
training_data_path = '/data01/shared/hanle/tumor_project/breast_cancer_40X/cancer_pos1'
dataset_list = os.path.join(training_data_path, 'tumor_data_list.txt')
dataset_list = os.path.join(training_data_path, dataset_list)
print(dataset_list)
###########
print('DataLoader ....')
def mean_std(type = 'none'):
if type == 'vahadane':
mean = [0.8372, 0.6853, 0.8400]
std = [0.1135, 0.1595, 0.0922]
elif type == 'macenko':
mean = [0.8196, 0.6938, 0.8131]
std = [0.1417, 0.1707, 0.1129]
elif type == 'reinhard':
mean = [0.8364, 0.6738, 0.8475]
std = [0.1315, 0.1559, 0.1084]
elif type == 'macenkoMatlab':
mean = [0.7805, 0.6230, 0.7068]
std = [0.1241, 0.1590, 0.1202]
else:
mean = [0.7238, 0.5716, 0.6779]
std = [0.1120, 0.1459, 0.1089]
return mean, std
mean, std = mean_std(args.color)
input_size = 224
data_transforms = {
'train': transforms.Compose([
transforms.RandomRotation(22),
transforms.CenterCrop(350),
transforms.Scale(input_size),
transforms.RandomHorizontalFlip(), # simple data augmentation
transforms.RandomVerticalFlip(),
transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.1),
transforms.ToTensor(),
transforms.Normalize(mean, std)]),
'val': transforms.Compose([
transforms.CenterCrop(350),
transforms.Scale(input_size),
transforms.ToTensor(),
transforms.Normalize(mean, std)
]),
}
img_trains, img_vals = load_imgs_files(classn, dataset_list = dataset_list, training_data_path = training_data_path, color = args.color)
# for demo training, small number of training/val. Delete these when running real training
random.shuffle(img_trains)
random.shuffle(img_vals)
img_trains, img_vals = img_trains[:10000], img_vals[:1000]
# end of demo
train_set = data_loader(img_trains, transform = data_transforms['train'])
train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=False)
val_set = data_loader(img_vals, transform = data_transforms['val'])
val_loader = DataLoader(val_set, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=False)
def val_fn_epoch(classn = 1, val_fn = None, crit = None, val_loader = None):
Pr = np.empty(shape = (20000, classn), dtype = np.int32)
Or = np.empty(shape = (20000, classn), dtype = np.float32)
Tr = np.empty(shape = (20000, classn), dtype = np.int32)
def softmax_np(x):
x = x - np.max(x, 1, keepdims=True)
x = np.exp(x) / (np.sum(np.exp(x), 1, keepdims=True))
return x
nline = 0
running_loss = 0.0
with torch.no_grad():
for ix, batch in enumerate(val_loader):
if (len(val_loader.dataset) - nline) < 5: continue
inputs, targets = batch
inputs = Variable(inputs.to(device))
targets = Variable(targets.to(device))
output = val_fn(inputs)
if type(output) == tuple:
output,_ = output
N = output.size(0)
loss = crit(output, targets)
running_loss += loss.item() * N
_, pred = torch.max(output.data, 1)
output = output.data.cpu().numpy()
pred = pred.data.cpu().numpy()
output = softmax_np(output)[:,1]
Pr[nline:nline+N] = pred.reshape(-1, 1)
Or[nline:nline+N] = output.reshape(-1, 1)
Tr[nline:nline+N] = targets.data.cpu().numpy().reshape(-1, 1)
nline += N
Pr = Pr[:nline]
Or = Or[:nline]
Tr = Tr[:nline]
val_ham = (1 - hamming_loss(Tr, Pr))
val_acc = accuracy_score(Tr, Pr)
f1 = f1_score(Tr, Pr, average='binary')
return val_ham, val_acc, f1, Pr, Or, Tr, running_loss/nline
def confusion_matrix(Or, Tr, thres):
tpos = np.sum((Or>=thres) * (Tr==1))
tneg = np.sum((Or< thres) * (Tr==0))
fpos = np.sum((Or>=thres) * (Tr==0))
fneg = np.sum((Or< thres) * (Tr==1))
return tpos, tneg, fpos, fneg
def auc_roc(Pr, Tr):
fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)
return auc(fpr, tpr)
def train_model(model, criterion = None, num_epochs=100, train_loader = train_loader, val_loader = val_loader):
best_auc = 0
best_epoch = 0
start_training = time.time()
for epoch in range(num_epochs):
start = time.time()
if epoch < 4: lr = args.lr
elif epoch < 8: lr = args.lr/2
elif epoch < 10: lr = args.lr/10
elif epoch < 15: lr = args.lr / 50
else: lr = args.lr/100
if epoch >= 1:
for param in model.parameters():
param.requires_grad = True
optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=lr, momentum=0.9, weight_decay=args.weight_decay)
print('Epoch {}/{}'.format(epoch + 1, num_epochs))
print('lr: {:.6f}'.format(lr))
print('-' * 50)
for phase in ['train']:
if phase == 'train':
data_loader = train_loader
model.train(True)
else:
data_loader = val_loader
model.train(False)
running_loss = 0.0
running_corrects = 0
N_tot = 0
for ix, data in enumerate(data_loader):
if (len(data_loader.dataset) - N_tot) < 3: continue
inputs, labels = data
inputs = Variable(inputs.to(device))
labels = Variable(labels.to(device))
optimizer.zero_grad()
outputs = model(inputs)
if type(outputs) == tuple: # for inception_v3 output
outputs,_ = outputs
_, preds = torch.max(outputs.data, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer.step()
N_tot += outputs.size(0)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if (ix + 1) % freq_print == 0:
print('| Epoch:[{}][{}/{}]\tTrain_Loss: {:.4f}\tAccuracy: {:.4f}\tTime: {:.2f} mins'.format(epoch + 1, ix + 1,
len(data_loader.dataset)//args.batch_size,
running_loss / N_tot, running_corrects.item() / N_tot, (time.time() - start)/60.0))
sys.stdout.flush()
############ VALIDATION #############################################
if (epoch + 1) % args.check_after == 0:
model.eval()
start = time.time()
val_ham, val_acc, f1, Pr, Or, Tr, val_loss = val_fn_epoch(classn = 1, val_fn = model, crit = criterion, val_loader = val_loader)
tpos0, tneg0, fpos0, fneg0 = confusion_matrix(Or, Tr, 0.4)
tpos1, tneg1, fpos1, fneg1 = confusion_matrix(Or, Tr, 0.5)
tpos2, tneg2, fpos2, fneg2 = confusion_matrix(Or, Tr, 0.6)
val_auc = auc_roc(Or, Tr)
print("Epoch: {}\tVal_Loss: {:.4f}\tAccuracy: {:.4f}\tAUC: {:.4f}\tF1-score: {:.4f}\t{}/{}/{}/{}\t{}/{}/{}/{}\t{}/{}/{}/{}\t{}/{}\t{:.3f}mins".format(
(epoch + 1), val_loss, val_acc, val_auc, f1,
tpos0, tneg0, fpos0, fneg0,
tpos1, tneg1, fpos1, fneg1,
tpos2, tneg2, fpos2, fneg2,
epoch + 1, num_epochs, (time.time() - start)/60.0))
start = time.time()
# deep copy the model
if f1 > best_auc and epoch > 2:
print('Saving model')
best_auc = f1
best_epoch = epoch
best_model = copy.deepcopy(model)
state = {
'model': best_model,
'auc': best_auc,
'args': args,
'lr': lr,
'saved_epoch': epoch,
}
if not os.path.isdir('checkpoint'):
os.mkdir('checkpoint')
save_point = './checkpoint/'
if not os.path.isdir(save_point):
os.mkdir(save_point)
saved_model_fn = args.net_type + '_' + args.color + '_' + strftime('%m%d_%H%M')
torch.save(state, save_point + saved_model_fn + '_' + str(best_auc) + '_' + str(epoch) + '.t7')
print('=======================================================================')
time_elapsed = time.time() - start_training
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f} at epoch: {}'.format(best_auc, best_epoch))
def main():
sys.setrecursionlimit(10000)
with open(os.path.basename(__file__)) as f:
codes = f.readlines()
print('\n\n' + '=' * 20 + os.path.basename(__file__) + '=' * 20)
for c in codes:
print(c[:-1])
with open('tumor_utils.py') as f:
codes = f.readlines()
print('\n\n' + '=' * 20 + 'tumor_utils.py' + '=' * 20)
for c in codes:
print(c[:-1])
with open('resnet.py') as f:
codes = f.readlines()
print('\n\n' + '=' * 20 + 'resnet.py' + '=' * 20)
for c in codes:
print(c[:-1])
model = models.resnet34(pretrained=True)
for param in model.parameters():
param.requires_grad = False
num_in = model.fc.in_features
model.fc = nn.Linear(num_in, 2)
model = model.to(device)
model = torch.nn.DataParallel(model, device_ids=[0,1])
cudnn.benchmark = True
print(model)
##################
print('Start training ... ')
criterion = nn.CrossEntropyLoss().to(device)
train_model(model, criterion, num_epochs=args.num_epochs, train_loader=train_loader, val_loader=val_loader)
if __name__ == "__main__":
main()
| 38.872727
| 166
| 0.58154
|
4a0dd4c4a84298d7f668ae37b3c52299fc6ac5cc
| 10,672
|
py
|
Python
|
template_email_manager/tasks.py
|
mbacicc/django-template-email-manager
|
85a5b11a0b9c4d166bd8dec569db573ca317ea61
|
[
"MIT"
] | null | null | null |
template_email_manager/tasks.py
|
mbacicc/django-template-email-manager
|
85a5b11a0b9c4d166bd8dec569db573ca317ea61
|
[
"MIT"
] | 19
|
2021-05-06T08:09:23.000Z
|
2022-03-21T02:09:06.000Z
|
template_email_manager/tasks.py
|
mbacicc/django-template-email-manager
|
85a5b11a0b9c4d166bd8dec569db573ca317ea61
|
[
"MIT"
] | null | null | null |
from background_task import background
from django.contrib.auth.models import User
from .models import *
import logging
from django.db.models import Q
from .manager import *
from django.utils.timezone import now
from datetime import datetime
from django.utils import timezone
from datetime import timedelta
from django.shortcuts import render
from django.template import Template, Context
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from smtplib import SMTPException
from email.mime.image import MIMEImage
import os
logger = logging.getLogger('django.email_manager.background_tasks')
timeout_in_progress_expiration_seconds = 600
@background(schedule=10)
# @background()
def background_process_emails():
# Attempt Sending newly created emails and failed emails that are not expired
emails = EmailQueue.objects.filter(Q(status=EmailQueue.EmailQueueStatus.READY) | Q(status=EmailQueue.EmailQueueStatus.FAILED,retry_at__lte=now()))
for email in emails:
attempt_send_email(email)
# Send to failed in progress email that are there for long time
time_threshold = datetime.now(timezone.utc) - timedelta(seconds=timeout_in_progress_expiration_seconds)
emails = EmailQueue.objects.filter(status=EmailQueue.EmailQueueStatus.INPROGRESS, last_operation__lte=time_threshold)
for email in emails:
fail_email(email, 'expired, in progress for more than ' + str(timeout_in_progress_expiration_seconds) + ' seconds')
return True
def attempt_send_email(email):
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.INPROGRESS,
send_attempt = 0,
error_code = 0,
log_info = 'Starting composing e-mail message'
)
eql.save()
email_config = email.account
if email_config:
if email_config.backend == EmailConfig.EmailConfigBackendChoices.SMTP:
email_backend = SMTPEmailBackend(host=email_config.host, port=email_config.port, username=email_config.username,
password=email_config.password, use_tls=email_config.use_tls, fail_silently=email_config.fail_silently)
else:
email_backend = ConsoleEmailBackend(fail_silently=email_config.fail_silently)
try:
email.status = EmailQueue.EmailQueueStatus.INPROGRESS
email.last_operation = datetime.now(timezone.utc)
email.save()
except:
pass
emailSubject = email.subject
emailOfSender = email.sender.address
emailOfRecipient = []
for to_address in email.to.all():
emailOfRecipient.append(to_address.name + " <" + to_address.address + ">")
emailBcc = []
for bcc_address in email.bcc.all():
emailBcc.append(bcc_address.name + " <" + bcc_address.address + ">")
headers={
"From": email.sender.name + " <" + email.sender.address + ">"
}
context = {}
for item in email.context_items.all():
cont_item = {
item.context_class.name : item.value
}
context.update(cont_item)
html_template_string = email.html_template.html_content
html_template = Template(html_template_string)
html_content = html_template.render(Context(context))
txt_template_string = email.html_template.text_alternate
txt_template = Template(txt_template_string)
text_content = txt_template.render(Context(context))
emailMessage = EmailMultiAlternatives(subject=emailSubject, body=text_content, from_email=emailOfSender,\
to=emailOfRecipient, bcc=emailBcc, reply_to=[emailOfSender,], headers=headers, connection=email_backend)
emailMessage.attach_alternative(html_content, "text/html")
success = True
try:
for image in email.html_template.images.all():
fp = open(os.path.join(settings.MEDIA_ROOT, image.image.name), 'rb')
msg_img = MIMEImage(fp.read())
fp.close()
msg_img.add_header('Content-ID', '<{}>'.format(image.name))
emailMessage.attach(msg_img)
except:
pass
try:
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.INPROGRESS,
send_attempt = 0,
error_code = 0,
log_info = 'Attempting e-mail send'
)
eql.save()
emailMessage.send(fail_silently=False)
pass
except SMTPException as e:
# print('There was an error sending an email: ', e)
# error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
success = False
try:
if email.send_attempts < email_config.max_attempts :
email.status = EmailQueue.EmailQueueStatus.FAILED
email.send_attempts += 1
email.retry_at = datetime.now(timezone.utc) + timedelta(seconds=email_config.default_attempts_wait + (email_config.default_attempts_wait_multiplier * email.send_attempts))
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.FAILED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'SMTP Error SMTPException ' + str(e.args)
)
eql.save()
else :
email.status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED
email.send_attempts += 1
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'SMTP Error SMTPException ' + str(e.args) + ' - canceling email send for max number of attempts'
)
eql.save()
except:
pass
return False
except SMTPDataError as e:
success = False
try:
if email.send_attempts < email_config.max_attempts :
email.status = EmailQueue.EmailQueueStatus.FAILED
email.send_attempts += 1
email.retry_at = datetime.now(timezone.utc) + timedelta(seconds=email_config.default_attempts_wait + (email_config.default_attempts_wait_multiplier * email.send_attempts))
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.FAILED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'SMTP Error SMTPDataError ' + str(e.args)
)
eql.save()
else :
email.status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED
email.send_attempts += 1
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'SMTP Error SMTPDataError ' + str(e.args) + ' - canceling email send for max number of attempts'
)
eql.save()
except:
pass
return False
except Exception as e:
print('There was an error sending an email: ', e)
try:
if email.send_attempts < email_config.max_attempts :
email.status = EmailQueue.EmailQueueStatus.FAILED
email.send_attempts += 1
email.retry_at = datetime.now(timezone.utc).strftime("%d/%m/%Y %H:%M:%S") + timedelta(seconds=email_config.default_attempts_wait + (email_config.default_attempts_wait_multiplier * email.send_attempts))
email.last_operation = datetime.now(timezone.utc)
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.FAILED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'Error ' + str(e.args)
)
eql.save()
else :
email.status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED
email.send_attempts += 1
email.last_operation = datetime.now(timezone.utc)
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.MAXATTEMPTSCANCELED,
send_attempt = 0,
error_code = int(e.args),
log_info = 'Error ' + str(e.args) + ' - canceling email send for max number of attempts'
)
eql.save()
except:
pass
success = False
return False
if success:
try:
email.status = EmailQueue.EmailQueueStatus.SENT
email.send_attempts += 1
email.sent_on = datetime.now(timezone.utc)
email.last_operation = datetime.now(timezone.utc)
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.SENT,
send_attempt = 0,
error_code = 0,
log_info = 'Message sent'
)
eql.save()
except:
pass
return True
def fail_email(email, reason):
email.status = EmailQueue.EmailQueueStatus.FAILED
email.last_operation = datetime.now(timezone.utc)
email.save()
eql = EmailQueueLog(
message = email,
status = EmailQueue.EmailQueueStatus.FAILED,
send_attempt = 0,
error_code = 0,
log_info = 'Failed: ' + reason
)
eql.save()
| 41.204633
| 222
| 0.564936
|
4a0dd5d323120c12373c701920bae38e763eeace
| 990
|
py
|
Python
|
server/FirebaseClient.py
|
owo/jitalk
|
2db2782282a2302b4cf6049030822734a6856982
|
[
"MIT"
] | 1
|
2020-06-22T14:28:41.000Z
|
2020-06-22T14:28:41.000Z
|
server/FirebaseClient.py
|
owo/jitalk
|
2db2782282a2302b4cf6049030822734a6856982
|
[
"MIT"
] | null | null | null |
server/FirebaseClient.py
|
owo/jitalk
|
2db2782282a2302b4cf6049030822734a6856982
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from firebase import firebase
class FirebaseClient(object):
"""docstring for FirebaseClient"""
_instance = None
def __init__(self):
if not FirebaseClient._instance:
FirebaseClient._instance = firebase.FirebaseApplication('https://ji-talk.firebaseio.com', None)
def getRooms(self):
return FirebaseClient._instance.get('/', None)
def getChat(self, roomID):
return FirebaseClient._instance.get('/', roomID)
def createRoom(self):
# could be handled by the front-end
# returns the room ID as a string in uni-8 unicoding
roomID = FirebaseClient._instance.post('/', "chatRoom")
return str(roomID['name'])
def postChat(self, roomID, username, text, originalText):
# roomID expected as a string
data = {'username': username, 'text': text, 'original': originalText}
return FirebaseClient._instance.post('/'+roomID, data)
if __name__ == "__main__":
print "You ran the client, nothing will happen. Exiting..."
| 26.756757
| 98
| 0.717172
|
4a0dd6c2b8695427ae86b4bc2b2e351e1368453f
| 17
|
py
|
Python
|
python-game/images__init__.py
|
rcook/ptool-templates
|
44ccc78594c2b5f277d29ade13f303447aafd36f
|
[
"MIT"
] | null | null | null |
python-game/images__init__.py
|
rcook/ptool-templates
|
44ccc78594c2b5f277d29ade13f303447aafd36f
|
[
"MIT"
] | null | null | null |
python-game/images__init__.py
|
rcook/ptool-templates
|
44ccc78594c2b5f277d29ade13f303447aafd36f
|
[
"MIT"
] | null | null | null |
{{py_copyright}}
| 8.5
| 16
| 0.705882
|
4a0dd7e63125e68626ae7d2164ebdeaa7177cb6f
| 2,576
|
py
|
Python
|
donkeycar/parts/cv.py
|
yaser-eftekhari/donkey
|
cd2216e906787097a67a11cb7825b6b3ae151ad7
|
[
"MIT"
] | 1
|
2018-07-12T17:38:57.000Z
|
2018-07-12T17:38:57.000Z
|
donkeycar/parts/cv.py
|
yaser-eftekhari/donkey
|
cd2216e906787097a67a11cb7825b6b3ae151ad7
|
[
"MIT"
] | 13
|
2018-04-26T08:13:36.000Z
|
2018-05-13T13:31:44.000Z
|
donkeycar/parts/cv.py
|
yaser-eftekhari/donkey
|
cd2216e906787097a67a11cb7825b6b3ae151ad7
|
[
"MIT"
] | 6
|
2017-11-22T06:11:16.000Z
|
2018-07-11T18:04:13.000Z
|
import cv2
import numpy as np
class ImgGreyscale():
def run(self, img_arr):
img_arr = cv2.cvtColor(img_arr, cv2.COLOR_RGB2GRAY)
return img_arr
class ImgCanny():
def __init__(self, low_threshold=60, high_threshold=110):
self.low_threshold = low_threshold
self.high_threshold = high_threshold
def run(self, img_arr):
return cv2.Canny(img_arr,
self.low_threshold,
self.high_threshold)
class ImgGaussianBlur():
def __init__(self, kernal_size=5):
self.kernal_size = kernal_size
def run(self, img_arr):
return cv2.GaussianBlur(img_arr,
(self.kernel_size, self.kernel_size), 0)
class ImgCrop:
"""
Crop an image to an area of interest.
"""
def __init__(self, top=0, bottom=0, left=0, right=0):
self.top = top
self.bottom = bottom
self.left = left
self.right = right
def run(self, img_arr):
height, width, _ = img_arr.shape
img_arr = img_arr[self.top:height-self.bottom,
self.left: width-self.right]
return img_arr
class ImgStack:
"""
Stack N previous images into a single N channel image, after converting each to grayscale.
The most recent image is the last channel, and pushes previous images towards the front.
"""
def __init__(self, num_channels=3):
self.img_arr = None
self.num_channels = num_channels
def rgb2gray(self, rgb):
'''
take a numpy rgb image return a new single channel image converted to greyscale
'''
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
def run(self, img_arr):
width, height, _ = img_arr.shape
gray = self.rgb2gray(img_arr)
if self.img_arr is None:
self.img_arr = np.zeros([width, height, self.num_channels], dtype=np.dtype('B'))
for ch in range(self.num_channels - 1):
self.img_arr[...,ch] = self.img_arr[...,ch+1]
self.img_arr[...,self.num_channels - 1:] = np.reshape(gray, (width, height, 1))
return self.img_arr
class Pipeline():
def __init__(self, steps):
self.steps = steps
def run(self, val):
for step in self.steps:
f = step['f']
args = step['args']
kwargs = step['kwargs']
val = f(val, *args, **kwargs)
return val
| 26.285714
| 94
| 0.561335
|
4a0dd8b9e8c326e5464a1cba4fedacd07f7fc96e
| 1,548
|
py
|
Python
|
conductor/conductor/tests/unit/solver/optimizer/test_random_pick.py
|
aalsudais/optf-has
|
c3e070b6ebc713a571c10d7a5cd87e5053047136
|
[
"Apache-2.0"
] | null | null | null |
conductor/conductor/tests/unit/solver/optimizer/test_random_pick.py
|
aalsudais/optf-has
|
c3e070b6ebc713a571c10d7a5cd87e5053047136
|
[
"Apache-2.0"
] | null | null | null |
conductor/conductor/tests/unit/solver/optimizer/test_random_pick.py
|
aalsudais/optf-has
|
c3e070b6ebc713a571c10d7a5cd87e5053047136
|
[
"Apache-2.0"
] | null | null | null |
#
# -------------------------------------------------------------------------
# Copyright (C) 2019 IBM.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -------------------------------------------------------------------------
#
"""Test class for optimizer random_pick.py"""
import unittest
from conductor.common.music import api
from conductor.solver.optimizer.random_pick import RandomPick
from oslo_config import cfg
from mock import patch
class TestRandomPick(unittest.TestCase):
@patch('conductor.solver.optimizer')
@patch('conductor.common.music.model.base.Base.table_create')
@patch('conductor.common.music.model.base.Base.insert')
def setUp(self, conf, _requests=None, _begin_time=None):
self.music = api.API()
self.conf = cfg.CONF
self.randomPick = RandomPick(self.conf)
def test_search(self):
_demand_list = list()
self.assertEqual(None, self.randomPick.search(_demand_list, '_request').current_demand)
if __name__ == '__main__':
unittest.main()
| 34.4
| 95
| 0.654393
|
4a0dd96c964aba0c30aa22e5fbd0380966b4ed9b
| 7,058
|
py
|
Python
|
onza/Modules/input.py
|
ladsantos/onza
|
a0afcdedef49bc883d37d2e015beb1a786d9e857
|
[
"MIT"
] | null | null | null |
onza/Modules/input.py
|
ladsantos/onza
|
a0afcdedef49bc883d37d2e015beb1a786d9e857
|
[
"MIT"
] | null | null | null |
onza/Modules/input.py
|
ladsantos/onza
|
a0afcdedef49bc883d37d2e015beb1a786d9e857
|
[
"MIT"
] | null | null | null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module computes input data for the lyman_alpha module.
"""
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import numpy as np
from itertools import product
__all__ = ["ParticleEnsemble", "DensityMap"]
# The general onza-input parent class
class _OnzaInput(object):
"""
Generalized `onza` input parent class.
Args:
cell_bin (`numpy.array`): The bins of the cell map.
vel_bin (`numpy.array`): Array containing the bins of Doppler shift
velocities in which to compute the spectrum.
cell_area (`numpy.array` or `None`, optional): 2-d array containing the
area of each cell. If `None`, it will be automatically computed from
`cell_bin`. It must have dimensions (N-1, N-1), where N is the
length of `cell_bin`. Default value is `None`.
px_physical_area (`float`): Physical area of a pixel, in km ** 2.
"""
def __init__(self, cell_bin, vel_bin, cell_area=None, cell_volume=None,
px_physical_area=40680159.61):
self.cell_bin = cell_bin
self.vel_bin = vel_bin
self.cell_volume = cell_volume
# Check if `cell_area` was provided
if cell_area is not None:
self.cell_area = cell_area
else:
# Compute the areas if they were not provided
self.cell_area = []
for i in range(len(self.cell_bin) - 1):
area = []
for j in range(len(self.cell_bin) - 1):
area.append((self.cell_bin[i + 1] - self.cell_bin[i]) *
(self.cell_bin[j + 1] - self.cell_bin[j]))
self.cell_area.append(area)
self.cell_area = np.array(self.cell_area) * px_physical_area
# Compute the `doppler_shift` array, which consists on the values of the
# Doppler shift away from the line center computed as the mean of two
# consecutive values in `vel_bin`
self.doppler_shift = []
for i in range(len(self.vel_bin) - 1):
self.doppler_shift.append((self.vel_bin[i] +
self.vel_bin[i + 1]) / 2)
self.doppler_shift = np.array(self.doppler_shift)
# Spectral resolution element, assuming uniform Doppler shift sampling
self.res_element = self.doppler_shift[1] - self.doppler_shift[0]
# Compute a density cube from an ensemble of pseudo-particles
class ParticleEnsemble(_OnzaInput):
"""
Compute the density cube (essentially an histogram) of an ensemble of
pseudo-particles. The third dimension is an histogram of velocities in the
line-of-sight direction.
Args:
positions (`numpy.array`): Positions of particles, in unit of pixels.
Shape of array must be (2, N), where N is the number of
pseudo-particles. Positions in lines 0, 1 and 2 must be x and y,
respectively.
velocities (`numpy.array`): Velocities of particles in the line-of-sight
direction, in km / s. Shape of array must be (N, ), where N is the
number of pseudo-particles.
cell_bin (array-like): The bins of the cell map.
vel_bin (array-like): Array containing the bins of Doppler shift
velocities in which to compute the spectrum.
cell_area (`numpy.array` or `None`, optional): 2-d array containing the
area of each cell. If `None`, it will be automatically computed from
`cell_bin`. It must have dimensions (N-1, N-1), where N is the
length of `cell_bin`. Default value is `None`.
atoms_per_particle (`float`, optional): Number of atoms per
pseudo-particle. Default value is 1E9.
"""
def __init__(self, positions, velocities, cell_bin, vel_bin, cell_area=None,
cell_volume=None, atoms_per_particle=1E9):
super(ParticleEnsemble, self).__init__(cell_bin, vel_bin, cell_area,
cell_volume)
self.pos = positions
self.vel = velocities
# Computing the histogram of particles in cells and velocity space
self.arr = np.array([self.vel[2], self.pos[0], self.pos[1]]).T
self.hist, self.hist_bins = np.histogramdd(sample=self.arr,
bins=[self.vel_bin,
self.cell_bin,
self.cell_bin])
self.hist *= atoms_per_particle
self.density = self.hist / self.cell_area
# The volume density can be useful sometimes
if self.cell_volume is not None:
hist_vol, hist_vol_bins = np.histogramdd(sample=self.pos,
bins=[self.cell_bin,
self.cell_bin,
self.cell_bin])
hist_vol *= atoms_per_particle
self.volume_density = hist_vol / self.cell_volume
# Compute a density cube from a 2-d density map and a fixed distribution of
# velocities
class DensityMap(_OnzaInput):
"""
Compute a density cube using as input a 2-d number density of particles map
and a fixed distribution of velocities of particles in the line of sight.
Args:
density_map (`numpy.array`): 2-d array containing the number densities
of particles inside a pixel.
vel_bin (`numpy.array`): Array containing the bins of Doppler shift
velocities in which to compute the spectrum.
vel_dist (`numpy.array`): Distribution of velocities of particles in
the direction of the line of sight.
cell_bin (array-like): The bins of the cell map.
cell_area (`numpy.array` or `None`, optional): 2-d array containing the
area of each cell. If `None`, it will be automatically computed from
`cell_bin`. It must have dimensions (N-1, N-1), where N is the
length of `cell_bin`. Default value is `None`.
"""
def __init__(self, density_map, vel_bin, vel_dist, cell_bin,
cell_area=None):
super(DensityMap, self).__init__(cell_bin, vel_bin, cell_area)
self.map = density_map
self.vel_dist = vel_dist
# Computing the coarse map (cells instead of pixels)
cells = np.arange(len(cell_bin))
self.map_coarse = np.zeros([len(cells) - 1, len(cells) - 1], float)
for i, j in product(cells[:-1], cells[:-1]):
self.map_coarse[i, j] = np.sum(self.map[cell_bin[i]:cell_bin[i + 1],
cell_bin[j]:cell_bin[j + 1]])
# Computing the density cube
self.density = np.array([vk * self.map_coarse * self.res_element
for vk in self.vel_dist]) / self.cell_area
| 41.034884
| 80
| 0.594361
|
4a0dd9f04adb59ce0ff909c059a4bcbb0a1a1c2f
| 31,741
|
py
|
Python
|
mmcls/datasets/pipelines/transforms3D.py
|
18152189583/mmclassification-3D
|
61bff05e893f123eae4497f7f1904f7447c65899
|
[
"Apache-2.0"
] | null | null | null |
mmcls/datasets/pipelines/transforms3D.py
|
18152189583/mmclassification-3D
|
61bff05e893f123eae4497f7f1904f7447c65899
|
[
"Apache-2.0"
] | null | null | null |
mmcls/datasets/pipelines/transforms3D.py
|
18152189583/mmclassification-3D
|
61bff05e893f123eae4497f7f1904f7447c65899
|
[
"Apache-2.0"
] | null | null | null |
import torch.nn.functional
from ..builder import PIPELINES
import numpy as np
import mmcv
from scipy.ndimage import binary_fill_holes
import nibabel as nib
from mmcv.utils import deprecated_api_warning
import skimage
#TODO to be eval
@PIPELINES.register_module()
class ResampleMedicalImage(object):
def __init__(self, img_scale=None, multiscale_mode='range',
ratio_range=None, keep_ratio=True):
if img_scale is None:
self.img_scale = img_scale
else:
if isinstance(img_scale, list):
self.img_scale = img_scale
else:
self.img_scale = [img_scale]
assert mmcv.is_list_of(self.img_scale, tuple)
if ratio_range is None:
assert self.img_scale is None or len(self.img_scale) == 1
else:
assert multiscale_mode.lower() in ['value', 'range']
self.multiscale_mode = multiscale_mode
self.ratio_range = ratio_range
self.keep_ratio = keep_ratio
@staticmethod
def random_select(img_scales):
assert mmcv.is_list_of(img_scales, tuple)
scale_idx = np.random.randint(len(img_scales))
img_scale = img_scales[scale_idx]
return img_scale, scale_idx
@staticmethod
def random_sample(img_scales):
"""Randomly sample an img_scale when ``multiscale_mode=='range'``.
Args:
img_scales (list[tuple]): Images scale range for sampling.
There must be two tuples in img_scales, which specify the lower
and upper bound of image scales.
Returns:
(tuple, None): Returns a tuple ``(img_scale, None)``, where
``img_scale`` is sampled scale and None is just a placeholder
to be consistent with :func:`random_select`.
"""
assert mmcv.is_list_of(img_scales, tuple) and len(img_scales) == 2
img_scale_long = [max(s) for s in img_scales]
img_scale_short = [min(s) for s in img_scales]
long_edge = np.random.randint(
min(img_scale_long),
max(img_scale_long) + 1)
short_edge = np.random.randint(
min(img_scale_short),
max(img_scale_short) + 1)
img_scale = (long_edge, short_edge)
return img_scale, None
@staticmethod
def random_sample_ratio(img_scale, ratio_range):
"""Randomly sample an img_scale when ``ratio_range`` is specified.
A ratio will be randomly sampled from the range specified by
``ratio_range``. Then it would be multiplied with ``img_scale`` to
generate sampled scale.
Args:
img_scale (tuple): Images scale base to multiply with ratio.
ratio_range (tuple[float]): The minimum and maximum ratio to scale
the ``img_scale``.
Returns:
(tuple, None): Returns a tuple ``(scale, None)``, where
``scale`` is sampled ratio multiplied with ``img_scale`` and
None is just a placeholder to be consistent with
:func:`random_select`.
"""
assert isinstance(img_scale, tuple) and len(img_scale) == 3
min_ratio, max_ratio = ratio_range
assert min_ratio <= max_ratio
ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio
scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio)
return scale, None
def _random_scale(self, results):
"""Randomly sample an img_scale according to ``ratio_range`` and
``multiscale_mode``.
If ``ratio_range`` is specified, a ratio will be sampled and be
multiplied with ``img_scale``.
If multiple scales are specified by ``img_scale``, a scale will be
sampled according to ``multiscale_mode``.
Otherwise, single scale will be used.
Args:
results (dict): Result dict from :obj:`dataset`.
Returns:
dict: Two new keys 'scale` and 'scale_idx` are added into
``results``, which would be used by subsequent pipelines.
"""
if self.ratio_range is not None:
if self.img_scale is None:
c, h, w = results['img']
scale, scale_idx = self.random_sample_ratio((c, w, h),
self.ratio_range)
else:
scale, scale_idx = self.random_sample_ratio(
self.img_scale[0], self.ratio_range)
elif len(self.img_scale) == 1:
scale, scale_idx = self.img_scale[0], 0
elif self.multiscale_mode == 'range':
scale, scale_idx = self.random_sample(self.img_scale)
elif self.multiscale_mode == 'value':
scale, scale_idx = self.random_select(self.img_scale)
else:
raise NotImplementedError
results['scale'] = scale
results['scale_idx'] = scale_idx
def _resize_img(self, results):
"""Resize images with ``results['scale']``."""
if self.keep_ratio:
img, scale_factor = mmcv.imrescale(
results['img'], results['scale'], return_scale=True)
# the w_scale and h_scale has minor difference
# a real fix should be done in the mmcv.imrescale in the future
new_h, new_w = img.shape[:2]
h, w = results['img'].shape[:2]
w_scale = new_w / w
h_scale = new_h / h
else:
img, w_scale, h_scale = mmcv.imresize(
results['img'], results['scale'], return_scale=True)
scale_factor = np.array([w_scale, h_scale, w_scale, h_scale],
dtype=np.float32)
results['img'] = img
results['img_shape'] = img.shape
results['pad_shape'] = img.shape # in case that there is no padding
results['scale_factor'] = scale_factor
results['keep_ratio'] = self.keep_ratio
def _resize_seg(self, results):
"""Resize semantic segmentation map with ``results['scale']``."""
for key in results.get('seg_fields', []):
if self.keep_ratio:
gt_seg = mmcv.imrescale(
results[key], results['scale'], interpolation='nearest')
else:
gt_seg = mmcv.imresize(
results[key], results['scale'], interpolation='nearest')
results[key] = gt_seg
def __call__(self, results):
"""Call function to resize images, bounding boxes, masks, semantic
segmentation map.
Args:
results (dict): Result dict from loading pipeline.
Returns:
dict: Resized results, 'img_shape', 'pad_shape', 'scale_factor',
'keep_ratio' keys are added into result dict.
"""
if 'scale' not in results:
self._random_scale(results)
self._resize_img(results)
self._resize_seg(results)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += (f'(img_scale={self.img_scale}, '
f'multiscale_mode={self.multiscale_mode}, '
f'ratio_range={self.ratio_range}, '
f'keep_ratio={self.keep_ratio})')
return repr_str
@PIPELINES.register_module()
class RandomCropMedical(object):
"""Random crop the image & seg.
Args:
crop_size (tuple): Expected size after cropping, (h, w).
cat_max_ratio (float): The maximum ratio that single category could
occupy.
"""
def __init__(self, crop_size, cat_max_ratio=1., ignore_index=255):
self.crop_size = crop_size
self.cat_max_ratio = cat_max_ratio
self.ignore_index = ignore_index
def get_crop_region(self, img):
"""Randomly get a crop bounding box."""
margin_x = max(img.shape[0] - self.crop_size[0], 0)
margin_y = max(img.shape[1] - self.crop_size[1], 0)
margin_z = max(img.shape[2] - self.crop_size[2], 0)
offset_x = np.random.randint(0, margin_x + 1)
offset_y = np.random.randint(0, margin_y + 1)
offset_z = np.random.randint(0, margin_z + 1)
crop_x1, crop_x2 = offset_x, offset_x + self.crop_size[0]
crop_y1, crop_y2 = offset_y, offset_y + self.crop_size[1]
crop_z1, crop_z2 = offset_z, offset_z + self.crop_size[2]
return crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2
def crop(self, img, crop_region):
"""Crop from ``img``"""
# crop_y1, crop_y2, crop_x1, crop_x2 = crop_region
# img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2 = crop_region
img = img[crop_x1: crop_x2, crop_y1: crop_y2, crop_z1: crop_z2]
return img
def __call__(self, results):
"""Call function to randomly crop images, semantic segmentation maps.
Args:
results (dict): Result dict from loading pipeline.
Returns:
dict: Randomly cropped results, 'img_shape' key in result dict is
updated according to crop size.
"""
if isinstance(results["img"], list):
img = results["img"][0]
else:
img = results["img"]
assert isinstance(img, np.ndarray) and len(img.shape) == len(self.crop_size)
crop_region = self.get_crop_region(img)
if self.cat_max_ratio < 1.:
# Repeat 10 times
for _ in range(20):
seg_temp = self.crop(results['gt_semantic_seg'], crop_region)
labels, cnt = np.unique(seg_temp, return_counts=True)
cnt = cnt[labels != self.ignore_index]
if len(cnt) > 1 and np.max(cnt) / np.sum(
cnt) < self.cat_max_ratio:
break
crop_region = self.get_crop_region(img)
if isinstance(results["img"], list):
for i in range(len(results["img"])):
results["img"][i] = self.crop(results["img"][i], crop_region)
img_shape = results["img"][0].shape
else:
results["img"] = self.crop(results["img"], crop_region)
img_shape = results["img"].shape
# img = self.crop(img, crop_region)
# img_shape = img.shape
# results['img'] = img
results['img_shape'] = img_shape
# crop semantic seg
for key in results.get('seg_fields', []):
results[key] = self.crop(results[key], crop_region)
# print("[DEBUG] foreground {}: {}".format(key, np.where((results[key] > 0) * (results[key] < 5))[0].shape))
# print("[DEBUG] ignore {}: {}".format(key, np.where(results[key]== 255)[0].shape))
return results
@PIPELINES.register_module()
class ExtractDataFromObj(object):
def __init__(self):
pass
def __call__(self, results):
# if isinstance(results["gt_semantic_seg"], nib.Nifti1Image):
# results["gt_semantic_seg"] = np.squeeze(results["gt_semantic_seg"].get_fdata(dtype=np.float32))
if mmcv.is_list_of(results["img"], nib.Nifti1Image) or isinstance(results["img"], nib.Nifti1Image):
for key in results.get('seg_fields', []):
results[key] = np.squeeze(results[key].get_fdata(dtype=np.float32))
if mmcv.is_list_of(results["img"], nib.Nifti1Image):
for i, img_nii in enumerate(results["img"]):
results["img"][i] = np.squeeze(img_nii.get_fdata(dtype=np.float32))
else:
if not isinstance(results["img"], nib.Nifti1Image):
print("[ERROR] Unsupported image type: {}!".format(type(results["img"])))
raise ValueError
results["img"] = np.squeeze(results["img"].get_fdata(dtype=np.float32))
return results
@PIPELINES.register_module()
class RandomCropMedicalWithForeground(object):
"""Random crop the image & seg.
Args:
crop_size (tuple): Expected size after cropping, (h, w).
cat_max_ratio (float): The maximum ratio that single category could
occupy.
"""
def __init__(self, crop_size, fore_cat_ratio=1., ignore_index=255):
self.crop_size = crop_size
self.fore_cat_ratio = fore_cat_ratio
self.ignore_index = ignore_index
def get_crop_region(self, img):
"""Randomly get a crop bounding box."""
margin_x = max(img.shape[0] - self.crop_size[0], 0)
margin_y = max(img.shape[1] - self.crop_size[1], 0)
margin_z = max(img.shape[2] - self.crop_size[2], 0)
offset_x = np.random.randint(0, margin_x + 1)
offset_y = np.random.randint(0, margin_y + 1)
offset_z = np.random.randint(0, margin_z + 1)
crop_x1, crop_x2 = offset_x, offset_x + self.crop_size[0]
crop_y1, crop_y2 = offset_y, offset_y + self.crop_size[1]
crop_z1, crop_z2 = offset_z, offset_z + self.crop_size[2]
return crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2
def crop(self, img, crop_region):
"""Crop from ``img``"""
# crop_y1, crop_y2, crop_x1, crop_x2 = crop_region
# img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2 = crop_region
img = img[crop_x1: crop_x2, crop_y1: crop_y2, crop_z1: crop_z2]
return img
def find_non_zero_labels_mask(self, segmentation_map, th_percent, crop_region):
# d1, d2, d3 = segmentation_map.shape
# segmentation_map[segmentation_map > 0] = 1
# total_voxel_labels = segmentation_map.sum()
total_voxel_labels = (segmentation_map > 0).sum()
cropped_segm_map = self.crop(segmentation_map, crop_region)
crop_voxel_labels = (cropped_segm_map > 0).sum()
label_percentage = crop_voxel_labels / total_voxel_labels
# print(label_percentage,total_voxel_labels,crop_voxel_labels)
if label_percentage >= th_percent:
return True
else:
return False
def __call__(self, results):
"""Call function to randomly crop images, semantic segmentation maps.
Args:
results (dict): Result dict from loading pipeline.
Returns:
dict: Randomly cropped results, 'img_shape' key in result dict is
updated according to crop size.
"""
if isinstance(results["img"], list):
img = results["img"][0]
else:
img = results["img"]
assert isinstance(img, np.ndarray) and len(img.shape) == len(self.crop_size)
crop_region = self.get_crop_region(img)
if self.fore_cat_ratio < 1.:
# Repeat 10 times
for _ in range(20):
# seg_temp = self.crop(results['gt_semantic_seg'], crop_region)
# labels, cnt = np.unique(seg_temp, return_counts=True)
# cnt = cnt[labels != self.ignore_index]
if self.find_non_zero_labels_mask(results['gt_semantic_seg'], self.fore_cat_ratio,
crop_region):
break
crop_region = self.get_crop_region(img)
if isinstance(results["img"], list):
for i in range(len(results["img"])):
results["img"][i] = self.crop(results["img"][i], crop_region)
img_shape = results["img"][0].shape
else:
results["img"] = self.crop(results["img"], crop_region)
img_shape = results["img"].shape
# img = self.crop(img, crop_region)
# img_shape = img.shape
# results['img'] = img
results['img_shape'] = img_shape
# crop semantic seg
for key in results.get('seg_fields', []):
results[key] = self.crop(results[key], crop_region)
# print("[DEBUG] foreground {}: {}".format(key, np.where((results[key] > 0) * (results[key] < 5))[0].shape))
# print("[DEBUG] ignore {}: {}".format(key, np.where(results[key]== 255)[0].shape))
return results
#TODO: consider padding
# @PIPELINES.register_module()
# class RandomCropMedicalWithAnnotations(object):
# def __init__(self, is_save=False, save_path=None):
# self.is_save = is_save
# self.save_path = save_path
# if self.is_save and not os.path.exists(self.save_path):
# os.makedirs(self.save_path)
# def __call__(self, results):
# if "gt_semantic_seg" not in results:
# print("[WARNING] key: gt_semantic_seg not in input data")
# return results
# mask = results["gt_semantic_seg"]
# crop_region = self._get_annotation_region(mask)
# if mmcv.is_list_of(results["img"], np.ndarray):
# for i in range(len(results["img"])):
# results["img"][i] = self.crop(results["img"][i], crop_region)
# if self.is_save:
# img_nii = nib.Nifti1Image(results["img"][i], results["img_affine_matrix"][i])
# img_name = results["filename"][i].split('/')[-1].split('.')[0]
# nib.save(img_nii, os.path.join(self.save_path, "{}_crop.nii.gz".format(img_name)))
# else:
# results["img"] = self.crop(results["img"], crop_region)
# if self.is_save:
# img_nii = nib.Nifti1Image(results["img"], results["img_affine_matrix"])
# img_name = results["filename"].split('/')[-1].split('.')[0]
# nib.save(img_nii, os.path.join(self.save_path, "{}_crop.nii.gz".format(img_name)))
# for key in results.get('seg_fields', []):
# results[key] = self.crop(results[key], crop_region)
# if self.is_save:
# img_nii = nib.Nifti1Image(results[key], results["seg_affine_matrix"])
# img_name = results["filename"].split('/')[-1].split('.')[0]
# nib.save(img_nii, os.path.join(self.save_path, "{}_crop_{}.nii.gz".format(img_name, key)))
# return results
#
# @staticmethod
# def _get_annotation_region(mask):
# location = np.where(mask > 0)
# crop_region = []
# for loc in location:
# crop_region.append(np.min(loc))
# crop_region.append(np.max(loc) + 1)
# return crop_region
#
# def crop(self, img, crop_region):
# """Crop from ``img``"""
# # crop_y1, crop_y2, crop_x1, crop_x2 = crop_region
# # img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
# crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2 = crop_region
# img = img[crop_x1: crop_x2, crop_y1: crop_y2, crop_z1: crop_z2]
# return img
@PIPELINES.register_module()
class RandomCropMedicalWithAnnotations(object):
def __init__(self, pad_mode=None, **kwargs):
self.pad_mode = pad_mode
self.kwargs = kwargs
self._check_cfg(pad_mode, kwargs)
def __call__(self, results):
if "gt_semantic_seg" not in results:
print("[WARNING] key: gt_semantic_seg not in input data")
return results
mask = results["gt_semantic_seg"]
crop_region = self._get_annotation_region(mask, self.pad_mode, self.kwargs)
if mmcv.is_list_of(results["img"], np.ndarray):
for i in range(len(results["img"])):
results["img"][i] = self.crop(results["img"][i], crop_region)
else:
results["img"] = self.crop(results["img"], crop_region)
for key in results.get('seg_fields', []):
results[key] = self.crop(results[key], crop_region)
return results
def _check_cfg(self, pad_mode, kwargs):
if pad_mode == 'static':
assert 'static_size' in kwargs
@staticmethod
def _get_annotation_region(mask, pad_mode, kwargs):
location = np.where(mask > 0)
crop_region = []
for i, loc in enumerate(location):
# crop_region.append(np.min(loc))
# crop_region.append(np.max(loc) + 1)
min_l = np.min(loc)
max_r = np.max(loc)
if pad_mode == 'static':
size = kwargs['static_size'][i]
assert size <= mask.shape[i]
left = np.random.randint(0, min_l + 1)
right = np.random.randint(max_r, mask.shape[i])
margin = (right - left) - size
margin_l = int(np.random.uniform() * margin)
left = max(0, left + margin_l)
right = min(mask.shape[i], left + size)
left = min(0, right - size)
# left = np.random.randint(0, min_l + 1)
# right = min(left + size, mask.shape[i])
# left = max(right - size, 0)
crop_region.append(left)
crop_region.append(right)
elif pad_mode == None:
crop_region.append(min_l)
crop_region.append(max_r)
else:
raise NotImplementedError
return crop_region
def crop(self, img, crop_region):
"""Crop from ``img``"""
# crop_y1, crop_y2, crop_x1, crop_x2 = crop_region
# img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2 = crop_region
img = img[crop_x1: crop_x2, crop_y1: crop_y2, crop_z1: crop_z2]
return img
@PIPELINES.register_module()
class CropMedicalExceptHoleArea(object):
def __call__(self, results):
img = results['img']
nonzero_mask = self._create_nonzero_mask(img)
bbox = self._get_bbox_from_mask(nonzero_mask)
if isinstance(results['img'], list):
for i in range(len(results['img'])):
results['img'][i] = self.crop(results['img'][i], bbox)
else:
results['img'] = self.crop(results['img'], bbox)
for key in results.get('seg_fields', []):
results[key] = self.crop(results[key], bbox)
return results
def _create_nonzero_mask(self, img):
if isinstance(img, list):
nonzero_mask = np.zeros(img[0].shape, dtype=bool)
for i in range(len(img)):
this_mask = img[i] != 0
nonzero_mask = nonzero_mask | this_mask
nonzero_mask = binary_fill_holes(nonzero_mask)
else:
nonzero_mask = img != 0
nonzero_mask = binary_fill_holes(nonzero_mask)
return nonzero_mask
def _get_bbox_from_mask(self, mask, outside_value=0):
mask_voxel_coords = np.where(mask != outside_value)
minzidx = int(np.min(mask_voxel_coords[0]))
maxzidx = int(np.max(mask_voxel_coords[0])) + 1
minxidx = int(np.min(mask_voxel_coords[1]))
maxxidx = int(np.max(mask_voxel_coords[1])) + 1
minyidx = int(np.min(mask_voxel_coords[2]))
maxyidx = int(np.max(mask_voxel_coords[2])) + 1
return [minzidx, maxzidx, minxidx, maxxidx, minyidx, maxyidx]
def crop(self, img, crop_region):
crop_x1, crop_x2, crop_y1, crop_y2, crop_z1, crop_z2 = crop_region
img = img[crop_x1: crop_x2, crop_y1: crop_y2, crop_z1: crop_z2]
return img
@PIPELINES.register_module()
class NormalizeMedical(object):
def __init__(self, norm_type: str, clip_intenisty=True, **kwargs):
self.norm_type = norm_type.lower()
self.clip_intenisty = clip_intenisty
self.kwargs = kwargs
def __call__(self, results):
if self.norm_type == "full_volume_mean":
if isinstance(results["img"], list):
for i, img_np in enumerate(results["img"]):
if self.clip_intenisty:
img_np = self.percentile_clip(img_np,
self.kwargs.get("instensity_min_val", 0.1),
self.kwargs.get("instensity_max_val", 99.8))
results["img"][i] = (img_np - img_np.mean()) / (img_np.std() + 10e-5)
else:
if self.clip_intenisty:
results["img"] = self.percentile_clip(results["img"],
self.kwargs.get("instensity_min_val", 0.1),
self.kwargs.get("instensity_max_val", 99.8))
results["img"] =(results["img"] - results["img"].mean()) / (results["img"].std() + 10e-5)
elif self.norm_type == "max_min":
if isinstance(results["img"], list):
for i, img_np in results["img"]:
results["img"][i] = (img_np - img_np.max()) / (img_np.min() - img_np.max() + 10e-5)
else:
results["img"] = (results["img"] - results["img"].max()) / \
(results["img"].min() - results["img"].max() + 10e-5)
elif self.norm_type == "mean":
if isinstance(results["img"], list):
for i, img_np in enumerate(results["img"]):
mask = img_np > 10e-5
if self.clip_intenisty:
img_np = self.percentile_clip(img_np,
self.kwargs.get("instensity_min_val", 0.1),
self.kwargs.get("instensity_max_val", 99.8))
desired = img_np[mask]
mean_val, std_val = desired.mean(), desired.std()
results["img"][i] = (img_np - mean_val) / (std_val + 10e-5)
else:
mask = results["img"] > 10e-5
if self.clip_intenisty:
results["img"] = self.percentile_clip(results["img"],
self.kwargs.get("instensity_min_val", 0.1),
self.kwargs.get("instensity_max_val", 99.8))
desired = results["img"][mask]
mean_val, std_val = desired.mean(), desired.std()
results["img"] = (results["img"] - mean_val) / (std_val + 10e-5)
else:
print("[ERROR] norm type: {} is not implement")
raise NotImplementedError
return results
@staticmethod
def percentile_clip(img_numpy, min_val=0.1, max_val=99.8):
b, t = np.percentile(img_numpy, (min_val, max_val))
data = np.clip(img_numpy, b, t)
return data
@PIPELINES.register_module()
class ConcatImage(object):
def __init__(self):
pass
def __call__(self, results):
if mmcv.is_list_of(results["img"], np.ndarray) or \
isinstance(results["img"], np.ndarray):
if isinstance(results["img"], list):
for i in range(len(results["img"])):
results["img"][i] = results["img"][i][np.newaxis, ...]
results["img"] = np.concatenate(results["img"], axis=0)
else:
results["img"] = results["img"][np.newaxis, ...]
return results
@PIPELINES.register_module()
class IgnoreBlackArea(object):
def __init__(self, set_label=255):
self.set_label = set_label
def __call__(self, results):
if mmcv.is_list_of(results["img"], np.ndarray):
for key in results.get('seg_fields', []):
results[key][results["img"][0] <= 10e-3] = self.set_label
else:
for key in results.get('seg_fields', []):
results[key][results["img"] <= 10e-3] = self.set_label
return results
@PIPELINES.register_module()
class BinaryCateogry(object):
def __init__(self, ignore_index=255):
self.ignore_index = ignore_index
def __call__(self, results):
for key in results.get('seg_fields', []):
results[key][(results[key] > 0) & (results[key] != self.ignore_index)] = 1
return results
@PIPELINES.register_module()
class RandomFlip3D(object):
"""Flip the image & seg.
If the input dict contains the key "flip", then the flag will be used,
otherwise it will be randomly decided by a ratio specified in the init
method.
Args:
prob (float, optional): The flipping probability. Default: None.
direction(str, optional): The flipping direction. Options are
'horizontal' and 'vertical'. Default: 'horizontal'.
"""
@deprecated_api_warning({'flip_ratio': 'prob'}, cls_name='RandomFlip3D')
def __init__(self, prob=None, direction=["sagittal", "coronal", "transverse"]):
self.prob = prob
self.direction = direction
if prob is not None:
assert prob >= 0 and prob <= 1
assert direction in ['horizontal', 'vertical']
def __call__(self, results):
"""Call function to flip bounding boxes, masks, semantic segmentation
maps.
Args:
results (dict): Result dict from loading pipeline.
Returns:
dict: Flipped results, 'flip', 'flip_direction' keys are added into
result dict.
"""
if 'flip' not in results:
flip = True if np.random.rand() < self.prob else False
results['flip'] = flip
if 'flip_direction' not in results:
results['flip_direction'] = self.direction
if results['flip']:
# flip image
results['img'] = mmcv.imflip(
results['img'], direction=results['flip_direction'])
# flip segs
for key in results.get('seg_fields', []):
# use copy() to make numpy stride positive
results[key] = mmcv.imflip(
results[key], direction=results['flip_direction']).copy()
return results
def __repr__(self):
return self.__class__.__name__ + f'(prob={self.prob})'
@PIPELINES.register_module()
class ResizeMedical(object):
def __init__(self, size):
self.size = size
def __call__(self, results):
if isinstance(results['img'], list):
for i in range(len(results['img'])):
resized = torch.nn.functional.interpolate(
torch.as_tensor(np.ascontiguousarray(results['img'][i]), dtype=torch.float).unsqueeze(0).unsqueeze(0),
size=self.size,
mode='area'
)
results['img'][i] = resized.squeeze(0).squeeze(0).detach().cpu().numpy()
else:
resized = torch.nn.functional.interpolate(
torch.as_tensor(np.ascontiguousarray(results['img']), dtype=torch.float).unsqueeze(0).unsqueeze(0),
size=self.size,
mode='area'
)
results['img'] = resized.squeeze(0).squeeze(0).detach().cpu().numpy()
return results
def __repr__(self):
return self.__class__.__name__ + f'(size={self.size})'
| 43.720386
| 123
| 0.562648
|
4a0ddb58b28222a195fe513df64d2f2046f12427
| 1,418
|
py
|
Python
|
job_monitor/exhausted.py
|
plinecom/Exhausted
|
4f2c1371daf3a0583a248eeaa66157ff4bcbb90e
|
[
"MIT"
] | 2
|
2020-05-13T09:21:03.000Z
|
2021-01-10T22:38:39.000Z
|
job_monitor/exhausted.py
|
plinecom/Exhausted
|
4f2c1371daf3a0583a248eeaa66157ff4bcbb90e
|
[
"MIT"
] | null | null | null |
job_monitor/exhausted.py
|
plinecom/Exhausted
|
4f2c1371daf3a0583a248eeaa66157ff4bcbb90e
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import psutil
import pymongo
import pymongo.errors
import os
from datetime import datetime
import time
import sys
# print psutil.cpu_percent(percpu=True)
# print psutil.virtual_memory()
# 必要な物、ソケット通信、標準入力ハンドラ。実行状態調査。ファイルロック。
def data_collect():
# mongodb へのアクセスを確立
client = pymongo.MongoClient('192.168.33.101', 27017)
# データベースを作成 (名前: my_database)
db = client.job_database
# コレクションを作成 (名前: my_collection)
co = db.job_collection
while True:
date = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline', 'environ', 'cpu_percent', 'num_threads', 'username', 'memory_percent'])
except psutil.NoSuchProcess:
pass
else:
pinfo["hostname"] = os.uname()
pinfo["date"] = date
try:
co.insert_one(pinfo)
except pymongo.errors.PyMongoError:
pass
time.sleep(30)
# なんか適当に保存
# 全部とってくる
# for data in co.find():
# print data
def fork():
pid = os.fork()
if pid > 0:
f = open('/var/run/exhaustedd.pid', 'w')
f.write(str(pid) + "\n")
f.close()
sys.exit()
if pid == 0:
data_collect()
if __name__ == '__main__':
fork()
| 20.852941
| 141
| 0.555712
|
4a0ddd5138c5a9f6759124a3794d490b6aab31ed
| 9,305
|
py
|
Python
|
pyschieber/player/challenge_player/strategy/card_counter.py
|
Murthy10/pyschieber
|
f9db28c9553b8f321f6ed71cff04eff7879af5f6
|
[
"MIT"
] | 5
|
2018-01-17T08:11:14.000Z
|
2018-11-27T11:37:15.000Z
|
pyschieber/player/challenge_player/strategy/card_counter.py
|
Murthy10/pyschieber
|
f9db28c9553b8f321f6ed71cff04eff7879af5f6
|
[
"MIT"
] | 4
|
2018-05-09T08:41:05.000Z
|
2018-11-16T08:07:39.000Z
|
pyschieber/player/challenge_player/strategy/card_counter.py
|
Murthy10/pyschieber
|
f9db28c9553b8f321f6ed71cff04eff7879af5f6
|
[
"MIT"
] | 3
|
2018-04-20T07:39:30.000Z
|
2018-11-10T12:44:08.000Z
|
from pyschieber.player.challenge_player.strategy.mode.trumpf_color_mode import *
from pyschieber.player.challenge_player.strategy.mode.top_down_mode import *
from pyschieber.player.challenge_player.strategy.mode.bottom_up_mode import *
from pyschieber.player.challenge_player.strategy.flags.doesnt_habe_card_flag import DoesntHaveCardFlag
from pyschieber.player.challenge_player.strategy.flags.previously_had_stich_flag import PreviouslyHadStichFlag
from pyschieber.player.challenge_player.strategy.flags.falied_to_serve_suit_flag import FailedToServeSuitFlag
from pyschieber.player.challenge_player.strategy.flags.suit_verworfen_flag import SuitVerworfenFlag
from pyschieber.deck import Deck
from pyschieber.card import from_string_to_card
from pyschieber.rules.stich_rules import stich_rules
from pyschieber.trumpf import get_trumpf
from pyschieber.stich import PlayedCard
from pyschieber.suit import Suit
from math import floor
class CardCounter:
def __init__(self, me):
self.played_cards = [[],[],[],[]]
self.flags = [[],[],[],[]]
self.played_count = 0
self.current_stich = {}
self.my_id = me.id
self.me = me
self.partner_id = (self.my_id + 2) % 4
self.opponent_1_id = (self.my_id+1)%4
self.opponent_2_id = (self.my_id+3)%4
def card_played(self, player_id, card, state):
self.played_cards[player_id].append(card)
self.played_count += 1
self.current_stich[player_id] = card
self.update_flags(player_id, card, state)
if self.played_count % 4 == 0:
self.current_stich = {}
def current_round(self):
return floor(self.played_count/4)
def update_flags(self, player_id, card, state):
current_stich_color = None
if len(state['table']) > 0:
current_stich_color = from_string_to_card(state['table'][0]['card']).suit
mode = get_mode(state['trumpf'])
if len(self.current_stich) == 4:
if player_id == self.partner_id and self.round_leader(state) != self.my_id and self.round_leader(state) != self.partner_id:
#neither of us wins, A2 played last card -> A2 doesn't have anything beating current stich
for stronger_card in mode.stronger_cards_remaining(self.current_stich[self.round_leader(state)], self):
self.flags[player_id].append(DoesntHaveCardFlag(stronger_card))
if len(self.current_stich) == 1:
if mode.trumpf_name().name not in [x.name for x in Suit]:
if player_id == self.partner_id and not mode.is_bock(card, self):
for suit in Suit:
self.flags[player_id].append(DoesntHaveCardFlag(mode.get_current_bock(suit, self)))
if not self.had_stich_previously(player_id):
if not (self.current_round() == 0 and state['geschoben'] and (mode.trumpf_name().name in [x.name for x in Suit])):
self.flags[player_id].append(PreviouslyHadStichFlag())
if self.round_leader(state) == self.partner_id:
if mode.trumpf_name().name in [x.name for x in Suit]:
if self.current_round() == 0:
if state['geschoben']:
if card.suit == mode.trumpf_name().name:
for stronger_card in mode.stronger_cards_remaining(card, self):
if stronger_card.value != 11:
self.flags[player_id].append(DoesntHaveCardFlag(stronger_card))
if card == mode.get_current_bock(card.suit, self) and card.suit != mode.trumpf_name().name:
for suit_cards in split_cards_by_suit(self.unknown_cards()):
if suit_cards[0].name == mode.trumpf_name().name:
for trumpf_card in suit_cards[1]:
self.flags[(self.my_id + 1)%4].append(DoesntHaveCardFlag(trumpf_card))
self.flags[(self.my_id + 3)%4].append(DoesntHaveCardFlag(trumpf_card))
if len(self.current_stich) > 1:
if card.suit != current_stich_color:
if (mode.trumpf_name().name in [x.name for x in Suit] and card.suit != mode.trumpf_name().name) or mode.trumpf_name().name not in [x.name for x in Suit]:
self.flags[player_id].append(FailedToServeSuitFlag(current_stich_color))
self.flags[player_id].append(SuitVerworfenFlag(card.suit))
def round_leader(self, state):
if len(self.get_table_cards()) == 0:
return None
return stich_rules[get_trumpf(state['trumpf'])](played_cards=self.get_table_cards()).player
def get_hand(self):
return self.me.cards
def get_table_cards(self):
cards_on_table = []
for player_id in self.current_stich:
cards_on_table.append(PlayedCard(player=player_id, card=self.current_stich[player_id]))
return cards_on_table
def cards_played(self):
played = []
for x in range(0,4):
played.extend(self.played_cards[x])
return played
def seen_cards(self):
seen = []
seen.extend(self.cards_played())
seen.extend(self.me.cards)
return seen
def remaining_cards(self, gone):
d = Deck()
return [x for x in d.cards if x not in gone]
def remaining_by_suit(self, suit):
return [x for x in self.unknown_cards() if x.suit == suit]
def unknown_cards(self):
return self.remaining_cards(self.seen_cards())
def dead_cards(self):
dead = []
current_round = int(self.played_count/4)
for player_id in range(0, 4):
dead.extend(self.played_cards[player_id][0:current_round])
return dead
def filter_cards_of_same_suit(self, card, predicate):
unknown_of_same_suit = list(filter(lambda x: x.suit == card.suit, self.unknown_cards()))
return list(filter(predicate, unknown_of_same_suit))
def filter_not_dead_cards_of_same_suit(self, card, predicate):
remaining_cards = self.remaining_cards(self.dead_cards())
remaining_of_same_suit = list(filter(lambda x: (x.suit == card.suit), remaining_cards))
return list(filter(predicate, remaining_of_same_suit))
def had_stich_previously(self, p_id):
for flag in self.flags[p_id]:
if isinstance(flag, PreviouslyHadStichFlag):
return True
return False
def has_suit_likelihood(self, player_id, suit, state):
return self.has_cards_likelihood(player_id, self.remaining_by_suit(suit), state)
def has_cards_likelihood(self, player_id, cards, state):
likelihood = 1
for card in cards:
likelihood = likelihood * (1 - self.has_card_likelihood(player_id, card, state))
return 1 - likelihood
def has_card_likelihood(self, player_id, card, state):
if card in self.get_hand() or card in [x[0] for x in self.played_cards if len(x) != 0]:
return 0
if state['trumpf'] == card.suit and card.value == 11:
return 1/3
for flag in self.flags[player_id]:
if isinstance(flag, FailedToServeSuitFlag):
if card.suit == flag.color:
return 0
elif isinstance(flag, DoesntHaveCardFlag):
if flag.card == card:
return 0
potential_holders = 3
for p_id in range(0, 4):
if p_id != self.my_id and p_id != player_id:
for flag in self.flags[p_id]:
if isinstance(flag, FailedToServeSuitFlag):
if card.suit == flag.color:
potential_holders -= 1
break
elif isinstance(flag, DoesntHaveCardFlag):
if card == flag.card:
potential_holders -= 1
break
if potential_holders > 0:
return 1 / potential_holders
else:
return 0
def get_suits_by_strength(self, player_id):
flags_of_player = self.flags[player_id]
weak = []
for flag in flags_of_player:
if isinstance(flag, FailedToServeSuitFlag):
if flag.color not in weak:
weak.append(flag.color)
for flag in flags_of_player:
if isinstance(flag, SuitVerworfenFlag):
if flag.color not in weak:
weak.append(flag.color)
for color in Suit:
if color.name not in weak:
weak.append(color.name)
return list(reversed(weak))
def tossed_suits(self, player_id):
return list(map(lambda y: y.color, filter(lambda x: isinstance(x, SuitVerworfenFlag), self.flags[player_id])))
def get_mode(trumpf):
return {
'OBE_ABE': TopDownMode(),
'UNDE_UFE': BottomUpMode(),
'ROSE': TrumpfColorMode(Suit['ROSE']),
'BELL': TrumpfColorMode(Suit['BELL']),
'ACORN': TrumpfColorMode(Suit['ACORN']),
'SHIELD': TrumpfColorMode(Suit['SHIELD']),
}[trumpf]
| 42.488584
| 169
| 0.616443
|
4a0ddd8d6c3f0e065269844373826e5bb6d884a7
| 2,247
|
py
|
Python
|
api-gateway/fcgi/super_resolution/python/post_local_super_resolution_py.py
|
intel/cloud-client-ai-service-framework
|
01676b08878f7a58201854aedb181134eafef7a2
|
[
"Apache-2.0"
] | 3
|
2022-03-25T17:28:53.000Z
|
2022-03-29T03:30:25.000Z
|
api-gateway/fcgi/super_resolution/python/post_local_super_resolution_py.py
|
intel/cloud-client-ai-service-framework
|
01676b08878f7a58201854aedb181134eafef7a2
|
[
"Apache-2.0"
] | null | null | null |
api-gateway/fcgi/super_resolution/python/post_local_super_resolution_py.py
|
intel/cloud-client-ai-service-framework
|
01676b08878f7a58201854aedb181134eafef7a2
|
[
"Apache-2.0"
] | 1
|
2022-03-27T12:44:19.000Z
|
2022-03-27T12:44:19.000Z
|
#Copyright (C) 2020 Intel Corporation
import requests
import json
import base64
import urllib.parse
import hashlib ## python3
import time
import random
import cv2
from collections import OrderedDict
import numpy as np
import argparse
import sys
def main(args):
#start_time = time.time()
appkey = 'di6ik9b9JiYfImUB'
f = open(args.image, "rb")
base64_data = base64.b64encode(f.read())
time_stamp = int(time.time())
random_let = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba1234567890', 10))
params = OrderedDict()
params['app_id'] = 2128571502
params['image'] = base64_data
params['nonce_str'] =time_stamp
params['time_stamp'] = time_stamp
query_string = urllib.parse.urlencode(params)
query_string += '&app_key=' + appkey
m = hashlib.md5(query_string.encode())
sign = m.hexdigest().upper()
params['sign'] = sign
start_time = time.time()
## notice: must uset http_proxy, otherwise can not get link
#url = 'https://api.ai.qq.com/fcgi-bin/aai/aai_asr';
url = 'http://localhost:8080/cgi-bin/fcgi_py_super_resolution'
res = requests.post(url,data=params)
processing_time = time.time() - start_time
image_width = 1920
image_height = 1080
image_channel = 3
if res.status_code == 200:
print(res.content.decode('utf-8'))
result_dict = json.loads(res.text, strict = False)
if result_dict['ret'] == 0:
img_str = base64.b64decode(bytes(result_dict['data'][1:-1], encoding = "utf8"))
img_np = np.frombuffer(img_str, dtype=np.uint8)
img = np.array(img_np[0: image_height * image_width * image_channel]).reshape(image_height, image_width, image_channel)
cv2.imwrite('out.jpg', img)
print ("the sagementation image is saved in out.jpg")
print ("processing time is:", processing_time)
else:
print ("the error number is:", res.status_code)
if __name__ == "__main__":
parser = argparse.ArgumentParser(usage = "it's usage tip.", description = "help info.")
parser.add_argument("-i", "--image", default = "./input_data/face-detection-adas-0001.png", help = "the path of the picture")
args = parser.parse_args()
main(args)
| 31.647887
| 131
| 0.667112
|
4a0dde45d4685720ae67810bf55293683b3973c3
| 2,038
|
py
|
Python
|
examples/dfp/v201805/custom_field_service/create_custom_fields.py
|
christineyi3898/googleads-python-lib
|
cd707dc897b93cf1bbb19355f7424e7834e7fb55
|
[
"Apache-2.0"
] | 1
|
2019-10-21T04:10:22.000Z
|
2019-10-21T04:10:22.000Z
|
examples/dfp/v201805/custom_field_service/create_custom_fields.py
|
christineyi3898/googleads-python-lib
|
cd707dc897b93cf1bbb19355f7424e7834e7fb55
|
[
"Apache-2.0"
] | null | null | null |
examples/dfp/v201805/custom_field_service/create_custom_fields.py
|
christineyi3898/googleads-python-lib
|
cd707dc897b93cf1bbb19355f7424e7834e7fb55
|
[
"Apache-2.0"
] | 1
|
2019-10-21T04:10:51.000Z
|
2019-10-21T04:10:51.000Z
|
#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example creates custom fields.
To determine which custom fields exist, run get_all_custom_fields.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
"""
import uuid
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
custom_field_service = client.GetService(
'CustomFieldService', version='v201805')
# Create custom field objects.
custom_fields = [
{
'name': 'Customer comments #%s' % uuid.uuid4(),
'entityType': 'LINE_ITEM',
'dataType': 'STRING',
'visibility': 'FULL'
}, {
'name': 'Internal approval status #%s' % uuid.uuid4(),
'entityType': 'LINE_ITEM',
'dataType': 'DROP_DOWN',
'visibility': 'FULL'
}
]
# Add custom fields.
custom_fields = custom_field_service.createCustomFields(custom_fields)
# Display results.
for custom_field in custom_fields:
print ('Custom field with ID "%s" and name "%s" was created.'
% (custom_field['id'], custom_field['name']))
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)
| 30.41791
| 77
| 0.700687
|
4a0ddf2921c20be602ddc38825112bcdd56bea32
| 65
|
py
|
Python
|
user_login.py
|
Hegen52/football
|
15572b9913af4eb399b74203a9a27dd65d3ecaf4
|
[
"Apache-2.0"
] | null | null | null |
user_login.py
|
Hegen52/football
|
15572b9913af4eb399b74203a9a27dd65d3ecaf4
|
[
"Apache-2.0"
] | null | null | null |
user_login.py
|
Hegen52/football
|
15572b9913af4eb399b74203a9a27dd65d3ecaf4
|
[
"Apache-2.0"
] | null | null | null |
Neuer Code...
Codezeile Arbeitsplatz
Codezeile LaptopCode
Code 2
| 13
| 22
| 0.830769
|
4a0de01ec15daa0f02af220d701ae218a8e4867a
| 1,409
|
py
|
Python
|
tests/api/test_quote.py
|
manstiilin/zvt
|
5a37c19f4837c0250b04d9f41ead910f42b72ce4
|
[
"MIT"
] | 1
|
2019-12-09T12:13:09.000Z
|
2019-12-09T12:13:09.000Z
|
tests/api/test_quote.py
|
manstiilin/zvt
|
5a37c19f4837c0250b04d9f41ead910f42b72ce4
|
[
"MIT"
] | 2
|
2019-12-05T00:46:06.000Z
|
2019-12-15T12:22:07.000Z
|
tests/api/test_quote.py
|
manstiilin/zvt
|
5a37c19f4837c0250b04d9f41ead910f42b72ce4
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from zvdata import IntervalLevel
from zvt.api.quote import get_indices, get_kdata
from zvt.domain import StockCategory
def test_get_indices():
df = get_indices(provider='sina', block_category=StockCategory.industry)
print(df)
df = get_indices(provider='eastmoney', block_category=StockCategory.industry)
print(df)
def test_jq_1mon_kdata():
df = get_kdata(entity_id='stock_sz_000338', provider='joinquant', level=IntervalLevel.LEVEL_1MON)
se = df.loc['2010-01-29']
# make sure our fq is ok
assert round(se['open'], 2) <= 5.44
assert round(se['high'], 2) <= 6.43
assert round(se['low'], 2) <= 5.2
assert round(se['close'], 2) <= 5.45
def test_jq_1wk_kdata():
df = get_kdata(entity_id='stock_sz_000338', provider='joinquant', level=IntervalLevel.LEVEL_1WEEK)
se = df.loc['2019-04-19']
# make sure our fq is ok
assert round(se['open'], 2) <= 13.28
assert round(se['high'], 2) <= 13.90
assert round(se['low'], 2) <= 12.36
assert round(se['close'], 2) <= 13.30
def test_jq_1d_kdata():
df = get_kdata(entity_id='stock_sz_000338', provider='joinquant', level=IntervalLevel.LEVEL_1DAY)
se = df.loc['2019-04-19']
# make sure our fq is ok
assert round(se['open'], 2) <= 12.93
assert round(se['high'], 2) <= 13.52
assert round(se['low'], 2) <= 12.89
assert round(se['close'], 2) <= 13.33
| 32.767442
| 102
| 0.657204
|
4a0de10732607700dd9a683757111e5a03a623b0
| 4,198
|
py
|
Python
|
backend/src/baserow/contrib/database/config.py
|
calvinchengx/baserow
|
0340d5abf0a3b48154d41fd05cd2e1e05814cd66
|
[
"MIT"
] | null | null | null |
backend/src/baserow/contrib/database/config.py
|
calvinchengx/baserow
|
0340d5abf0a3b48154d41fd05cd2e1e05814cd66
|
[
"MIT"
] | null | null | null |
backend/src/baserow/contrib/database/config.py
|
calvinchengx/baserow
|
0340d5abf0a3b48154d41fd05cd2e1e05814cd66
|
[
"MIT"
] | null | null | null |
from django.apps import AppConfig
from baserow.core.registries import plugin_registry, application_type_registry
from .views.registries import view_type_registry, view_filter_type_registry
from .fields.registries import field_type_registry, field_converter_registry
class DatabaseConfig(AppConfig):
name = 'baserow.contrib.database'
def prevent_generated_model_for_registering(self):
"""
A nasty hack that prevents a generated table model and related auto created
models from being registered to the apps. When a model class is defined it
will be registered to the apps, but we do not always want that to happen
because models with the same class name can differ. They are also meant to be
temporary. Removing the model from the cache does not work because if there
are multiple requests at the same it is not removed from the cache on time
which could result in hard failures. It is also hard to extend the
django.apps.registry.apps so this hack extends the original `register_model`
method and it will only call the original `register_model` method if the
model is not a generated table model.
If anyone has a better way to prevent the models from being registered then I
am happy to hear about it! :)
"""
original = self.apps.register_model
def register_model(app_label, model):
if (
not hasattr(model, '_generated_table_model') and
not hasattr(model._meta.auto_created, '_generated_table_model')
):
return original(app_label, model)
self.apps.register_model = register_model
def ready(self):
self.prevent_generated_model_for_registering()
from .plugins import DatabasePlugin
plugin_registry.register(DatabasePlugin())
from .fields.field_types import (
TextFieldType, LongTextFieldType, URLFieldType, NumberFieldType,
BooleanFieldType, DateFieldType, LinkRowFieldType, EmailFieldType,
FileFieldType
)
field_type_registry.register(TextFieldType())
field_type_registry.register(LongTextFieldType())
field_type_registry.register(URLFieldType())
field_type_registry.register(EmailFieldType())
field_type_registry.register(NumberFieldType())
field_type_registry.register(BooleanFieldType())
field_type_registry.register(DateFieldType())
field_type_registry.register(LinkRowFieldType())
field_type_registry.register(FileFieldType())
from .fields.field_converters import LinkRowFieldConverter, FileFieldConverter
field_converter_registry.register(LinkRowFieldConverter())
field_converter_registry.register(FileFieldConverter())
from .views.view_types import GridViewType
view_type_registry.register(GridViewType())
from .views.view_filters import (
EqualViewFilterType, NotEqualViewFilterType, EmptyViewFilterType,
NotEmptyViewFilterType, DateEqualViewFilterType, DateNotEqualViewFilterType,
HigherThanViewFilterType, LowerThanViewFilterType, ContainsViewFilterType,
ContainsNotViewFilterType, BooleanViewFilterType
)
view_filter_type_registry.register(EqualViewFilterType())
view_filter_type_registry.register(NotEqualViewFilterType())
view_filter_type_registry.register(ContainsViewFilterType())
view_filter_type_registry.register(ContainsNotViewFilterType())
view_filter_type_registry.register(HigherThanViewFilterType())
view_filter_type_registry.register(LowerThanViewFilterType())
view_filter_type_registry.register(DateEqualViewFilterType())
view_filter_type_registry.register(DateNotEqualViewFilterType())
view_filter_type_registry.register(BooleanViewFilterType())
view_filter_type_registry.register(EmptyViewFilterType())
view_filter_type_registry.register(NotEmptyViewFilterType())
from .application_types import DatabaseApplicationType
application_type_registry.register(DatabaseApplicationType())
| 47.704545
| 88
| 0.738209
|
4a0de437899a4b8987f89c11cd7926641a667ef0
| 3,267
|
py
|
Python
|
test/Alias/srcdir.py
|
moroten/scons
|
20927b42ed4f0cb87f51287fa3b4b6cf915afcf8
|
[
"MIT"
] | 1
|
2017-01-28T15:39:07.000Z
|
2017-01-28T15:39:07.000Z
|
test/Alias/srcdir.py
|
moroten/scons
|
20927b42ed4f0cb87f51287fa3b4b6cf915afcf8
|
[
"MIT"
] | 4
|
2019-04-11T16:27:45.000Z
|
2019-04-11T23:56:30.000Z
|
test/Alias/srcdir.py
|
moroten/scons
|
20927b42ed4f0cb87f51287fa3b4b6cf915afcf8
|
[
"MIT"
] | 2
|
2018-01-16T11:29:16.000Z
|
2020-05-13T16:48:26.000Z
|
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that an Alias for a VariantDir()'s source directory works as
expected.
This tests for a 0.96.93 bug uncovered by the LilyPond project's build.
The specific problem is that, in 0.96.93, the simple act of trying to
disambiguate a target file in the VariantDir() would call srcnode(), which
would create a "phantom" Node for the target in the *source* directory:
+-minimal
+-python
+-foo <= this doesn't belong!
+-foo.py
+-out-scons
+-foo <= this is all right
+-foo.py
As part of deciding if the 'minimal' Alias is up-to-date, the 'python'
source directory would get scanned for files, including the "phantom"
'python/foo' target Node. Since this didn't exist, the build would die:
scons: *** Source `python/foo' not found, needed by target `minimal'. Stop.
The specific 0.96.94 solution was to make the Node.FS.Entry.disambiguate()
smarter about looking on disk. Future versions may solve this in other
ways as the architecture evolves, of course, but this will still make
for good test case regardless.
"""
import TestSCons
test = TestSCons.TestSCons()
test.subdir('python')
test.write('SConstruct', """\
import os.path
env = Environment ()
def at_copy_ext (target, source, env):
n = str (source[0])
s = open (n, 'rb').read ()
e = os.path.splitext (n)[1]
t = str (target[0]) + e
open (t, 'wb').write (s)
AT_COPY_EXT = Builder (action = at_copy_ext, src_suffix=['.py', '.sh',])
env.Append (BUILDERS = {'AT_COPY_EXT': AT_COPY_EXT})
env.Alias ('minimal', ['python'])
Export ('env')
b = 'python/out-scons'
env.VariantDir(b, 'python', duplicate=0)
SConscript(b + '/SConscript')
""")
test.write(['python', 'SConscript'], """\
Import ('env')
env.AT_COPY_EXT('foo.py')
""")
test.write(['python', 'foo.py'], 'python/foo.py\n')
test.run('minimal')
test.must_match(['python', 'out-scons', 'foo.py'], "python/foo.py\n")
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| 30.53271
| 80
| 0.698806
|
4a0de4d1c8f586e3679502bba568a478ad163240
| 1,578
|
py
|
Python
|
Chapter08/dashboard-full/runnerly/dashboard/views/proxy.py
|
mtianyan/PythonMicroservicesDevelopment_Code
|
a99c6c18dfb40e790aa4a5e24ff5eba495e64743
|
[
"Apache-2.0"
] | 7
|
2019-01-14T01:11:32.000Z
|
2022-01-17T16:28:56.000Z
|
runnerly/dashboard/views/proxy.py
|
Runnerly/dashboard
|
60e036226f7ca880d60f704317556a26bdfd105b
|
[
"Apache-2.0"
] | null | null | null |
runnerly/dashboard/views/proxy.py
|
Runnerly/dashboard
|
60e036226f7ca880d60f704317556a26bdfd105b
|
[
"Apache-2.0"
] | 2
|
2019-01-14T00:51:49.000Z
|
2020-08-13T03:18:27.000Z
|
import requests
from flakon import JsonBlueprint
from flask import Blueprint, abort, session, jsonify
from flask import current_app as app
proxy = JsonBlueprint('proxy', __name__)
def email_to_uid(email):
return 1
def get_token():
data = [('client_id', app.config['TOKENDEALER_CLIENT_ID']),
('client_secret', app.config['TOKENDEALER_CLIENT_SECRET']),
('audience', 'runnerly.io'),
('grant_type', 'client_credentials')]
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
url = app.config['TOKENDEALER'] + '/oauth/token'
resp = requests.post(url, data=data, headers=headers)
return resp.json()['access_token']
_TOKEN = 'NOT_SET'
def get_auth_header(new=False):
global _TOKEN
if _TOKEN is None or new:
_TOKEN = get_token()
return 'Bearer ' + _TOKEN
def call_data_service(endpoint):
token = get_auth_header()
resp = requests.get(app.config['DATASERVICE'] + endpoint,
headers={'Authorization': token})
if resp.status_code == 401:
# the token might be revoked
token = get_auth_header(new=True)
resp = requests.get(app.config['DATASERVICE'] + endpoint,
headers={'Authorization': token})
return resp
@proxy.route('/api/runs/<int:year>/<int:month>')
def runs(year, month):
if 'user' not in session:
abort(401)
uid = email_to_uid(session['user'])
endpoint = '/runs/%d/%d/%d' % (uid, year, month)
resp = call_data_service(endpoint)
return jsonify(resp.json())
| 27.206897
| 71
| 0.641952
|
4a0de5b154a96135e40d919cb7a28b25d9526168
| 461
|
py
|
Python
|
examples/all_pico_leds.py
|
unPi-ro/sonar.glass
|
4349383c2551689618fc9165026ca6947d96c3d6
|
[
"BSD-3-Clause"
] | null | null | null |
examples/all_pico_leds.py
|
unPi-ro/sonar.glass
|
4349383c2551689618fc9165026ca6947d96c3d6
|
[
"BSD-3-Clause"
] | null | null | null |
examples/all_pico_leds.py
|
unPi-ro/sonar.glass
|
4349383c2551689618fc9165026ca6947d96c3d6
|
[
"BSD-3-Clause"
] | null | null | null |
from machine import Pin, Timer
# Red on the tiny Pico
rgbRed = Pin(18, Pin.OUT)
# Green on the tiny Pico
rgbGreen = Pin(19, Pin.OUT)
# Blue on the tiny Pico
rgbBlue = Pin(20, Pin.OUT)
# from https://github.com/raspberrypi/pico-micropython-examples/blob/master/blink/blink.py
# always Green on the (standard) Pico
led = Pin(25, Pin.OUT)
timer = Timer()
def tick(timer):
global led
led.toggle()
timer.init(freq=1, mode=Timer.PERIODIC, callback=tick)
| 21.952381
| 90
| 0.713666
|
4a0de69e6cbe7454f6fafaf0e0f020230819a583
| 1,477
|
py
|
Python
|
sphinxcontrib/svgbob/directive.py
|
althonos/sphinxcontrib.svgbob
|
42af9079059a29b747329c0012b823fe51f69f4e
|
[
"MIT"
] | 3
|
2021-07-23T03:37:51.000Z
|
2021-12-13T13:26:16.000Z
|
sphinxcontrib/svgbob/directive.py
|
sphinx-contrib/svgbob
|
42af9079059a29b747329c0012b823fe51f69f4e
|
[
"MIT"
] | null | null | null |
sphinxcontrib/svgbob/directive.py
|
sphinx-contrib/svgbob
|
42af9079059a29b747329c0012b823fe51f69f4e
|
[
"MIT"
] | null | null | null |
import typing
import sphinx.errors
from docutils.nodes import Node
from docutils.parsers.rst import directives
from sphinx.ext.graphviz import align_spec
from sphinx.util.docutils import SphinxDirective
from .node import svgbob
class SvgbobError(sphinx.errors.SphinxError):
category = "Svgbob error"
class SvgbobDirective(SphinxDirective):
"""Sphinx directive to convert ASCII diagrams to Svgbob nodes.
"""
has_content = True
required_arguments = 0
optional_arguments = 3
final_argument_whitespace = False
option_spec = {
# Svgbob options
"font-size": int,
"font-family": directives.unchanged,
"fill-color": directives.unchanged,
"background-color": directives.unchanged,
"stroke-color": directives.unchanged,
"stroke-width": float,
"scale": float,
# HTML options
"align": align_spec,
"class": directives.class_option,
}
def run(self) -> typing.List[Node]:
document = self.state.document
source: str = "\n".join(self.content)
nodes: typing.List[Node] = []
node = svgbob()
node["code"] = source
node["options"] = self.options.copy()
classes = ["svgbob"]
node["classes"] = classes + self.options.get("class", [])
if "align" in self.options:
node["align"] = self.options["align"]
self.add_name(node)
nodes.append(node)
return nodes
| 26.375
| 66
| 0.633717
|
4a0de85a139428a9efba1aadbea38226b8ef02ea
| 267
|
py
|
Python
|
examples/Supervised_simul_MT/models/__init__.py
|
ashkanalinejad/Supervised-Simultaneous-MT
|
d09397ed86bbf4133d5d9b906030a8881ee4c13f
|
[
"MIT"
] | 2
|
2022-01-11T19:27:11.000Z
|
2022-01-12T11:06:53.000Z
|
examples/Supervised_simul_MT/models/__init__.py
|
sfu-natlang/Supervised-Simultaneous-MT
|
12c3a53887c985ae24199ecef2f7b2335fe214c6
|
[
"MIT"
] | 1
|
2022-02-12T03:02:52.000Z
|
2022-02-12T04:27:10.000Z
|
examples/Supervised_simul_MT/models/__init__.py
|
sfu-natlang/Supervised-Simultaneous-MT
|
12c3a53887c985ae24199ecef2f7b2335fe214c6
|
[
"MIT"
] | 1
|
2022-02-27T14:22:36.000Z
|
2022-02-27T14:22:36.000Z
|
import importlib
import os
for file in os.listdir(os.path.dirname(__file__)):
if file.endswith('.py') and not file.startswith('_'):
model_name = file[:file.find('.py')]
importlib.import_module('examples.Supervised_simul_MT.models.' + model_name)
| 33.375
| 84
| 0.70412
|
4a0de896eece20ca91bfbbc50822cd3d4fb95819
| 4,443
|
py
|
Python
|
repo/script.module.urlresolver/lib/urlresolver/plugins/vkpass.py
|
Hades01/Addons
|
710da97ac850197498a3cd64be1811c593610add
|
[
"Apache-2.0"
] | null | null | null |
repo/script.module.urlresolver/lib/urlresolver/plugins/vkpass.py
|
Hades01/Addons
|
710da97ac850197498a3cd64be1811c593610add
|
[
"Apache-2.0"
] | null | null | null |
repo/script.module.urlresolver/lib/urlresolver/plugins/vkpass.py
|
Hades01/Addons
|
710da97ac850197498a3cd64be1811c593610add
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
VKPass urlresolver XBMC Addon based on VKResolver
Copyright (C) 2015 Seberoth
Version 0.0.1
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
import xbmcgui
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class VKPassResolver(UrlResolver):
name = "VKPass.com"
domains = ["vkpass.com"]
pattern = '(?://|\.)(vkpass\.com)/token/(.+)'
def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
base_url = self.get_url(host, media_id)
soup = self.net.http_GET(base_url).content
html = soup.decode('cp1251')
vBlocks = re.findall('{(file.*?label.*?)}', html)
html5 = re.findall('}\((.*?)\)\)<', html)
if not vBlocks and not html5:
raise ResolverError('No vsource found')
data = dict()
data['purged_jsonvars'] = {}
data['lines'] = []
data['best'] = '0'
if html5:
for source in html5:
params = source.split(',')
data = self.__decodeLinks(params[0], params[3].split('|'), data)
elif vBlocks:
data = self.__getFlashVids()
data['lines'] = sorted(data['lines'], key=int)
if len(data['lines']) == 1:
return data['purged_jsonvars'][data['lines'][0]].encode('utf-8')
else:
if self.get_setting('auto_pick') == 'true':
return data['purged_jsonvars'][str(data['best'])].encode('utf-8') + '|User-Agent=%s' % (common.IE_USER_AGENT)
else:
result = xbmcgui.Dialog().select('Choose the link', data['lines'])
if result != -1:
return data['purged_jsonvars'][data['lines'][result]].encode('utf-8') + '|User-Agent=%s' % (common.IE_USER_AGENT)
else:
raise ResolverError('No link selected')
def __decodeLinks(self, html, list, data):
if "source" not in list:
return data
numerals = "0123456789abcdefghijklmnopqrstuvwxyz"
letters = re.findall('([0-9a-z])', html)
for letter in letters:
html = re.sub('\\b' + letter + '\\b', list[numerals.index(letter)], html)
sources = re.findall('<source.*?>', html)
for source in sources:
url = re.findall('src="(.*?)"', source)
res = re.findall('res="(.*?)"', source)
data['lines'].append(res[0])
data['purged_jsonvars'][res[0]] = url[0]
if int(res[0]) > int(data['best']): data['best'] = res[0]
return data
def __getFlashVids(self, vBlocks, data):
for block in vBlocks:
vItems = re.findall('([a-z]*):"(.*?)"', block)
if vItems:
quality = ''
url = ''
for item in vItems:
if 'file' in item[0]:
url = item[1]
if 'label' in item[0]:
quality = re.sub("[^0-9]", "", item[1])
data['lines'].append(quality)
if int(quality) > int(data['best']): data['best'] = quality
data['purged_jsonvars'][quality] = url
return data
def get_url(self, host, media_id):
return 'http://vkpass.com/token/%s' % media_id
def get_host_and_id(self, url):
r = re.search(self.pattern, url)
if r:
return r.groups()
else:
return False
def valid_url(self, url, host):
return re.search(self.pattern, url) or self.name in host
@classmethod
def get_settings_xml(cls):
xml = super(cls, cls).get_settings_xml()
xml.append('<setting id="%s_auto_pick" type="bool" label="Automatically pick best quality" default="false" visible="true"/>' % (cls.__name__))
return xml
| 35.544
| 150
| 0.571461
|
4a0de984bdf2716ab1f1e4c4ebf9053954bbb177
| 4,184
|
py
|
Python
|
ltr/data/transforms.py
|
CASIA-IVA-Lab/DCFST
|
ca881ba3aae1ce00e4a7a6db01d99e5f6efff68b
|
[
"Apache-2.0"
] | 22
|
2020-07-22T13:58:36.000Z
|
2021-12-01T01:48:44.000Z
|
ltr/data/transforms.py
|
CASIA-IVA-Lab/DCFST
|
ca881ba3aae1ce00e4a7a6db01d99e5f6efff68b
|
[
"Apache-2.0"
] | 3
|
2020-08-03T02:23:47.000Z
|
2021-04-09T01:21:58.000Z
|
ltr/data/transforms.py
|
CASIA-IVA-Lab/DCFST
|
ca881ba3aae1ce00e4a7a6db01d99e5f6efff68b
|
[
"Apache-2.0"
] | 4
|
2020-09-26T00:01:51.000Z
|
2021-08-05T09:58:30.000Z
|
import random
import numpy as np
import math
import cv2 as cv
import torch
import torch.nn.functional as F
class Transform:
""" Class for applying various image transformations."""
def __call__(self, *args):
rand_params = self.roll()
if rand_params is None:
rand_params = ()
elif not isinstance(rand_params, tuple):
rand_params = (rand_params,)
output = [self.transform(img, *rand_params) for img in args]
if len(output) == 1:
return output[0]
return output
def roll(self):
return None
def transform(self, img, *args):
"""Must be deterministic"""
raise NotImplementedError
class Compose:
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, *args):
for t in self.transforms:
if not isinstance(args, tuple):
args = (args,)
args = t(*args)
return args
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class ToTensorAndJitter(Transform):
""" Convert to a Tensor and jitter brightness"""
def __init__(self, brightness_jitter=0.0):
self.brightness_jitter = brightness_jitter
def roll(self):
return np.random.uniform(max(0, 1 - self.brightness_jitter), 1 + self.brightness_jitter)
def transform(self, img, brightness_factor):
# handle numpy array
img = torch.from_numpy(img.transpose((2, 0, 1)))
# backward compatibility
return img.float().mul(brightness_factor/255.0).clamp(0.0,1.0)
class ToGrayscale(Transform):
"""Converts image to grayscale with probability"""
def __init__(self, probability = 0.5):
self.probability = probability
self.color_weights = np.array([0.2989, 0.5870, 0.1140], dtype=np.float32)
def roll(self):
return random.random() < self.probability
def transform(self, img, do_grayscale):
if do_grayscale:
if isinstance(img, torch.Tensor):
raise NotImplementedError('Implement torch variant.')
img_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
return np.stack([img_gray, img_gray, img_gray], axis=2)
# return np.repeat(np.sum(img * self.color_weights, axis=2, keepdims=True).astype(np.uint8), 3, axis=2)
return img
class RandomHorizontalFlip(Transform):
"""Horizontally flip the given NumPy Image randomly with a probability p."""
def __init__(self, probability = 0.5):
self.probability = probability
def roll(self):
return random.random() < self.probability
def transform(self, img, do_flip):
if do_flip:
if isinstance(img, torch.Tensor):
return img.flip((2,))
return np.fliplr(img).copy()
return img
class Blur(Transform):
""" Blur the image by applying a gaussian kernel with given sigma"""
def __init__(self, sigma):
if isinstance(sigma, (float, int)):
sigma = (sigma, sigma)
self.sigma = sigma
self.filter_size = [math.ceil(2*s) for s in self.sigma]
x_coord = [torch.arange(-sz, sz+1, dtype=torch.float32) for sz in self.filter_size]
self.filter = [torch.exp(-(x**2)/(2*s**2)) for x, s in zip(x_coord, self.sigma)]
self.filter[0] = self.filter[0].view(1,1,-1,1) / self.filter[0].sum()
self.filter[1] = self.filter[1].view(1,1,1,-1) / self.filter[1].sum()
def transform(self, img):
if isinstance(img, torch.Tensor):
sz = img.shape[2:]
im1 = F.conv2d(img.view(-1, 1, sz[0], sz[1]), self.filter[0], padding=(self.filter_size[0], 0))
return F.conv2d(im1, self.filter[1], padding=(0,self.filter_size[1])).view(-1,sz[0],sz[1])
else:
raise NotImplementedError
| 33.206349
| 115
| 0.613528
|
4a0de9bb1031c3779a6469804ba54f0a3690fdb1
| 766
|
py
|
Python
|
LearnPython3/funcArgs.py
|
balajithangamani/LearnPy
|
87aac13314687f06e54db00c656386db8249a1a0
|
[
"MIT"
] | null | null | null |
LearnPython3/funcArgs.py
|
balajithangamani/LearnPy
|
87aac13314687f06e54db00c656386db8249a1a0
|
[
"MIT"
] | null | null | null |
LearnPython3/funcArgs.py
|
balajithangamani/LearnPy
|
87aac13314687f06e54db00c656386db8249a1a0
|
[
"MIT"
] | null | null | null |
def showname(name, age=60):
'Function simply displays the inputs'
print("Name", name)
print("Age", age)
def showname2(name, *vartuple, **vardict):
'Advanced version of showname function'
print("Name", ':', name)
for tup_arg in vartuple:
print(tup_arg, sep=':')
for key in vardict:
print(key,':', vardict[key])
showname("Anna")
showname("Bala", 34)
showname(34, "Bala")
# showname(34, name="Poda") #TypeError: showname() got multiple values for argument 'name'
# showname(name="Soma", 50) #SyntaxError: positional argument follows keyword argument
showname(age=78, name="hijnb")
showname("noname", age=8)
showname2("jack black")
showname2("balaji", 16, 'M', 'Chennai')
showname2("balaji", 16, sex='M', city='Chennai')
| 28.37037
| 90
| 0.667102
|
4a0dea8ab15058256ad6e2f697d82fec912c7a9f
| 3,648
|
py
|
Python
|
erplicense/migrations/0001_initial.py
|
GolamMullick/HR_PROJECT
|
fc4c76cfc835ad014a62a3da9d32b8fc8d474397
|
[
"MIT"
] | null | null | null |
erplicense/migrations/0001_initial.py
|
GolamMullick/HR_PROJECT
|
fc4c76cfc835ad014a62a3da9d32b8fc8d474397
|
[
"MIT"
] | 3
|
2020-02-12T02:52:01.000Z
|
2021-06-10T22:18:25.000Z
|
erplicense/migrations/0001_initial.py
|
GolamMullick/HR_PROJECT
|
fc4c76cfc835ad014a62a3da9d32b8fc8d474397
|
[
"MIT"
] | null | null | null |
# Generated by Django 2.1.4 on 2019-11-14 10:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CompanyUsers',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(blank=True, null=True)),
('deleted_at', models.DateTimeField(blank=True, null=True)),
('is_active', models.BooleanField(default=True)),
('is_owner', models.BooleanField(default=False)),
('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Company')),
],
),
migrations.CreateModel(
name='License',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(blank=True, null=True)),
('deleted_at', models.DateTimeField(blank=True, null=True)),
('is_active', models.BooleanField(default=True)),
('type', models.CharField(blank=True, max_length=191, null=True)),
('duration', models.IntegerField(blank=True, default=30, null=True)),
('start_date', models.DateTimeField(blank=True, null=True)),
('end_date', models.DateTimeField(blank=True, null=True)),
('status', models.BooleanField(default=True)),
('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Company')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Modules',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=191, unique=True)),
('slug', models.CharField(max_length=191, unique=True)),
('description', models.TextField(blank=True)),
('status', models.BooleanField(default=True)),
],
),
migrations.AddField(
model_name='license',
name='module',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='erplicense.Modules'),
),
migrations.AddField(
model_name='companyusers',
name='module',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='erplicense.Modules'),
),
migrations.AddField(
model_name='companyusers',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterUniqueTogether(
name='license',
unique_together={('company', 'module')},
),
migrations.AlterUniqueTogether(
name='companyusers',
unique_together={('company', 'user', 'module', 'is_owner')},
),
]
| 45.037037
| 147
| 0.593202
|
4a0dead962e9c00fbbcda764712e8aeda0119c5e
| 6,252
|
py
|
Python
|
project/rrt_planner/robot.py
|
czeng6/6881-f19-brian-catherine
|
6b84d5b82986e66702a01968d6d288ca62e51c2e
|
[
"MIT"
] | null | null | null |
project/rrt_planner/robot.py
|
czeng6/6881-f19-brian-catherine
|
6b84d5b82986e66702a01968d6d288ca62e51c2e
|
[
"MIT"
] | null | null | null |
project/rrt_planner/robot.py
|
czeng6/6881-f19-brian-catherine
|
6b84d5b82986e66702a01968d6d288ca62e51c2e
|
[
"MIT"
] | null | null | null |
from .geometry import Point, Pose, Polygon, Object
import random
from math import ceil, sqrt
class Robot:
"""
A Robot is a set of convex polygons.
"""
def __init__(self, polys):
self.polys = polys
self.radius = None
# Creates an Object with reference point at the specified conf.
def configuration(self, configuration): # [x, y, theta]
assert len(configuration) == 3
return Object(Point(configuration[0], configuration[1]),
[poly.rotate(configuration[2]) for poly in self.polys])
def get_radius(self): # radius of robot
if self.radius is None:
self.radius = max([poly.get_radius() for poly in self.polys])
return self.radius
def distance(self, configuration): # configuration distance
return sqrt(configuration[0]*configuration[0] + configuration[1]*configuration[1]) + \
self.get_radius()*abs(configuration[2])
def __repr__(self):
return 'Robot: (' + str(self.polys) + ')'
def __hash__(self):
return str(self).__hash__()
__str__ = __repr__
class RobotArm:
"""
A robot arm with rotating joints.
"""
def __init__(self, reference, joints):
self.reference = reference # a Point
# The joint Point is location of joint at zero configuration
# The joint Polygon is link relative to that location
# This definition could be generalized a bit...
self.joints = joints # [(Point, Polygon)...]
# Creates an instance of robot at the specified configuration
def configuration(self, configuration): #[theta_1, theta_2, ..., theta_n]
assert len(configuration) == len(self.joints)
polys = []
origin = None
angle = None
for i in range(len(configuration)):
(joint, link) = self.joints[i]
if origin == None:
angle = configuration[i]
origin = joint.rotate(angle)
else:
origin += joint.rotate(angle)
angle += configuration[i]
polys.append(link.at_pose(Pose(origin, angle)))
return Object(self.reference, polys)
def distance(self, configuration): # configuration distance
assert len(configuration) == len(self.joints)
return max([abs(configuration[i])*self.joints[i][1].get_radius() \
for i in range(len(configuration))])
def __repr__(self):
return 'RobotArm: (' + self.reference + ', ' + str(self.joints) + ')'
def __hash__(self):
return str(self).__hash__()
__str__ = __repr__
# Below are classes for defining the ranges of values of the joints.
# These classes are generic, they don't depend on the particular
# robot.
class Range:
"""
range of values, handles wraparound.
"""
def __init__(self, low, high, wrap_around = False):
self.low = low
self.high = high
self.wrap_around = wrap_around
def difference(self, one, two): # difference (with wraparound)
if self.wrap_around:
if one < two:
if abs(two - one) < abs((self.low - one) + (two - self.high)):
return two - one
else:
return (self.low - one) + (two - self.high)
else:
if abs(two - one) < abs((self.high - one) + (two - self.low)):
return two - one
else:
return (self.high - one) + (two - self.low)
else:
return two - one
def in_range(self, value): # test if in range
if self.wrap_around:
altered = value
while not (self.low <= altered <= self.high):
if altered > self.high:
altered -= (self.high - self.low)
else:
altered += (self.high - self.low)
return altered
else:
if self.contains(value):
return value
else:
return None
def sample(self): # sample random value
return (self.high - self.low)*random.random() + self.low
def contains(self, x):
return self.wrap_around or (x >= self.low and x <= self.high)
class ConfigurationSpace:
"""
Cspace for robot (ranges and distance)
"""
def __init__(self, cspace_ranges, robot_distance, max_steps):
self.cspace_ranges = cspace_ranges
self.robot_distance = robot_distance
self.max_diff_on_path = max_steps
def distance(self, one: tuple, two: tuple): # distance in Cspace
a = [self.cspace_ranges[i].difference(one[i], two[i]) for i in range(len(self.cspace_ranges))]
return self.robot_distance(tuple(a))
def path(self, one: tuple, two: tuple): # linear interpolation
assert self.valid_configuration(one) and self.valid_configuration(two)
diffs = [self.cspace_ranges[i].difference(one[i], two[i]) \
for i in range(len(self.cspace_ranges))]
samples = max([int(ceil(abs(diff)/max_diff)) \
for diff,max_diff in zip(diffs, self.max_diff_on_path)])
samples = max(2, samples)
linear_interpolation = [diff/(samples - 1.0) for diff in diffs]
path = [one]
for s in range(1, samples-1):
sample = tuple([self.cspace_ranges[i].in_range(one[i] + s*linear_interpolation[i]) \
for i in range(len(self.cspace_ranges))])
# return path
path.append(sample)
return path + [two]
def sample(self): # sample random configuration
'''Samples a random configuration in this ConfigurationSpace
Returns:
3-tuple of floats (x, y, theta) in this ConfigurationSpace
'''
return tuple([r.sample() for r in self.cspace_ranges])
def valid_configuration(self, config): # validity test (in ranges)
return len(config) == len(self.cspace_ranges) and \
all([self.cspace_ranges[i].contains(config[i]) \
for i in range(len(self.cspace_ranges))])
| 36.561404
| 102
| 0.574536
|
4a0debafff7a7339e78e85a9c72073e420a8c2f5
| 1,261
|
py
|
Python
|
ritual/__main__.py
|
kerighan/ritual
|
87bacfc68adb6e84a312c44e54bbef058f0bd4e8
|
[
"MIT"
] | 4
|
2019-11-20T12:21:31.000Z
|
2021-02-09T11:06:37.000Z
|
ritual/__main__.py
|
kerighan/ritual
|
87bacfc68adb6e84a312c44e54bbef058f0bd4e8
|
[
"MIT"
] | null | null | null |
ritual/__main__.py
|
kerighan/ritual
|
87bacfc68adb6e84a312c44e54bbef058f0bd4e8
|
[
"MIT"
] | 1
|
2021-08-20T07:37:33.000Z
|
2021-08-20T07:37:33.000Z
|
from .editor import start_server, list_saved_files
import argparse
import sys
import os
def main():
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--editor",
help="starts Anubis editor",
action="store_true")
parser.add_argument("-f", help="which folder to start")
parser.add_argument("-p",
const=5000,
nargs="?",
help="on which port to start the webserver")
parser.add_argument("--packages",
nargs='+',
help="libraries of boxes")
args = parser.parse_args()
# instantiate Anubis
if args.editor:
from flask_socketio import SocketIO
app = start_server(args)
# app.run(host="0.0.0.0", debug=False, port=args.p)
socketio = SocketIO(app)
socketio.run(app, debug=True, port=args.p)
else:
from . import load_graph
if args.f:
filename = args.f
else:
filenames = list_saved_files()
filename = "graphs/" + filenames[0] + ".json"
print(f"Running graph: {filename}")
ritual = load_graph(filename)
ritual.run()
| 30.02381
| 68
| 0.546392
|
4a0dec2468e73695c9fe2cbd89a767688fea3001
| 165
|
py
|
Python
|
landsat_cogeo_mosaic/__init__.py
|
kylebarron/landsat-cogeo-mosaic
|
ca029d18b8decad3dd5445dd0b62dd5df1e5abda
|
[
"MIT"
] | 3
|
2020-04-01T16:01:46.000Z
|
2021-01-12T23:18:02.000Z
|
landsat_cogeo_mosaic/__init__.py
|
kylebarron/landsat-cogeo-mosaic
|
ca029d18b8decad3dd5445dd0b62dd5df1e5abda
|
[
"MIT"
] | 17
|
2020-03-20T06:12:29.000Z
|
2020-09-25T04:30:35.000Z
|
landsat_cogeo_mosaic/__init__.py
|
kylebarron/landsat-cogeo-mosaic
|
ca029d18b8decad3dd5445dd0b62dd5df1e5abda
|
[
"MIT"
] | null | null | null |
__author__ = """Kyle Barron"""
__email__ = 'kylebarron2@gmail.com'
__version__ = '0.2.1'
from .mosaic import features_to_mosaicJSON
from .stac import fetch_sat_api
| 23.571429
| 42
| 0.769697
|
4a0deca8691e326d16c49dd4461e5d33b890bff9
| 2,410
|
py
|
Python
|
examples/use_cases/use_case_38_1L2S_qflux.py
|
ketozhang/MulensModel
|
cad22055b4c18f2ddc5a20de64240d2286cc23be
|
[
"MIT"
] | 30
|
2016-08-30T23:32:43.000Z
|
2022-03-07T20:06:25.000Z
|
examples/use_cases/use_case_38_1L2S_qflux.py
|
ketozhang/MulensModel
|
cad22055b4c18f2ddc5a20de64240d2286cc23be
|
[
"MIT"
] | 25
|
2018-08-22T19:14:22.000Z
|
2022-03-28T17:22:56.000Z
|
examples/use_cases/use_case_38_1L2S_qflux.py
|
ketozhang/MulensModel
|
cad22055b4c18f2ddc5a20de64240d2286cc23be
|
[
"MIT"
] | 11
|
2016-10-03T16:00:50.000Z
|
2022-03-23T16:53:54.000Z
|
"""
Fit a binary source event. Allow the flux ratio to be freely fit for KMTC data,
but then constrained for other datasets in the same band.
For example, suppose there is a short-term anomaly that is only covered by KMTC
data. Then, for a binary source fit, the KMTC data constrain q_flux but the
other datasets do not. However, for a self-consistent fit, fits to KMTA and
KMTS data must still track the contribution from the second source because even
if it doesn't *appear* to contribute to the other datasets, it might. Possibly
this is not something you would ever want to do In Real Life, but the point is,
you could if you wanted to.
This use case is not functional. To make it functional, someone needs to track
down an event with appropriate data.
"""
import MulensModel as mm
raise NotImplementedError('Needs fake data.')
# define some fake data
files = ['phot.dat', 'KMTC_I.pysis', 'KMTA_I.pysis', 'KMTS_I.pysis',
'KMTC_V.pysis', 'KMTA_V.pysis', 'KMTS_V.pysis']
bandpasses = ['I'] * 4 + ['V'] * 3
kwargs = {'phot_fmt': 'mag', 'usecols': range(3)}
datasets = [mm.MulensData(file_name=file_, bandpass=bandpass, **kwargs)
for (file_, bandpass) in zip(files, bandpasses)]
# define the model
binary_source_model = mm.Model(
{'t_0_1': 2459000.0, 'u_0_1': 1.5, 't_0_2': 2459007.0, 'u_0_2': 0.01,
't_E': 30.})
# Create my own event class
class MyEvent(mm.Event):
def fit_fluxes(self):
"""
Allow the two source fluxes to be freely fit for some reference
dataset, but then constrain the fluxes for all other datasets in
the same bandpass.
"""
self.fits = []
kmtc_fits = {
1: mm.FitData(model=self.model, dataset=self.datasets[1]),
4: mm.FitData(model=self.model, dataset=self.datasets[4])}
band = {'I': 1, 'V': 4} # This simplies the code below.
for (i, dataset) in enumerate(self.datasets):
if i in kmtc_fits:
fit = kmtc_fits[i]
else:
q_flux = kmtc_fits[band[dataset.bandpass]].source_flux_ratio
fit = mm.FitData(model=self.model, dataset=dataset,
fix_source_flux_ratio=q_flux)
self.fits.append(fit)
# Fit the fluxes
event = MyEvent(model=binary_source_model, datasets=datasets)
print(event.chi2)
print(event.source_fluxes)
print(event.blend_fluxes)
| 38.253968
| 79
| 0.666805
|
4a0ded2fda4d8768a46ded2576d32407b8294882
| 1,916
|
py
|
Python
|
stacks/XIAOMATECH/1.0/services/AMBARI_METRICS/package/scripts/hbase_service.py
|
tvorogme/dataops
|
acfa21df42a20768c004c6630a064f4e38e280b2
|
[
"Apache-2.0"
] | 3
|
2019-08-13T01:44:16.000Z
|
2019-12-10T04:05:56.000Z
|
stacks/XIAOMATECH/1.0/services/AMBARI_METRICS/package/scripts/hbase_service.py
|
tvorogme/dataops
|
acfa21df42a20768c004c6630a064f4e38e280b2
|
[
"Apache-2.0"
] | null | null | null |
stacks/XIAOMATECH/1.0/services/AMBARI_METRICS/package/scripts/hbase_service.py
|
tvorogme/dataops
|
acfa21df42a20768c004c6630a064f4e38e280b2
|
[
"Apache-2.0"
] | 7
|
2019-05-29T17:35:25.000Z
|
2021-12-04T07:55:10.000Z
|
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from resource_management.core.resources.system import Execute, File
from resource_management.libraries.functions.format import format
def hbase_service(name, action='start'): # 'start' or 'stop' or 'status'
import params
role = name
cmd = format("{daemon_script} --config {hbase_conf_dir}")
pid_file = format("{hbase_pid_dir}/hbase-{hbase_user}-{role}.pid")
no_op_test = format(
"ls {pid_file} >/dev/null 2>&1 && ps `cat {pid_file}` >/dev/null 2>&1")
if action == 'start':
daemon_cmd = format("{cmd} start {role}")
Execute(daemon_cmd, not_if=no_op_test, user=params.hbase_user)
elif action == 'stop':
daemon_cmd = format("{cmd} stop {role}")
Execute(
daemon_cmd,
user=params.hbase_user,
# BUGFIX: hbase regionserver sometimes hangs when nn is in safemode
timeout=params.hbase_regionserver_shutdown_timeout,
on_timeout=format(
"{no_op_test} && {sudo} -H -E kill -9 `{sudo} cat {pid_file}`")
)
File(
pid_file,
action="delete",
)
| 34.836364
| 79
| 0.683194
|
4a0dee1c977c7786d255e760f61e6c34a12fb3d0
| 635
|
py
|
Python
|
wagtail/migrations/0046_site_name_remove_null.py
|
stevedya/wagtail
|
52e5abfe62547cdfd90ea7dfeb8bf5a52f16324c
|
[
"BSD-3-Clause"
] | 1
|
2022-02-09T05:25:30.000Z
|
2022-02-09T05:25:30.000Z
|
wagtail/migrations/0046_site_name_remove_null.py
|
stevedya/wagtail
|
52e5abfe62547cdfd90ea7dfeb8bf5a52f16324c
|
[
"BSD-3-Clause"
] | null | null | null |
wagtail/migrations/0046_site_name_remove_null.py
|
stevedya/wagtail
|
52e5abfe62547cdfd90ea7dfeb8bf5a52f16324c
|
[
"BSD-3-Clause"
] | null | null | null |
# Generated by Django 3.0.6 on 2020-05-27 15:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0045_assign_unlock_grouppagepermission"),
]
operations = [
migrations.AlterField(
model_name="site",
name="site_name",
field=models.CharField(
blank=True,
default="",
help_text="Human-readable name for the site.",
max_length=255,
verbose_name="site name",
),
preserve_default=False,
),
]
| 24.423077
| 66
| 0.543307
|
4a0dee36a923c95f0f508dbb3041573d8a63b11c
| 5,376
|
py
|
Python
|
livereload/watcher.py
|
andreycizov/python-livereload
|
2a51a77028911a2b69db1d4f72323966c34b3c1e
|
[
"BSD-3-Clause"
] | null | null | null |
livereload/watcher.py
|
andreycizov/python-livereload
|
2a51a77028911a2b69db1d4f72323966c34b3c1e
|
[
"BSD-3-Clause"
] | null | null | null |
livereload/watcher.py
|
andreycizov/python-livereload
|
2a51a77028911a2b69db1d4f72323966c34b3c1e
|
[
"BSD-3-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
livereload.watcher
~~~~~~~~~~~~~~~~~~
A file watch management for LiveReload Server.
:copyright: (c) 2013 - 2015 by Hsiaoming Yang
:license: BSD, see LICENSE for more details.
"""
import glob
import logging
import os
import time
try:
import pyinotify
except ImportError:
pyinotify = None
logger = logging.getLogger('livereload')
class Watcher(object):
"""A file watcher registery."""
def __init__(self):
self._tasks = {}
self._mtimes = {}
# setting changes
self._changes = []
# filepath that is changed
self.filepath = None
self._start = time.time()
#list of ignored dirs
self.ignored_dirs = ['.git', '.hg', '.svn', '.cvs']
def ignore_dirs(self, *args):
self.ignored_dirs.extend(args)
def remove_dirs_from_ignore(self, *args):
for a in args:
self.ignored_dirs.remove(a)
def ignore(self, filename):
"""Ignore a given filename or not."""
_, ext = os.path.splitext(filename)
return ext in ['.pyc', '.pyo', '.o', '.swp']
def watch(self, path, func=None, delay=0, ignore=None):
"""Add a task to watcher.
:param path: a filepath or directory path or glob pattern
:param func: the function to be executed when file changed
:param delay: Delay sending the reload message. Use 'forever' to
not send it. This is useful to compile sass files to
css, but reload on changed css files then only.
:param ignore: A function return True to ignore a certain pattern of
filepath.
"""
self._tasks[path] = {
'func': func,
'delay': delay,
'ignore': ignore,
}
def start(self, callback):
"""Start the watcher running, calling callback when changes are
observed. If this returns False, regular polling will be used."""
return False
def examine(self):
"""Check if there are changes, if true, run the given task."""
if self._changes:
return self._changes.pop()
# clean filepath
self.filepath = None
delays = set()
for path in self._tasks:
item = self._tasks[path]
if self.is_changed(path, item['ignore']):
func = item['func']
delay = item['delay']
if delay and isinstance(delay, float):
delays.add(delay)
if func:
logger.info("Running task: {} (delay: {})".format(
func.repr_str if hasattr(func, 'repr_str') else str(func), delay))
func()
if delays:
delay = max(delays)
else:
delay = None
return self.filepath, delay
def is_changed(self, path, ignore=None):
if os.path.isfile(path):
return self.is_file_changed(path, ignore)
elif os.path.isdir(path):
return self.is_folder_changed(path, ignore)
return self.is_glob_changed(path, ignore)
def is_file_changed(self, path, ignore=None):
if not os.path.isfile(path):
return False
if self.ignore(path):
return False
if ignore and ignore(path):
return False
mtime = os.path.getmtime(path)
if path not in self._mtimes:
self._mtimes[path] = mtime
self.filepath = path
return mtime > self._start
if self._mtimes[path] != mtime:
self._mtimes[path] = mtime
self.filepath = path
return True
self._mtimes[path] = mtime
return False
def is_folder_changed(self, path, ignore=None):
for root, dirs, files in os.walk(path, followlinks=True):
for d in self.ignored_dirs:
if d in dirs:
dirs.remove(d)
for f in files:
if self.is_file_changed(os.path.join(root, f), ignore):
return True
return False
def is_glob_changed(self, path, ignore=None):
for f in glob.glob(path):
if self.is_file_changed(f, ignore):
return True
return False
class INotifyWatcher(Watcher):
def __init__(self):
Watcher.__init__(self)
self.wm = pyinotify.WatchManager()
self.notifier = None
self.callback = None
def watch(self, path, func=None, delay=None, ignore=None):
flag = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
self.wm.add_watch(path, flag, rec=True, do_glob=True, auto_add=True)
Watcher.watch(self, path, func, delay, ignore)
def inotify_event(self, event):
self.callback()
def start(self, callback):
if not self.notifier:
self.callback = callback
from tornado import ioloop
self.notifier = pyinotify.TornadoAsyncNotifier(
self.wm, ioloop.IOLoop.instance(),
default_proc_fun=self.inotify_event
)
callback()
return True
def get_watcher_class():
if pyinotify is None or not hasattr(pyinotify, 'TornadoAsyncNotifier'):
return Watcher
return INotifyWatcher
| 29.217391
| 90
| 0.567708
|
4a0def386852b29266d324d542be21f3743f9ab2
| 799
|
py
|
Python
|
src/azure-cli/azure/cli/command_modules/storage/operations/cors.py
|
YuanyuanNi/azure-cli
|
63844964374858bfacd209bfe1b69eb456bd64ca
|
[
"MIT"
] | 3,287
|
2016-07-26T17:34:33.000Z
|
2022-03-31T09:52:13.000Z
|
src/azure-cli/azure/cli/command_modules/storage/operations/cors.py
|
YuanyuanNi/azure-cli
|
63844964374858bfacd209bfe1b69eb456bd64ca
|
[
"MIT"
] | 19,206
|
2016-07-26T07:04:42.000Z
|
2022-03-31T23:57:09.000Z
|
src/azure-cli/azure/cli/command_modules/storage/operations/cors.py
|
YuanyuanNi/azure-cli
|
63844964374858bfacd209bfe1b69eb456bd64ca
|
[
"MIT"
] | 2,575
|
2016-07-26T06:44:40.000Z
|
2022-03-31T22:56:06.000Z
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
def list_cors(client, timeout=None):
results = {}
for s in client:
results[s.name] = s.get_cors(timeout)
return results
def add_cors(client, origins, methods, max_age=0, exposed_headers=None, allowed_headers=None, timeout=None):
for s in client:
s.add_cors(origins, methods, max_age, exposed_headers, allowed_headers, timeout)
def clear_cors(client, timeout=None):
for s in client:
s.clear_cors(timeout)
| 36.318182
| 108
| 0.549437
|
4a0def62b4d92b035af7c192dbf84e633fe8ba2e
| 4,941
|
py
|
Python
|
homeassistant/components/hassio/http.py
|
nickna/core
|
c682d5d5e430de52e3da7e06026cd8b4087e864f
|
[
"Apache-2.0"
] | 5
|
2019-02-24T11:46:18.000Z
|
2019-05-28T17:37:21.000Z
|
homeassistant/components/hassio/http.py
|
nickna/core
|
c682d5d5e430de52e3da7e06026cd8b4087e864f
|
[
"Apache-2.0"
] | 77
|
2020-07-16T16:43:09.000Z
|
2022-03-31T06:14:37.000Z
|
homeassistant/components/hassio/http.py
|
nickna/core
|
c682d5d5e430de52e3da7e06026cd8b4087e864f
|
[
"Apache-2.0"
] | 7
|
2021-03-20T12:34:01.000Z
|
2021-12-02T10:13:52.000Z
|
"""HTTP Support for Hass.io."""
from __future__ import annotations
import asyncio
import logging
import os
import re
import aiohttp
from aiohttp import web
from aiohttp.client import ClientTimeout
from aiohttp.hdrs import (
CONTENT_ENCODING,
CONTENT_LENGTH,
CONTENT_TYPE,
TRANSFER_ENCODING,
)
from aiohttp.web_exceptions import HTTPBadGateway
from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView
from homeassistant.components.onboarding import async_is_onboarded
from homeassistant.const import HTTP_UNAUTHORIZED
from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO
_LOGGER = logging.getLogger(__name__)
MAX_UPLOAD_SIZE = 1024 * 1024 * 1024
NO_TIMEOUT = re.compile(
r"^(?:"
r"|homeassistant/update"
r"|hassos/update"
r"|hassos/update/cli"
r"|supervisor/update"
r"|addons/[^/]+/(?:update|install|rebuild)"
r"|backups/.+/full"
r"|backups/.+/partial"
r"|backups/[^/]+/(?:upload|download)"
r"|snapshots/.+/full"
r"|snapshots/.+/partial"
r"|snapshots/[^/]+/(?:upload|download)"
r")$"
)
NO_AUTH_ONBOARDING = re.compile(
r"^(?:" r"|supervisor/logs" r"|backups/[^/]+/.+" r"|snapshots/[^/]+/.+" r")$"
)
NO_AUTH = re.compile(
r"^(?:" r"|app/.*" r"|addons/[^/]+/logo" r"|addons/[^/]+/icon" r")$"
)
class HassIOView(HomeAssistantView):
"""Hass.io view to handle base part."""
name = "api:hassio"
url = "/api/hassio/{path:.+}"
requires_auth = False
def __init__(self, host: str, websession: aiohttp.ClientSession) -> None:
"""Initialize a Hass.io base view."""
self._host = host
self._websession = websession
async def _handle(
self, request: web.Request, path: str
) -> web.Response | web.StreamResponse:
"""Route data to Hass.io."""
hass = request.app["hass"]
if _need_auth(hass, path) and not request[KEY_AUTHENTICATED]:
return web.Response(status=HTTP_UNAUTHORIZED)
return await self._command_proxy(path, request)
delete = _handle
get = _handle
post = _handle
async def _command_proxy(
self, path: str, request: web.Request
) -> web.StreamResponse:
"""Return a client request with proxy origin for Hass.io supervisor.
This method is a coroutine.
"""
headers = _init_header(request)
if path in ("snapshots/new/upload", "backups/new/upload"):
# We need to reuse the full content type that includes the boundary
headers[
"Content-Type"
] = request._stored_content_type # pylint: disable=protected-access
try:
client = await self._websession.request(
method=request.method,
url=f"http://{self._host}/{path}",
params=request.query,
data=request.content,
headers=headers,
timeout=_get_timeout(path),
)
# Stream response
response = web.StreamResponse(
status=client.status, headers=_response_header(client)
)
response.content_type = client.content_type
await response.prepare(request)
async for data in client.content.iter_chunked(4096):
await response.write(data)
return response
except aiohttp.ClientError as err:
_LOGGER.error("Client error on api %s request %s", path, err)
except asyncio.TimeoutError:
_LOGGER.error("Client timeout error on API request %s", path)
raise HTTPBadGateway()
def _init_header(request: web.Request) -> dict[str, str]:
"""Create initial header."""
headers = {
X_HASSIO: os.environ.get("HASSIO_TOKEN", ""),
CONTENT_TYPE: request.content_type,
}
# Add user data
user = request.get("hass_user")
if user is not None:
headers[X_HASS_USER_ID] = request["hass_user"].id
headers[X_HASS_IS_ADMIN] = str(int(request["hass_user"].is_admin))
return headers
def _response_header(response: aiohttp.ClientResponse) -> dict[str, str]:
"""Create response header."""
headers = {}
for name, value in response.headers.items():
if name in (
TRANSFER_ENCODING,
CONTENT_LENGTH,
CONTENT_TYPE,
CONTENT_ENCODING,
):
continue
headers[name] = value
return headers
def _get_timeout(path: str) -> ClientTimeout:
"""Return timeout for a URL path."""
if NO_TIMEOUT.match(path):
return ClientTimeout(connect=10, total=None)
return ClientTimeout(connect=10, total=300)
def _need_auth(hass, path: str) -> bool:
"""Return if a path need authentication."""
if not async_is_onboarded(hass) and NO_AUTH_ONBOARDING.match(path):
return False
if NO_AUTH.match(path):
return False
return True
| 28.560694
| 81
| 0.627201
|
4a0df1fd4fb0eb4e627203d19085aed0ca7831b8
| 2,028
|
py
|
Python
|
isi_mip/climatemodels/migrations/0027_auto_20160602_1210.py
|
ISI-MIP/isimip
|
c2a78c727337e38f3695031e00afd607da7d6dcb
|
[
"MIT"
] | 4
|
2017-07-05T08:06:18.000Z
|
2021-03-01T17:23:18.000Z
|
isi_mip/climatemodels/migrations/0027_auto_20160602_1210.py
|
ISI-MIP/isimip
|
c2a78c727337e38f3695031e00afd607da7d6dcb
|
[
"MIT"
] | 4
|
2020-01-31T09:02:57.000Z
|
2021-04-20T14:04:35.000Z
|
isi_mip/climatemodels/migrations/0027_auto_20160602_1210.py
|
ISI-MIP/isimip
|
c2a78c727337e38f3695031e00afd607da7d6dcb
|
[
"MIT"
] | 4
|
2017-10-12T01:48:55.000Z
|
2020-04-29T13:50:03.000Z
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-02 10:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('climatemodels', '0026_impactmodel_spatial_aggregation'),
]
operations = [
migrations.AlterField(
model_name='impactmodel',
name='main_reference_paper',
field=models.ForeignKey(blank=True, help_text='The single paper that should be cited when referring to simulation output from this model', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='main_ref', to='climatemodels.ReferencePaper', verbose_name='Reference paper: main reference'),
),
migrations.AlterField(
model_name='impactmodel',
name='spatial_aggregation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='climatemodels.SpatialAggregation'),
),
migrations.AlterField(
model_name='inputdata',
name='data_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='climatemodels.ClimateDataType'),
),
migrations.AlterField(
model_name='inputdata',
name='phase',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='climatemodels.InputPhase'),
),
migrations.AlterField(
model_name='inputdata',
name='scenario',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='climatemodels.Scenario'),
),
migrations.AlterField(
model_name='outputdata',
name='model',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='climatemodels.ImpactModel'),
),
]
| 43.148936
| 316
| 0.663708
|
4a0df3f0577390d0f6569e18967ef73e91da8be2
| 2,429
|
py
|
Python
|
tests/unit/test_base64.py
|
weslambert/unfurl
|
b9a65db6842ac9f2c2e8165fc5eebfee4f2918b3
|
[
"Apache-2.0"
] | 1
|
2020-07-23T18:42:44.000Z
|
2020-07-23T18:42:44.000Z
|
tests/unit/test_base64.py
|
weslambert/unfurl
|
b9a65db6842ac9f2c2e8165fc5eebfee4f2918b3
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/test_base64.py
|
weslambert/unfurl
|
b9a65db6842ac9f2c2e8165fc5eebfee4f2918b3
|
[
"Apache-2.0"
] | 2
|
2020-07-06T20:27:07.000Z
|
2020-07-23T18:42:49.000Z
|
from unfurl import Unfurl
import unittest
class TestBase64(unittest.TestCase):
def test_padded_b64_ascii(self):
""" Test a simple ASCII string that is base64-encoded."""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='dGVzdHl0ZXN0dGVzdA==')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 2)
self.assertEqual(test.total_nodes, 2)
# confirm that it was detected as b64
self.assertEqual('b64', test.nodes[2].data_type)
# confirm that text decoded correctly
self.assertEqual('testytesttest', test.nodes[2].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
def test_unpadded_b64_ascii(self):
""" Test a simple ASCII string that is base64-encoded, with padding removed."""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='dGVzdHl0ZXN0dGVzdA')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 2)
self.assertEqual(test.total_nodes, 2)
# confirm that it was detected as b64
self.assertEqual('b64', test.nodes[2].data_type)
# confirm that text decoded correctly
self.assertEqual('testytesttest', test.nodes[2].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
def test_incorrect_padded_b64_ascii(self):
""" Test a simple ASCII string that is base64-encoded, with incorrect padding"""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='dGVzdHl0ZXN0dGVzdA=')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 2)
self.assertEqual(test.total_nodes, 2)
# confirm that it was detected as b64
self.assertEqual('b64', test.nodes[2].data_type)
# confirm that text decoded correctly
self.assertEqual('testytesttest', test.nodes[2].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
| 30.3625
| 88
| 0.629889
|
4a0df4e73fe978f79c0962c07ab64a686a8270b2
| 1,001
|
py
|
Python
|
tests/confdb/engine/test_compile.py
|
prorevizor/noc
|
37e44b8afc64318b10699c06a1138eee9e7d6a4e
|
[
"BSD-3-Clause"
] | 84
|
2017-10-22T11:01:39.000Z
|
2022-02-27T03:43:48.000Z
|
tests/confdb/engine/test_compile.py
|
prorevizor/noc
|
37e44b8afc64318b10699c06a1138eee9e7d6a4e
|
[
"BSD-3-Clause"
] | 22
|
2017-12-11T07:21:56.000Z
|
2021-09-23T02:53:50.000Z
|
tests/confdb/engine/test_compile.py
|
prorevizor/noc
|
37e44b8afc64318b10699c06a1138eee9e7d6a4e
|
[
"BSD-3-Clause"
] | 23
|
2017-12-06T06:59:52.000Z
|
2022-02-24T00:02:25.000Z
|
# ----------------------------------------------------------------------
# Test engine's query compilations
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Third-party modules
import pytest
# NOC modules
from noc.core.confdb.engine.base import Engine
@pytest.mark.parametrize(
"query",
[
"True()",
"True() and True()",
"True() and True() and True()",
"(True() and True())",
"Set(x=1, y=2) and True()",
],
)
def test_valid(query):
e = Engine()
e.compile(query)
@pytest.mark.parametrize("query", ["True("])
def test_invalid(query):
e = Engine()
with pytest.raises(SyntaxError):
e.compile(query)
@pytest.mark.parametrize("query", ["True()", "True() and True()"])
def test_prepared_query(query):
e = Engine()
q = e.compile(query)
e.query(q)
| 23.833333
| 72
| 0.471528
|
4a0df505548f95a23dcef3a7af9f90d190adbba0
| 20,902
|
py
|
Python
|
MDPModel.py
|
klolos/mdpdt
|
28699d67e9a9e8cad53af9671eb3489e5d8b448b
|
[
"MIT"
] | 4
|
2018-12-19T16:50:29.000Z
|
2022-02-09T12:12:01.000Z
|
MDPModel.py
|
klolos/mdpdt
|
28699d67e9a9e8cad53af9671eb3489e5d8b448b
|
[
"MIT"
] | null | null | null |
MDPModel.py
|
klolos/mdpdt
|
28699d67e9a9e8cad53af9671eb3489e5d8b448b
|
[
"MIT"
] | 3
|
2018-10-17T07:41:54.000Z
|
2020-05-09T10:18:59.000Z
|
from __future__ import division
from DecisionMaking.Configuration import ConfigurationError
from DecisionMaking.Constants import *
from DecisionMaking.Exceptions import *
"""
Represents a Q-state in the MDP model
"""
class QState(object):
def __init__(self, action, num_states, qvalue = 0.0):
self.action = action
self.num_taken = 0
self.qvalue = qvalue
self.transitions = [0] * num_states
self.rewards = [0] * num_states
self.num_states = num_states
action_type, action_value = action
if action_type == ADD_VMS:
self.action_name = "Add %s VMs " % action_value
elif action_type == REMOVE_VMS:
self.action_name = "Remove %s VMs" % action_value
else:
self.action_name = "no op "
# TODO the rest of the actions
"""
Updates the transition and reward estimations after the given transition
"""
def update(self, new_state, reward):
self.num_taken += 1
state_num = new_state.get_state_num()
self.transitions[state_num] += 1
self.rewards[state_num] += reward
"""
Returns the action that corresponds to this Q-state
"""
def get_action(self):
return self.action
"""
Returns the q-value of the q-state
"""
def get_qvalue(self):
return self.qvalue
"""
Returns true if the estimated transition probability to the given state is non zero
"""
def has_transition(self, state_num):
return self.transitions[state_num] > 0
"""
Returns the estimated transition probability to the given state.
Returns 1 over the number of states if the action has never been taken
"""
def get_transition(self, state_num):
if self.num_taken == 0:
return 1 / self.num_states
else:
return self.transitions[state_num] / self.num_taken
"""
Returns the number of recorded transitions to the given state
"""
def get_num_transitions(self, state_num):
return self.transitions[state_num]
"""
Returns the estimated reward after taking this action
"""
def get_reward(self, state_num):
if self.transitions[state_num] == 0:
return 0.0
else:
return self.rewards[state_num] / self.transitions[state_num]
"""
The qvalue for this action
"""
def set_qvalue(self, qvalue):
self.qvalue = qvalue
"""
The number of times this action has been taken
"""
def get_num_taken(self):
return self.num_taken
"""
Returns a list containing the number of transitions to each state
"""
def get_transitions(self):
return list(self.transitions)
"""
Returns a list containing the total rewards gained after transitioning to each state
"""
def get_rewards(self):
return list(self.rewards)
"""
String representatin for a Q-state
"""
def __str__(self):
return "Action: %s \tQ-value: %2.3f \tTaken: %d" % \
(self.action_name, self.qvalue, self.num_taken)
def __repr__(self):
return str(self)
"""
Represents a state in the MDP model
"""
class State(object):
def __init__(self, parameters = [], state_num = 0, initial_value = 0, num_states = 0):
self.parameters = list(parameters)
self.qstates = []
self.state_num = state_num
self.num_states = num_states
self.value = 0
self.best_qstate = None
self.num_visited = 0
"""
Increments the number of times the state has been visited
"""
def visit(self):
self.num_visited += 1
"""
The unique number of the state in the MDP model
"""
def get_state_num(self):
return self.state_num
"""
Sets the total number of states in the model
"""
def set_num_states(self, num_states):
self.num_states = num_states
"""
The current value of the state
"""
def get_value(self):
return self.value
"""
Returns the Q-state with the highest q-value
"""
def get_best_qstate(self):
return self.best_qstate
"""
Returns the optimal action for this state
"""
def get_optimal_action(self):
return self.best_qstate.get_action()
"""
Retuns the number of times the optimal action has been executed
"""
def best_action_num_taken(self):
return self.best_qstate.get_num_taken()
"""
Updates the value of the state based on the values of its Q-states
"""
def update_value(self):
self.best_qstate = self.qstates[0]
self.value = self.qstates[0].get_qvalue()
for qs in self.qstates:
if qs.get_qvalue() > self.value:
self.best_qstate = qs
self.value = qs.get_qvalue()
"""
Returns a list containing the names and values of the parameters for this state
"""
def get_parameters(self):
return self.parameters
"""
Adds a new parameter-value pair to the list of parameters that this state represents
"""
def add_new_parameter(self, name, values):
self.parameters.append((name, values))
"""
Returns the value for the given parameter
"""
def get_parameter(self, param):
for par, values in self.parameters:
if par == param:
return values
return None
"""
Adds a new Q-state to this state
"""
def add_qstate(self, qstate):
self.qstates.append(qstate)
if self.best_qstate is None:
self.best_qstate = qstate
"""
Returns the list of Q-states for this state
"""
def get_qstates(self):
return self.qstates
"""
Returns the Q-state that corresponds to the given action
"""
def get_qstate(self, action):
for qs in self.qstates:
if qs.get_action() == action:
return qs
"""
Returns a dict that contains the maximum transition probability for any action
for all the states that there is a non-zero transition probability
"""
def get_max_transitions(self):
transitions = {}
for i in range(self.num_states):
for qs in self.qstates:
if qs.has_transition(i):
if i in transitions:
transitions[i] = max(transitions[i], qs.get_transition(i))
else:
transitions[i] = qs.get_transition(i)
return transitions
"""
Returns all the possible actions from this state
"""
def get_legal_actions(self):
return [qs.get_action() for qs in self.qstates]
"""
String representation for a state
"""
def __str__(self):
return "%d: %s" % (self.state_num, str(self.parameters))
def __repr__(self):
return str(self)
"""
Prints the details of the state and its q-states
"""
def print_detailed(self):
print("%d: %s, visited: %d" % (self.state_num, str(self.parameters), self.num_visited))
for qs in self.get_qstates():
print(qs)
"""
Class that represents a full Markov Decision Process model.
"""
class MDPModel:
"""
Creates a model from a given configuration dict
"""
def __init__(self, conf):
required_fields = [PARAMETERS, ACTIONS, DISCOUNT, INITIAL_QVALUES]
for f in required_fields:
if not f in conf:
raise ConfigurationError("%s not provided in the configuration" % f)
self.discount = conf[DISCOUNT]
self.states = [State()]
self.index_params = []
self.index_states = list(self.states)
self.current_state = None
self.update_error = 0.01
self.max_updates = 100
self._assert_modeled_params(conf)
parameters = self._get_params(conf[PARAMETERS])
# create all the states of the model
for name, param in parameters.items():
self.index_params.append((name, param[VALUES]))
self._update_states(str(name), param)
# set the final number of states to all states
num_states = len(self.states)
for s in self.states:
s.set_num_states(num_states)
self._set_maxima_minima(parameters, conf[ACTIONS])
self._add_qstates(conf[ACTIONS], conf[INITIAL_QVALUES])
# set the default update algorithm
self.update_algorithm = SINGLE_UPDATE
# initialize the reverse transition indexes and priorities for prioritized sweeping
self.reverse_transitions = []
self.priorities = [0] * len(self.states)
for i in range(len(self.states)):
self.reverse_transitions.append({})
"""
Asserts that action dependent parameters are being modeled
"""
def _assert_modeled_params(self, conf):
if ADD_VMS in conf[ACTIONS] or REMOVE_VMS in conf[ACTIONS]:
if not NUMBER_OF_VMS in conf[PARAMETERS]:
raise ConfigurationError("Add/Remove VM actions require %s parameter" % NUMBER_OF_VMS)
# TODO the rest of the actions
"""
The values of each model parameter are represented as a [min, max] touple.
This method asserts that values are provided for all the parameters and converts
distinct values to [min, max] touples.
"""
def _get_params(self, parameters):
new_pars = {}
for name, par in parameters.items():
new_pars[name] = {}
# we convert both values and limits to pairs of limits so we can treat them uniformly
if VALUES in par:
if not isinstance(par[VALUES], list):
raise ConfigurationError("Provided values for %s must be in a list" % name)
if len(par[VALUES]) <= 1:
raise ConfigurationError("At least two values must be provided for " + name)
values = []
for v in par[VALUES]:
values.append((v, v))
new_pars[name][VALUES] = values
elif LIMITS in par:
if not isinstance(par[LIMITS], list):
raise ConfigurationError("Provided limits for %s must be in a list" % name)
if len(par[LIMITS]) <= 2:
raise ConfigurationError("At least three limits must be provided for " + name)
values = []
for i in range(1, len(par[LIMITS])):
values.append((par[LIMITS][i-1], par[LIMITS][i]))
new_pars[name][VALUES] = values
if not VALUES in new_pars[name]:
raise ConfigurationError("Values or limits must be provided for parameter " + name)
return new_pars
"""
Initializes the current state based on the given measurements
"""
def set_state(self, measurements):
self.current_state = self._get_state(measurements)
"""
Extends the current states to include all the possible values of the
given parameter, multiplying their number with the number of values
of the parameter.
"""
def _update_states(self, name, new_parameter):
state_num = 0
new_states = []
for value in new_parameter[VALUES]:
for s in self.states:
new_state = State(s.get_parameters(), state_num)
new_state.add_new_parameter(name, value)
new_states.append(new_state)
state_num += 1
self.states = new_states
"""
Stores the maxima and minima for the parameters that have actions which
need to be limited
"""
def _set_maxima_minima(self, parameters, actions):
if ADD_VMS in actions or REMOVE_VMS in actions:
vm_values = parameters[NUMBER_OF_VMS][VALUES]
self.max_VMs = max([max(x) for x in vm_values])
self.min_VMs = min([min(x) for x in vm_values])
# TODO the rest of the actions
"""
Adds the given actions to all the states
"""
def _add_qstates(self, actions, initial_qvalue):
num_states = len(self.states)
for action_type, values in actions.items():
for action_value in values:
action = (action_type, action_value)
for s in self.states:
if self._is_permissible(s, action):
s.add_qstate(QState(action, num_states, initial_qvalue))
for s in self.states:
s.update_value()
"""
Returns true if we are allowed to take that action from that state
"""
def _is_permissible(self, state, action):
action_type, action_value = action
if action_type == ADD_VMS:
param_values = state.get_parameter(NUMBER_OF_VMS)
return max(param_values) + action_value <= self.max_VMs
elif action_type == REMOVE_VMS:
param_values = state.get_parameter(NUMBER_OF_VMS)
return min(param_values) - action_value >= self.min_VMs
# TODO the rest of the actions
return True
"""
Returns the state that corresponds to given set of measurementes
"""
def _get_state(self, measurements): # TODO this with indexing
for name, values in self.index_params:
if not name in measurements:
raise ParameterError("Missing measurement: " + name)
for s in self.states:
matches = True
for name, values in s.get_parameters():
min_v, max_v = values
if measurements[name] < min_v or measurements[name] > max_v:
matches = False
break
if matches:
return s
"""
Suggest the next action based on the greedy criterion
"""
def suggest_action(self):
if self.current_state is None:
raise StateNotSetError()
return self.current_state.get_optimal_action()
"""
Returns all the legal actions from the current_state
"""
def get_legal_actions(self):
if self.current_state is None:
raise StateNotSetError()
return self.current_state.get_legal_actions()
"""
Stops the model from performing any updates to q-values
"""
def set_no_update(self):
self.update_algorithm = NO_UPDATE
"""
Update only the value of the starting state after each transition
"""
def set_single_update(self):
self.update_algorithm = SINGLE_UPDATE
"""
Perform a full value iteration after each transition
"""
def set_value_iteration(self, update_error):
self.update_algorithm = VALUE_ITERATION
self.update_error = update_error
"""
Perform prioritized sweeping after each transition
"""
def set_prioritized_sweeping(self, update_error, max_updates):
self.update_algorithm = PRIORITIZED_SWEEPING
self.update_error = update_error
self.max_updates = max_updates
"""
Updates the model after taking the given action and ending up in the
state corresponding to the given measurements.
"""
def update(self, action, measurements, reward):
if self.current_state is None:
raise StateNotSetError()
self.current_state.visit()
qstate = self.current_state.get_qstate(action)
if qstate is None:
# TODO log
return
new_state = self._get_state(measurements)
qstate.update(new_state, reward)
#print("old state: %s" % self.current_state)
#print("new state: %s" % new_state)
if self.update_algorithm == SINGLE_UPDATE:
self._q_update(qstate)
self.current_state.update_value()
elif self.update_algorithm == VALUE_ITERATION:
self.value_iteration()
elif self.update_algorithm == PRIORITIZED_SWEEPING:
self.prioritized_sweeping()
self.current_state = new_state
"""
Runs a single update for the Q-value of the given state-action pair.
"""
def _q_update(self, qstate):
new_qvalue = 0
for i in range(len(self.states)):
t = qstate.get_transition(i)
r = qstate.get_reward(i)
new_qvalue += t * (r + self.discount * self.states[i].get_value())
qstate.set_qvalue(new_qvalue)
"""
Recalculates the value of all the q-states of the given state,
and updates the value of the state accordingly.
"""
def _v_update(self, state):
for qs in state.get_qstates():
self._q_update(qs)
state.update_value()
"""
Runs the value iteration algorithm on the model.
"""
def value_iteration(self, error=None):
if error is None:
error = self.update_error
repeat = True
while (repeat):
repeat = False
for s in self.states:
old_value = s.get_value()
self._v_update(s)
new_value = s.get_value()
if abs(old_value - new_value) > error:
repeat = True
"""
Runs prioritized sweeping starting from the given state.
"""
def prioritized_sweeping(self, initial_state=None, error=None, max_updates=None, debug=False):
if self.current_state is None and initial_state is None:
raise StateNotSetError()
if initial_state is None:
initial_state = self.current_state
if error is None:
error = self.update_error
if max_updates is None:
max_updates = self.max_updates
# transition probabilities have changed for the initial state
max_transitions = initial_state.get_max_transitions()
initial_s_num = initial_state.get_state_num()
for s_num, t in max_transitions.items():
self.reverse_transitions[s_num][initial_s_num] = t
s = initial_state
num_updates = 0
for i in range(max_updates):
num_updates += 1
# update the state value
old_value = s.get_value()
self._v_update(s)
new_value = s.get_value()
delta = abs(new_value - old_value)
# update the priorities of the predecessors
rev_transitions = self.reverse_transitions[s.get_state_num()]
for s_num, t in rev_transitions.items():
self.priorities[s_num] = max(t * delta, self.priorities[s_num])
# zero the updated state's priority
self.priorities[s.get_state_num()] = 0
if debug:
print("sweeping for %d, delta = %f" % (s.get_state_num(), delta))
print(self.reverse_transitions)
print(self.priorities)
# choose the next max priority state
# TODO with Priority Queue - but needs to support item removal
max_index = 0
max_priority = 0
for i in range(len(self.priorities)):
if self.priorities[i] > max_priority:
max_priority = self.priorities[i]
max_index = i
# stop if the priority gets below the supplied limit
if max_priority <= error:
if debug:
print("max_priority = %s, stopping" % max_priority)
break
s = self.states[max_index]
"""
Returns a list of the names of all the parameters in the states of the model
"""
def get_parameters(self):
return [name for name, values in self.index_params]
"""
Prints the states of the model.
If detailed is True it also prints the q-states
"""
def print_model(self, detailed=False):
for s in self.states:
if detailed:
s.print_detailed()
print("")
else:
print(s)
"""
Returns the percentage of actions that have never been taken
"""
def get_percent_not_taken(self):
total = 0
not_taken = 0
for s in self.states:
for qs in s.get_qstates():
total += 1
if qs.get_num_taken() == 0:
not_taken += 1
return not_taken / total
| 27.358639
| 102
| 0.585733
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.