max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
mtgreatest-py/mtgreatest/scrape/players.py | oelarnes/mtgreatest | 0 | 6620351 | <filename>mtgreatest-py/mtgreatest/scrape/players.py
import requests
import re
from bs4 import BeautifulSoup
from distance import levenshtein
from mtgreatest.rdb import Cursor, serialize
NUM_NORM_NAMES = 4
NORM_NAMES = ['norm_name_{}'.format(num) for num in range(NUM_NORM_NAMES)]
def fix_name_and_country(name, country):
if name is None:
return (name, country)
part = name.rpartition('[')
if len(part[0]):
return (part[0][:-1], part[1]+part[2])
else:
return (name, country)
def normalize_raw_name(raw_name):
raw_name = raw_name.upper()
sleep_in_patterns = ['ZVIP', 'ZZVIP', 'ZZZVIP', 'ZZ', 'ZZZ', 'ZZSIS', 'ZZFIX', 'ZZZ_', 'ZZZZZ', 'VIP', 'VIP_', 'AAVIP', 'AAA VIP -']
for pattern in sleep_in_patterns:
if raw_name.startswith(pattern) and not raw_name.startswith('VIPPERMAN'):
raw_name = raw_name.rpartition(pattern)[2]
elif raw_name.endswith(pattern):
raw_name = raw_name.partition(pattern)[0]
raw_name = raw_name.strip(' ()1234567890')
last_first = list(raw_name.partition(','))
last_first[0] = last_first[0].partition('[')[0].rstrip(' *').strip(' *')
last_first[2] = last_first[2].rpartition('SEE SK ')[2].strip(' *').rstrip(' *') #why?? what is this??
normalized_name = last_first[0]
if len(last_first[2]):
normalized_name += ', ' + last_first[2]
return normalized_name
def normalize_full_raw_name(full_raw_name):
return '/'.join([normalize_raw_name(name) for name in full_raw_name.split('/')])
def max_name_list(names1, names2):
ret_names = []
for name in names1:
if not any([name2.startswith(name) for name2 in names2]):
ret_names.append(name)
for name in names2:
if not any([name1.startswith(name) and len(name1)>len(name) for name1 in names1]):
ret_names.append(name)
return ret_names
def normalized_event_names(event_id):
cursor = Cursor()
num_rounds = cursor.execute("select max(round_num) from results_raw_table where event_id = '{}'".format(event_id))[0][0]
all_round_names = []
for round_num in range(num_rounds):
names = cursor.execute("select distinct p1_name_raw from results_raw_table where event_id = '{}' and round_num = {}".format(event_id, round_num))
names += cursor.execute("select distinct p2_name_raw from results_raw_table where event_id = '{}' and round_num = {}".format(event_id, round_num))
all_round_names.append(list(set([normalize_raw_name(item) for sublist in names for item in sublist if '* BYE *' not in item and 'Awarded Bye' not in item])))
cursor.close()
return reduce(max_name_list, all_round_names, [])
def populate_event_player_table(event_names, event_id):
cursor = Cursor()
cursor.execute("delete from event_player_table where event_id = {}".format(serialize(event_id)))
query = "select player_id, "
query += ', '.join(NORM_NAMES)
query += ' from player_table where '
or_ = False
for name in event_names:
if or_:
query += "or "
or_ = True
join_str = ' like {}'.format(serialize(name + '%'))
query += (join_str + ' or ').join(NORM_NAMES) + join_str
player_table_names = cursor.execute(query)
found_names = []
new_names = []
for name in event_names:
found = False
for idx, row in enumerate(player_table_names):
if name in row:
if found:
raise 'two matches found for name ' + name
found_names.append({'player_id':row[0], 'normalized_name':name, 'event_id':event_id})
found = True
if not found:
new_names.append(name)
player_id = cursor.execute("select max(player_id) from player_table")[0][0] or 1
new_players = []
for name in new_names:
player_id += 1
new_players.append({'player_id':player_id, 'norm_name_1':name, 'event_added':event_id, 'last_name':name.partition(',')[0],
'first_name':name.partition(', ')[2]})
found_names.append({'player_id':player_id, 'normalized_name':name, 'event_id':event_id})
cursor.insert('event_player_table', found_names)
cursor.insert('player_table', new_players)
cursor.close()
def remove_header_row():
query = "delete from results_raw_table where table_id like '%table%'"
cursor = Cursor()
cursor.execute(query);
cursor.close();
def combine_players(norm_name_1, norm_name_2):
query_template = "select * from player_table where "
query_template += ' or '.join([name + ' like {0}' for name in NORM_NAMES])
cursor = Cursor()
player_infos = [cursor.execute(query_template.format(serialize(name))) for name in (norm_name_1, norm_name_2)]
assert len(player_infos[0]) == 1 and len(player_infos[1]) == 1, "multiple or no matches found for a name"
| <filename>mtgreatest-py/mtgreatest/scrape/players.py
import requests
import re
from bs4 import BeautifulSoup
from distance import levenshtein
from mtgreatest.rdb import Cursor, serialize
NUM_NORM_NAMES = 4
NORM_NAMES = ['norm_name_{}'.format(num) for num in range(NUM_NORM_NAMES)]
def fix_name_and_country(name, country):
if name is None:
return (name, country)
part = name.rpartition('[')
if len(part[0]):
return (part[0][:-1], part[1]+part[2])
else:
return (name, country)
def normalize_raw_name(raw_name):
raw_name = raw_name.upper()
sleep_in_patterns = ['ZVIP', 'ZZVIP', 'ZZZVIP', 'ZZ', 'ZZZ', 'ZZSIS', 'ZZFIX', 'ZZZ_', 'ZZZZZ', 'VIP', 'VIP_', 'AAVIP', 'AAA VIP -']
for pattern in sleep_in_patterns:
if raw_name.startswith(pattern) and not raw_name.startswith('VIPPERMAN'):
raw_name = raw_name.rpartition(pattern)[2]
elif raw_name.endswith(pattern):
raw_name = raw_name.partition(pattern)[0]
raw_name = raw_name.strip(' ()1234567890')
last_first = list(raw_name.partition(','))
last_first[0] = last_first[0].partition('[')[0].rstrip(' *').strip(' *')
last_first[2] = last_first[2].rpartition('SEE SK ')[2].strip(' *').rstrip(' *') #why?? what is this??
normalized_name = last_first[0]
if len(last_first[2]):
normalized_name += ', ' + last_first[2]
return normalized_name
def normalize_full_raw_name(full_raw_name):
return '/'.join([normalize_raw_name(name) for name in full_raw_name.split('/')])
def max_name_list(names1, names2):
ret_names = []
for name in names1:
if not any([name2.startswith(name) for name2 in names2]):
ret_names.append(name)
for name in names2:
if not any([name1.startswith(name) and len(name1)>len(name) for name1 in names1]):
ret_names.append(name)
return ret_names
def normalized_event_names(event_id):
cursor = Cursor()
num_rounds = cursor.execute("select max(round_num) from results_raw_table where event_id = '{}'".format(event_id))[0][0]
all_round_names = []
for round_num in range(num_rounds):
names = cursor.execute("select distinct p1_name_raw from results_raw_table where event_id = '{}' and round_num = {}".format(event_id, round_num))
names += cursor.execute("select distinct p2_name_raw from results_raw_table where event_id = '{}' and round_num = {}".format(event_id, round_num))
all_round_names.append(list(set([normalize_raw_name(item) for sublist in names for item in sublist if '* BYE *' not in item and 'Awarded Bye' not in item])))
cursor.close()
return reduce(max_name_list, all_round_names, [])
def populate_event_player_table(event_names, event_id):
cursor = Cursor()
cursor.execute("delete from event_player_table where event_id = {}".format(serialize(event_id)))
query = "select player_id, "
query += ', '.join(NORM_NAMES)
query += ' from player_table where '
or_ = False
for name in event_names:
if or_:
query += "or "
or_ = True
join_str = ' like {}'.format(serialize(name + '%'))
query += (join_str + ' or ').join(NORM_NAMES) + join_str
player_table_names = cursor.execute(query)
found_names = []
new_names = []
for name in event_names:
found = False
for idx, row in enumerate(player_table_names):
if name in row:
if found:
raise 'two matches found for name ' + name
found_names.append({'player_id':row[0], 'normalized_name':name, 'event_id':event_id})
found = True
if not found:
new_names.append(name)
player_id = cursor.execute("select max(player_id) from player_table")[0][0] or 1
new_players = []
for name in new_names:
player_id += 1
new_players.append({'player_id':player_id, 'norm_name_1':name, 'event_added':event_id, 'last_name':name.partition(',')[0],
'first_name':name.partition(', ')[2]})
found_names.append({'player_id':player_id, 'normalized_name':name, 'event_id':event_id})
cursor.insert('event_player_table', found_names)
cursor.insert('player_table', new_players)
cursor.close()
def remove_header_row():
query = "delete from results_raw_table where table_id like '%table%'"
cursor = Cursor()
cursor.execute(query);
cursor.close();
def combine_players(norm_name_1, norm_name_2):
query_template = "select * from player_table where "
query_template += ' or '.join([name + ' like {0}' for name in NORM_NAMES])
cursor = Cursor()
player_infos = [cursor.execute(query_template.format(serialize(name))) for name in (norm_name_1, norm_name_2)]
assert len(player_infos[0]) == 1 and len(player_infos[1]) == 1, "multiple or no matches found for a name"
| en | 0.955255 | #why?? what is this?? | 2.721333 | 3 |
djangoExample/django/example/urls.py | jbinvnt/static-form-gen | 0 | 6620352 | <gh_stars>0
from django.conf.urls.static import static
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('cars', views.carEndpoint),
]
| from django.conf.urls.static import static
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('cars', views.carEndpoint),
] | none | 1 | 1.421502 | 1 | |
src/dataset.py | Bobholamovic/CNN-FRIQA | 12 | 6620353 | <filename>src/dataset.py
"""
Dataset and Transforms
"""
import torch.utils.data
import numpy as np
import random
import json
from skimage import io
from os.path import join, exists
from utils import limited_instances, SimpleProgressBar
class IQADataset(torch.utils.data.Dataset):
def __init__(self, data_dir, phase, n_ptchs=16, sample_once=False, subset='', list_dir=''):
super(IQADataset, self).__init__()
self.list_dir = data_dir if not list_dir else list_dir
self.data_dir = data_dir
self.phase = phase
self.subset = phase if not subset.strip() else subset
self.n_ptchs = n_ptchs
self.img_list = []
self.ref_list = []
self.score_list = []
self.sample_once = sample_once
self._from_pool = False
self._read_lists()
self._aug_lists()
self.tfs = Transforms()
if sample_once:
@limited_instances(self.__len__())
class IncrementCache:
def store(self, data):
self.data = data
self._pool = IncrementCache
self._to_pool()
self._from_pool = True
def __getitem__(self, index):
img = self._loader(self.img_list[index])
ref = self._loader(self.ref_list[index])
score = self.score_list[index]
if self._from_pool:
(img_ptchs, ref_ptchs) = self._pool(index).data
else:
if self.phase == 'train':
img, ref = self.tfs.horizontal_flip(img, ref)
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
elif self.phase == 'val':
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
elif self.phase == 'test':
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
else:
pass
return (img_ptchs, ref_ptchs), torch.tensor(score).float()
def __len__(self):
return len(self.img_list)
def _loader(self, name):
return io.imread(join(self.data_dir, name))
def _to_patch_tensors(self, img, ref):
img_ptchs, ref_ptchs = self.tfs.to_patches(img, ref, ptch_size=32, n_ptchs=self.n_ptchs)
img_ptchs, ref_ptchs = self.tfs.to_tensor(img_ptchs, ref_ptchs)
return img_ptchs, ref_ptchs
def _to_pool(self):
len_data = self.__len__()
pb = SimpleProgressBar(len_data)
print("\ninitializing data pool...")
for index in range(len_data):
self._pool(index).store(self.__getitem__(index)[0])
pb.show(index, "[{:d}]/[{:d}] ".format(index+1, len_data))
def _aug_lists(self):
if self.phase == 'test':
return
# Make samples from the reference images
# The number of the reference samples appears
# CRITICAL for the training effect!
len_aug = len(self.ref_list)//5 if self.phase == 'train' else 10
aug_list = self.ref_list*(len_aug//len(self.ref_list)+1)
random.shuffle(aug_list)
aug_list = aug_list[:len_aug]
self.img_list.extend(aug_list)
self.score_list += [0.0]*len_aug
self.ref_list.extend(aug_list)
if self.phase == 'train':
# More samples in one epoch
# This accelerates the training indeed as the cache
# of the file system could then be fully leveraged
# And also, augment the data in terms of number
mul_aug = 16
self.img_list *= mul_aug
self.ref_list *= mul_aug
self.score_list *= mul_aug
def _read_lists(self):
img_path = join(self.list_dir, self.subset + '_data.json')
assert exists(img_path)
with open(img_path, 'r') as fp:
data_dict = json.load(fp)
self.img_list = data_dict['img']
self.ref_list = data_dict.get('ref', self.img_list)
self.score_list = data_dict.get('score', [0.0]*len(self.img_list))
class TID2013Dataset(IQADataset):
def _read_lists(self):
super()._read_lists()
# For TID2013
self.score_list = [(9.0 - s) / 9.0 * 100.0 for s in self.score_list]
class WaterlooDataset(IQADataset):
def _read_lists(self):
super()._read_lists()
self.score_list = [(1.0 - s) * 100.0 for s in self.score_list]
class Transforms:
"""
Self-designed transformation class
------------------------------------
Several things to fix and improve:
1. Strong coupling with Dataset cuz transformation types can't
be simply assigned in training or testing code. (e.g. given
a list of transforms as parameters to construct Dataset Obj)
2. Might be unsafe in multi-thread cases
3. Too complex decorators, not pythonic
4. The number of params of the wrapper and the inner function should
be the same to avoid confusion
5. The use of params and isinstance() is not so elegant. For this,
consider to stipulate a fix number and type of returned values for
inner tf functions and do all the forwarding and passing work inside
the decorator. tf_func applies transformation, which is all it does.
6. Performance has not been optimized at all
7. Doc it
8. Supports only numpy arrays
"""
def __init__(self):
super(Transforms, self).__init__()
def _pair_deco(tf_func):
def transform(self, img, ref=None, *args, **kwargs):
""" image shape (w, h, c) """
if (ref is not None) and (not isinstance(ref, np.ndarray)):
args = (ref,)+args
ref = None
ret = tf_func(self, img, None, *args, **kwargs)
assert(len(ret) == 2)
if ref is None:
return ret[0]
else:
num_var = tf_func.__code__.co_argcount-3 # self, img, ref not counted
if (len(args)+len(kwargs)) == (num_var-1):
# The last parameter is special
# Resend it if necessary
var_name = tf_func.__code__.co_varnames[-1]
kwargs[var_name] = ret[1]
tf_ref, _ = tf_func(self, ref, None, *args, **kwargs)
return ret[0], tf_ref
return transform
def _horizontal_flip(self, img, flip):
if flip is None:
flip = (random.random() > 0.5)
return (img[...,::-1,:] if flip else img), flip
def _to_tensor(self, img):
return torch.from_numpy((img.astype(np.float32)/255).swapaxes(-3,-2).swapaxes(-3,-1)), ()
def _crop_square(self, img, crop_size, pos):
if pos is None:
h, w = img.shape[-3:-1]
assert(crop_size <= h and crop_size <= w)
ub = random.randint(0, h-crop_size)
lb = random.randint(0, w-crop_size)
pos = (ub, ub+crop_size, lb, lb+crop_size)
return img[...,pos[0]:pos[1],pos[-2]:pos[-1],:], pos
def _extract_patches(self, img, ptch_size):
# Crop non-overlapping patches as the stride equals patch size
h, w = img.shape[-3:-1]
nh, nw = h//ptch_size, w//ptch_size
assert(nh>0 and nw>0)
vptchs = np.stack(np.split(img[...,:nh*ptch_size,:,:], nh, axis=-3))
ptchs = np.concatenate(np.split(vptchs[...,:nw*ptch_size,:], nw, axis=-2))
return ptchs, nh*nw
def _to_patches(self, img, ptch_size, n_ptchs, idx):
ptchs, n = self._extract_patches(img, ptch_size)
if not n_ptchs:
n_ptchs = n
elif n_ptchs > n:
n_ptchs = n
if idx is None:
idx = list(range(n))
random.shuffle(idx)
idx = idx[:n_ptchs]
return ptchs[idx], idx
@_pair_deco
def horizontal_flip(self, img, ref=None, flip=None):
return self._horizontal_flip(img, flip=flip)
@_pair_deco
def to_tensor(self, img, ref=None):
return self._to_tensor(img)
@_pair_deco
def crop_square(self, img, ref=None, crop_size=64, pos=None):
return self._crop_square(img, crop_size=crop_size, pos=pos)
@_pair_deco
def to_patches(self, img, ref=None, ptch_size=32, n_ptchs=None, idx=None):
return self._to_patches(img, ptch_size=ptch_size, n_ptchs=n_ptchs, idx=idx)
| <filename>src/dataset.py
"""
Dataset and Transforms
"""
import torch.utils.data
import numpy as np
import random
import json
from skimage import io
from os.path import join, exists
from utils import limited_instances, SimpleProgressBar
class IQADataset(torch.utils.data.Dataset):
def __init__(self, data_dir, phase, n_ptchs=16, sample_once=False, subset='', list_dir=''):
super(IQADataset, self).__init__()
self.list_dir = data_dir if not list_dir else list_dir
self.data_dir = data_dir
self.phase = phase
self.subset = phase if not subset.strip() else subset
self.n_ptchs = n_ptchs
self.img_list = []
self.ref_list = []
self.score_list = []
self.sample_once = sample_once
self._from_pool = False
self._read_lists()
self._aug_lists()
self.tfs = Transforms()
if sample_once:
@limited_instances(self.__len__())
class IncrementCache:
def store(self, data):
self.data = data
self._pool = IncrementCache
self._to_pool()
self._from_pool = True
def __getitem__(self, index):
img = self._loader(self.img_list[index])
ref = self._loader(self.ref_list[index])
score = self.score_list[index]
if self._from_pool:
(img_ptchs, ref_ptchs) = self._pool(index).data
else:
if self.phase == 'train':
img, ref = self.tfs.horizontal_flip(img, ref)
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
elif self.phase == 'val':
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
elif self.phase == 'test':
img_ptchs, ref_ptchs = self._to_patch_tensors(img, ref)
else:
pass
return (img_ptchs, ref_ptchs), torch.tensor(score).float()
def __len__(self):
return len(self.img_list)
def _loader(self, name):
return io.imread(join(self.data_dir, name))
def _to_patch_tensors(self, img, ref):
img_ptchs, ref_ptchs = self.tfs.to_patches(img, ref, ptch_size=32, n_ptchs=self.n_ptchs)
img_ptchs, ref_ptchs = self.tfs.to_tensor(img_ptchs, ref_ptchs)
return img_ptchs, ref_ptchs
def _to_pool(self):
len_data = self.__len__()
pb = SimpleProgressBar(len_data)
print("\ninitializing data pool...")
for index in range(len_data):
self._pool(index).store(self.__getitem__(index)[0])
pb.show(index, "[{:d}]/[{:d}] ".format(index+1, len_data))
def _aug_lists(self):
if self.phase == 'test':
return
# Make samples from the reference images
# The number of the reference samples appears
# CRITICAL for the training effect!
len_aug = len(self.ref_list)//5 if self.phase == 'train' else 10
aug_list = self.ref_list*(len_aug//len(self.ref_list)+1)
random.shuffle(aug_list)
aug_list = aug_list[:len_aug]
self.img_list.extend(aug_list)
self.score_list += [0.0]*len_aug
self.ref_list.extend(aug_list)
if self.phase == 'train':
# More samples in one epoch
# This accelerates the training indeed as the cache
# of the file system could then be fully leveraged
# And also, augment the data in terms of number
mul_aug = 16
self.img_list *= mul_aug
self.ref_list *= mul_aug
self.score_list *= mul_aug
def _read_lists(self):
img_path = join(self.list_dir, self.subset + '_data.json')
assert exists(img_path)
with open(img_path, 'r') as fp:
data_dict = json.load(fp)
self.img_list = data_dict['img']
self.ref_list = data_dict.get('ref', self.img_list)
self.score_list = data_dict.get('score', [0.0]*len(self.img_list))
class TID2013Dataset(IQADataset):
def _read_lists(self):
super()._read_lists()
# For TID2013
self.score_list = [(9.0 - s) / 9.0 * 100.0 for s in self.score_list]
class WaterlooDataset(IQADataset):
def _read_lists(self):
super()._read_lists()
self.score_list = [(1.0 - s) * 100.0 for s in self.score_list]
class Transforms:
"""
Self-designed transformation class
------------------------------------
Several things to fix and improve:
1. Strong coupling with Dataset cuz transformation types can't
be simply assigned in training or testing code. (e.g. given
a list of transforms as parameters to construct Dataset Obj)
2. Might be unsafe in multi-thread cases
3. Too complex decorators, not pythonic
4. The number of params of the wrapper and the inner function should
be the same to avoid confusion
5. The use of params and isinstance() is not so elegant. For this,
consider to stipulate a fix number and type of returned values for
inner tf functions and do all the forwarding and passing work inside
the decorator. tf_func applies transformation, which is all it does.
6. Performance has not been optimized at all
7. Doc it
8. Supports only numpy arrays
"""
def __init__(self):
super(Transforms, self).__init__()
def _pair_deco(tf_func):
def transform(self, img, ref=None, *args, **kwargs):
""" image shape (w, h, c) """
if (ref is not None) and (not isinstance(ref, np.ndarray)):
args = (ref,)+args
ref = None
ret = tf_func(self, img, None, *args, **kwargs)
assert(len(ret) == 2)
if ref is None:
return ret[0]
else:
num_var = tf_func.__code__.co_argcount-3 # self, img, ref not counted
if (len(args)+len(kwargs)) == (num_var-1):
# The last parameter is special
# Resend it if necessary
var_name = tf_func.__code__.co_varnames[-1]
kwargs[var_name] = ret[1]
tf_ref, _ = tf_func(self, ref, None, *args, **kwargs)
return ret[0], tf_ref
return transform
def _horizontal_flip(self, img, flip):
if flip is None:
flip = (random.random() > 0.5)
return (img[...,::-1,:] if flip else img), flip
def _to_tensor(self, img):
return torch.from_numpy((img.astype(np.float32)/255).swapaxes(-3,-2).swapaxes(-3,-1)), ()
def _crop_square(self, img, crop_size, pos):
if pos is None:
h, w = img.shape[-3:-1]
assert(crop_size <= h and crop_size <= w)
ub = random.randint(0, h-crop_size)
lb = random.randint(0, w-crop_size)
pos = (ub, ub+crop_size, lb, lb+crop_size)
return img[...,pos[0]:pos[1],pos[-2]:pos[-1],:], pos
def _extract_patches(self, img, ptch_size):
# Crop non-overlapping patches as the stride equals patch size
h, w = img.shape[-3:-1]
nh, nw = h//ptch_size, w//ptch_size
assert(nh>0 and nw>0)
vptchs = np.stack(np.split(img[...,:nh*ptch_size,:,:], nh, axis=-3))
ptchs = np.concatenate(np.split(vptchs[...,:nw*ptch_size,:], nw, axis=-2))
return ptchs, nh*nw
def _to_patches(self, img, ptch_size, n_ptchs, idx):
ptchs, n = self._extract_patches(img, ptch_size)
if not n_ptchs:
n_ptchs = n
elif n_ptchs > n:
n_ptchs = n
if idx is None:
idx = list(range(n))
random.shuffle(idx)
idx = idx[:n_ptchs]
return ptchs[idx], idx
@_pair_deco
def horizontal_flip(self, img, ref=None, flip=None):
return self._horizontal_flip(img, flip=flip)
@_pair_deco
def to_tensor(self, img, ref=None):
return self._to_tensor(img)
@_pair_deco
def crop_square(self, img, ref=None, crop_size=64, pos=None):
return self._crop_square(img, crop_size=crop_size, pos=pos)
@_pair_deco
def to_patches(self, img, ref=None, ptch_size=32, n_ptchs=None, idx=None):
return self._to_patches(img, ptch_size=ptch_size, n_ptchs=n_ptchs, idx=idx)
| en | 0.83317 | Dataset and Transforms # Make samples from the reference images # The number of the reference samples appears # CRITICAL for the training effect! # More samples in one epoch # This accelerates the training indeed as the cache # of the file system could then be fully leveraged # And also, augment the data in terms of number # For TID2013 Self-designed transformation class ------------------------------------ Several things to fix and improve: 1. Strong coupling with Dataset cuz transformation types can't be simply assigned in training or testing code. (e.g. given a list of transforms as parameters to construct Dataset Obj) 2. Might be unsafe in multi-thread cases 3. Too complex decorators, not pythonic 4. The number of params of the wrapper and the inner function should be the same to avoid confusion 5. The use of params and isinstance() is not so elegant. For this, consider to stipulate a fix number and type of returned values for inner tf functions and do all the forwarding and passing work inside the decorator. tf_func applies transformation, which is all it does. 6. Performance has not been optimized at all 7. Doc it 8. Supports only numpy arrays image shape (w, h, c) # self, img, ref not counted # The last parameter is special # Resend it if necessary # Crop non-overlapping patches as the stride equals patch size | 2.252067 | 2 |
SimilarWords.py | SahanaMohandoss/WebTechVocabQuiz | 0 | 6620354 | from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
from nltk.stem.wordnet import WordNetLemmatizer
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None
def tagged_to_synset(word, tag):
wn_tag = penn_to_wn(tag)
if wn_tag is None:
return None
try:
return wn.synsets(word, wn_tag)[0]
except:
return None
def check_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
# Tokenize and tag
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
# Get the synsets for the tagged words
synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]
synsets2 = [tagged_to_synset(*tagged_word) for tagged_word in sentence2]
# Filter out the Nones
synsets1 = [ss for ss in synsets1 if ss]
synsets2 = [ss for ss in synsets2 if ss]
score, count = 0.0, 0
#print(synsets1)
#print(synsets2)
# For each word in the first sentence
for synset in synsets1:
# Get the similarity value of the most similar word in the other sentence
best_score = list([synset.path_similarity(ss) for ss in synsets2])
best_score= list(filter(lambda a: a != None, best_score))
if(best_score==[]):
best_score =0
else:
best_score = max(best_score)
# Check that the similarity could have been computed
if best_score is not None:
score += best_score
count += 1
# Average the values
if (count!= 0):
score /= count
return score
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
def cosine_sim(text1, text2):
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vectorizer.fit_transform([text1, text2])
return ((tfidf * tfidf.T).A)[0,1]
def preprocess(text):
word_tokens = word_tokenize(text)
filtered_sentence = " ".join([w for w in word_tokens if not w in stop_words])
wnl = WordNetLemmatizer()
Lemmatized = " ".join([wnl.lemmatize(i) for i in filtered_sentence.split()])
return Lemmatized
def returnSimilarity(s1 , s2):
sim1 = check_similarity(query,ques+" ".join(qa[ques]))
sim2 = check_similarity(ques+" ".join(qa[ques]), query)
sim = (sim1 + sim2)/2
tfidf_cosine = cosine_sim(ques+" ".join(qa[ques]) , query)
if(sim>0.7):
print(ques+" ".join(qa[ques]) , "Similarity: ", sim)
similar_questions[ques+" ".join(qa[ques])] = sim
print("Common words" ,common_words)
print("Tfidf cosine" , tfidf_cosine)ss
| from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
from nltk.stem.wordnet import WordNetLemmatizer
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None
def tagged_to_synset(word, tag):
wn_tag = penn_to_wn(tag)
if wn_tag is None:
return None
try:
return wn.synsets(word, wn_tag)[0]
except:
return None
def check_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
# Tokenize and tag
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
# Get the synsets for the tagged words
synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]
synsets2 = [tagged_to_synset(*tagged_word) for tagged_word in sentence2]
# Filter out the Nones
synsets1 = [ss for ss in synsets1 if ss]
synsets2 = [ss for ss in synsets2 if ss]
score, count = 0.0, 0
#print(synsets1)
#print(synsets2)
# For each word in the first sentence
for synset in synsets1:
# Get the similarity value of the most similar word in the other sentence
best_score = list([synset.path_similarity(ss) for ss in synsets2])
best_score= list(filter(lambda a: a != None, best_score))
if(best_score==[]):
best_score =0
else:
best_score = max(best_score)
# Check that the similarity could have been computed
if best_score is not None:
score += best_score
count += 1
# Average the values
if (count!= 0):
score /= count
return score
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
'''remove punctuation, lowercase, stem'''
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
def cosine_sim(text1, text2):
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vectorizer.fit_transform([text1, text2])
return ((tfidf * tfidf.T).A)[0,1]
def preprocess(text):
word_tokens = word_tokenize(text)
filtered_sentence = " ".join([w for w in word_tokens if not w in stop_words])
wnl = WordNetLemmatizer()
Lemmatized = " ".join([wnl.lemmatize(i) for i in filtered_sentence.split()])
return Lemmatized
def returnSimilarity(s1 , s2):
sim1 = check_similarity(query,ques+" ".join(qa[ques]))
sim2 = check_similarity(ques+" ".join(qa[ques]), query)
sim = (sim1 + sim2)/2
tfidf_cosine = cosine_sim(ques+" ".join(qa[ques]) , query)
if(sim>0.7):
print(ques+" ".join(qa[ques]) , "Similarity: ", sim)
similar_questions[ques+" ".join(qa[ques])] = sim
print("Common words" ,common_words)
print("Tfidf cosine" , tfidf_cosine)ss
| en | 0.744972 | Convert between a Penn Treebank tag to a simplified Wordnet tag compute the sentence similarity using Wordnet # Tokenize and tag # Get the synsets for the tagged words # Filter out the Nones #print(synsets1) #print(synsets2) # For each word in the first sentence # Get the similarity value of the most similar word in the other sentence # Check that the similarity could have been computed # Average the values remove punctuation, lowercase, stem | 3.335787 | 3 |
Mathematics/Algebra/wet-shark-and-42.py | ekant1999/HackerRank | 9 | 6620355 | <filename>Mathematics/Algebra/wet-shark-and-42.py
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for i in range(t):
MOD = 10**9 + 7
s = int(input())
k = s/20
rem = s%20
if rem == 0:
print (42*k - 2)%MOD
else:
print (42*k + 2*rem)%MOD
# The following code times out on the tests
# but I think it works
#
# s = int(raw_input())%(10**9 + 7)
# # k = s/20
# # square = 2*s + k
# square = 0
# while s != 0:
# square += 1
# if square%2 == 0 and square%42 != 0:
# s -= 1
# print "square = " + str(square) + " s = " + str(s)
# print square
| <filename>Mathematics/Algebra/wet-shark-and-42.py
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for i in range(t):
MOD = 10**9 + 7
s = int(input())
k = s/20
rem = s%20
if rem == 0:
print (42*k - 2)%MOD
else:
print (42*k + 2*rem)%MOD
# The following code times out on the tests
# but I think it works
#
# s = int(raw_input())%(10**9 + 7)
# # k = s/20
# # square = 2*s + k
# square = 0
# while s != 0:
# square += 1
# if square%2 == 0 and square%42 != 0:
# s -= 1
# print "square = " + str(square) + " s = " + str(s)
# print square
| en | 0.867175 | # Enter your code here. Read input from STDIN. Print output to STDOUT # The following code times out on the tests # but I think it works # # s = int(raw_input())%(10**9 + 7) # # k = s/20 # # square = 2*s + k # square = 0 # while s != 0: # square += 1 # if square%2 == 0 and square%42 != 0: # s -= 1 # print "square = " + str(square) + " s = " + str(s) # print square | 3.697428 | 4 |
tests/ut/explainer/manager/test_explain_manager.py | fapbatista/mindinsight | 216 | 6620356 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""UT for explainer.manager.explain_loader."""
import os
import threading
import time
from unittest.mock import patch
from mindinsight.explainer.manager.explain_loader import ExplainLoader
from mindinsight.explainer.manager.explain_loader import _LoaderStatus
from mindinsight.explainer.manager.explain_manager import ExplainManager
from mindinsight.explainer.manager.explain_manager import _ExplainManagerStatus
class TestExplainManager:
"""Test explain manager class."""
def test_stop_load_data_not_loading_status(self):
"""Test stop load data when the status is not loading."""
manager = ExplainManager('./summary_dir')
assert manager.status == _ExplainManagerStatus.INIT.value
manager.status = _ExplainManagerStatus.DONE.value
manager._stop_load_data()
assert manager.status == _ExplainManagerStatus.DONE.value
@patch.object(os, 'stat')
def test_stop_load_data_with_loading_status(self, mock_stat):
"""Test stop load data with status is loading."""
class _MockStat:
def __init__(self, _):
self.st_ctime = 1
self.st_mtime = 1
self.st_size = 1
mock_stat.side_effect = _MockStat
manager = ExplainManager('./summary_dir')
manager.status = _ExplainManagerStatus.LOADING.value
loader_count = 3
for i in range(loader_count):
loader = ExplainLoader(f'./summary_dir{i}', f'./summary_dir{i}')
loader.status = _LoaderStatus.LOADING.value
manager._loader_pool[i] = loader
def _wrapper(loader_manager):
assert loader_manager.status == _ExplainManagerStatus.LOADING.value
time.sleep(0.01)
loader_manager.status = _ExplainManagerStatus.DONE.value
thread = threading.Thread(target=_wrapper, args=(manager,), daemon=True)
thread.start()
manager._stop_load_data()
for loader in manager._loader_pool.values():
assert loader.status == _LoaderStatus.STOP.value
assert manager.status == _ExplainManagerStatus.DONE.value
def test_stop_load_data_with_after_cache_loaders(self):
"""
Test stop load data that is triggered by get a not in loader pool job.
In this case, we will mock the cache_loader function, and set status to STOP by other thread.
"""
manager = ExplainManager('./summary_dir')
def _mock_cache_loaders():
for _ in range(3):
time.sleep(0.1)
manager._cache_loaders = _mock_cache_loaders
load_data_thread = threading.Thread(target=manager._load_data, name='manager_load_data', daemon=True)
stop_thread = threading.Thread(target=manager._stop_load_data, name='stop_load_data', daemon=True)
load_data_thread.start()
while manager.status != _ExplainManagerStatus.LOADING.value:
continue
stop_thread.start()
stop_thread.join()
assert manager.status == _ExplainManagerStatus.DONE.value
| # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""UT for explainer.manager.explain_loader."""
import os
import threading
import time
from unittest.mock import patch
from mindinsight.explainer.manager.explain_loader import ExplainLoader
from mindinsight.explainer.manager.explain_loader import _LoaderStatus
from mindinsight.explainer.manager.explain_manager import ExplainManager
from mindinsight.explainer.manager.explain_manager import _ExplainManagerStatus
class TestExplainManager:
"""Test explain manager class."""
def test_stop_load_data_not_loading_status(self):
"""Test stop load data when the status is not loading."""
manager = ExplainManager('./summary_dir')
assert manager.status == _ExplainManagerStatus.INIT.value
manager.status = _ExplainManagerStatus.DONE.value
manager._stop_load_data()
assert manager.status == _ExplainManagerStatus.DONE.value
@patch.object(os, 'stat')
def test_stop_load_data_with_loading_status(self, mock_stat):
"""Test stop load data with status is loading."""
class _MockStat:
def __init__(self, _):
self.st_ctime = 1
self.st_mtime = 1
self.st_size = 1
mock_stat.side_effect = _MockStat
manager = ExplainManager('./summary_dir')
manager.status = _ExplainManagerStatus.LOADING.value
loader_count = 3
for i in range(loader_count):
loader = ExplainLoader(f'./summary_dir{i}', f'./summary_dir{i}')
loader.status = _LoaderStatus.LOADING.value
manager._loader_pool[i] = loader
def _wrapper(loader_manager):
assert loader_manager.status == _ExplainManagerStatus.LOADING.value
time.sleep(0.01)
loader_manager.status = _ExplainManagerStatus.DONE.value
thread = threading.Thread(target=_wrapper, args=(manager,), daemon=True)
thread.start()
manager._stop_load_data()
for loader in manager._loader_pool.values():
assert loader.status == _LoaderStatus.STOP.value
assert manager.status == _ExplainManagerStatus.DONE.value
def test_stop_load_data_with_after_cache_loaders(self):
"""
Test stop load data that is triggered by get a not in loader pool job.
In this case, we will mock the cache_loader function, and set status to STOP by other thread.
"""
manager = ExplainManager('./summary_dir')
def _mock_cache_loaders():
for _ in range(3):
time.sleep(0.1)
manager._cache_loaders = _mock_cache_loaders
load_data_thread = threading.Thread(target=manager._load_data, name='manager_load_data', daemon=True)
stop_thread = threading.Thread(target=manager._stop_load_data, name='stop_load_data', daemon=True)
load_data_thread.start()
while manager.status != _ExplainManagerStatus.LOADING.value:
continue
stop_thread.start()
stop_thread.join()
assert manager.status == _ExplainManagerStatus.DONE.value
| en | 0.842324 | # Copyright 2020 Huawei Technologies Co., Ltd # # 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. # ============================================================================ UT for explainer.manager.explain_loader. Test explain manager class. Test stop load data when the status is not loading. Test stop load data with status is loading. Test stop load data that is triggered by get a not in loader pool job. In this case, we will mock the cache_loader function, and set status to STOP by other thread. | 2.138579 | 2 |
src/evaluateWindow.py | deveshshakya/FantasyCricketGame | 0 | 6620357 | import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EvaluateWindow(object):
def setupUi(self, EvaluateWindow):
EvaluateWindow.setObjectName("EvaluateWindow")
EvaluateWindow.resize(750, 574)
self.centralwidget = QtWidgets.QWidget(EvaluateWindow)
self.centralwidget.setObjectName("centralwidget")
self.Evaluate_heading = QtWidgets.QLabel(self.centralwidget)
self.Evaluate_heading.setGeometry(QtCore.QRect(200, 30, 340, 20))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(11)
self.Evaluate_heading.setFont(font)
self.Evaluate_heading.setObjectName("Evaluate_heading")
self.TeamName_dropdown = QtWidgets.QComboBox(self.centralwidget)
self.TeamName_dropdown.setGeometry(QtCore.QRect(70, 80, 171, 22))
self.TeamName_dropdown.setObjectName("TeamName_dropdown")
# TeamNames
Teams = sqlite3.connect("../db/TEAM.db")
cursor = Teams.cursor()
cursor.execute("SELECT DISTINCT team_name FROM teams")
teamNames = cursor.fetchall()
Teams.close()
# Adding names in TeamName_dropdown
self.TeamName_dropdown.clear()
teamNames = [a[0] for a in teamNames]
teamNames.insert(0, 'Select Team')
self.TeamName_dropdown.addItems(teamNames)
self.MatchName_dropdown = QtWidgets.QComboBox(self.centralwidget)
self.MatchName_dropdown.setGeometry(QtCore.QRect(508, 80, 171, 22))
self.MatchName_dropdown.setObjectName("MatchName_dropdown")
# Default Match Added
self.MatchName_dropdown.addItem('Select Match')
self.MatchName_dropdown.addItem('Match 1')
self.Seprator = QtWidgets.QFrame(self.centralwidget)
self.Seprator.setGeometry(QtCore.QRect(37, 120, 671, 20))
self.Seprator.setFrameShape(QtWidgets.QFrame.HLine)
self.Seprator.setFrameShadow(QtWidgets.QFrame.Sunken)
self.Seprator.setObjectName("Seprator")
self.Players_list = QtWidgets.QListWidget(self.centralwidget)
self.Players_list.setGeometry(QtCore.QRect(60, 180, 256, 301))
self.Players_list.setObjectName("Players_list")
self.Points_list = QtWidgets.QListWidget(self.centralwidget)
self.Points_list.setGeometry(QtCore.QRect(440, 180, 256, 301))
self.Points_list.setObjectName("Points_list")
self.Players_head = QtWidgets.QLabel(self.centralwidget)
self.Players_head.setGeometry(QtCore.QRect(70, 150, 51, 16))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Players_head.setFont(font)
self.Players_head.setObjectName("Players_head")
self.Points_head = QtWidgets.QLabel(self.centralwidget)
self.Points_head.setGeometry(QtCore.QRect(450, 150, 36, 18))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Points_head.setFont(font)
self.Points_head.setObjectName("Points_head")
self.Points = QtWidgets.QLabel(self.centralwidget)
self.Points.setGeometry(QtCore.QRect(510, 150, 41, 18))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Points.setFont(font)
self.Points.setObjectName("Points")
self.Calculate_button = QtWidgets.QPushButton(self.centralwidget)
self.Calculate_button.setGeometry(QtCore.QRect(320, 510, 111, 26))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Calculate_button.setFont(font)
self.Calculate_button.setObjectName("Calculate_button")
EvaluateWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(EvaluateWindow)
QtCore.QMetaObject.connectSlotsByName(EvaluateWindow)
def retranslateUi(self, EvaluateWindow):
_translate = QtCore.QCoreApplication.translate
EvaluateWindow.setWindowTitle(_translate("EvaluateWindow", "Evaluate"))
self.Evaluate_heading.setText(_translate("EvaluateWindow", "Evaluate the Performance Of Your Fantasy Team"))
self.Players_head.setText(_translate("EvaluateWindow", "Players"))
self.Points_head.setText(_translate("EvaluateWindow", "Points"))
self.Points.setText(_translate("EvaluateWindow", "00"))
self.Calculate_button.setText(_translate("EvaluateWindow", "Calculate Score"))
| import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EvaluateWindow(object):
def setupUi(self, EvaluateWindow):
EvaluateWindow.setObjectName("EvaluateWindow")
EvaluateWindow.resize(750, 574)
self.centralwidget = QtWidgets.QWidget(EvaluateWindow)
self.centralwidget.setObjectName("centralwidget")
self.Evaluate_heading = QtWidgets.QLabel(self.centralwidget)
self.Evaluate_heading.setGeometry(QtCore.QRect(200, 30, 340, 20))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(11)
self.Evaluate_heading.setFont(font)
self.Evaluate_heading.setObjectName("Evaluate_heading")
self.TeamName_dropdown = QtWidgets.QComboBox(self.centralwidget)
self.TeamName_dropdown.setGeometry(QtCore.QRect(70, 80, 171, 22))
self.TeamName_dropdown.setObjectName("TeamName_dropdown")
# TeamNames
Teams = sqlite3.connect("../db/TEAM.db")
cursor = Teams.cursor()
cursor.execute("SELECT DISTINCT team_name FROM teams")
teamNames = cursor.fetchall()
Teams.close()
# Adding names in TeamName_dropdown
self.TeamName_dropdown.clear()
teamNames = [a[0] for a in teamNames]
teamNames.insert(0, 'Select Team')
self.TeamName_dropdown.addItems(teamNames)
self.MatchName_dropdown = QtWidgets.QComboBox(self.centralwidget)
self.MatchName_dropdown.setGeometry(QtCore.QRect(508, 80, 171, 22))
self.MatchName_dropdown.setObjectName("MatchName_dropdown")
# Default Match Added
self.MatchName_dropdown.addItem('Select Match')
self.MatchName_dropdown.addItem('Match 1')
self.Seprator = QtWidgets.QFrame(self.centralwidget)
self.Seprator.setGeometry(QtCore.QRect(37, 120, 671, 20))
self.Seprator.setFrameShape(QtWidgets.QFrame.HLine)
self.Seprator.setFrameShadow(QtWidgets.QFrame.Sunken)
self.Seprator.setObjectName("Seprator")
self.Players_list = QtWidgets.QListWidget(self.centralwidget)
self.Players_list.setGeometry(QtCore.QRect(60, 180, 256, 301))
self.Players_list.setObjectName("Players_list")
self.Points_list = QtWidgets.QListWidget(self.centralwidget)
self.Points_list.setGeometry(QtCore.QRect(440, 180, 256, 301))
self.Points_list.setObjectName("Points_list")
self.Players_head = QtWidgets.QLabel(self.centralwidget)
self.Players_head.setGeometry(QtCore.QRect(70, 150, 51, 16))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Players_head.setFont(font)
self.Players_head.setObjectName("Players_head")
self.Points_head = QtWidgets.QLabel(self.centralwidget)
self.Points_head.setGeometry(QtCore.QRect(450, 150, 36, 18))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Points_head.setFont(font)
self.Points_head.setObjectName("Points_head")
self.Points = QtWidgets.QLabel(self.centralwidget)
self.Points.setGeometry(QtCore.QRect(510, 150, 41, 18))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Points.setFont(font)
self.Points.setObjectName("Points")
self.Calculate_button = QtWidgets.QPushButton(self.centralwidget)
self.Calculate_button.setGeometry(QtCore.QRect(320, 510, 111, 26))
font = QtGui.QFont()
font.setFamily("Comic Sans MS")
font.setPointSize(10)
self.Calculate_button.setFont(font)
self.Calculate_button.setObjectName("Calculate_button")
EvaluateWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(EvaluateWindow)
QtCore.QMetaObject.connectSlotsByName(EvaluateWindow)
def retranslateUi(self, EvaluateWindow):
_translate = QtCore.QCoreApplication.translate
EvaluateWindow.setWindowTitle(_translate("EvaluateWindow", "Evaluate"))
self.Evaluate_heading.setText(_translate("EvaluateWindow", "Evaluate the Performance Of Your Fantasy Team"))
self.Players_head.setText(_translate("EvaluateWindow", "Players"))
self.Points_head.setText(_translate("EvaluateWindow", "Points"))
self.Points.setText(_translate("EvaluateWindow", "00"))
self.Calculate_button.setText(_translate("EvaluateWindow", "Calculate Score"))
| en | 0.630179 | # TeamNames # Adding names in TeamName_dropdown # Default Match Added | 2.758136 | 3 |
documented/commands/spiderdocs.py | nanvel/scrapy-spiderdocs | 1 | 6620358 | from __future__ import print_function
import re
from scrapy.commands import ScrapyCommand
from scrapy.exceptions import UsageError
__all__ = ('Command',)
INDENT_RE = re.compile('^(\s+)')
def get_line_indent(line):
matches = INDENT_RE.match(line)
return matches and len(matches.groups()[0]) or 0
class SpiderDocsSection(object):
_name = None
_lines = []
def __init__(self, name, processor=None):
self._name = name
self._processor = processor
self._lines = []
def append(self, line):
self._lines.append(line)
def _default_processor(self, name, content):
return "### {name}\n\n{content}".format(
name=name,
content=content
)
def to_md(self):
content = '\n'.join(self._lines).strip()
return (self._processor or self._default_processor)(name=self._name, content=content)
class Command(ScrapyCommand):
requires_project = True
default_settings = {
# {<module>: <destination>}
'SPIDERDOCS_LOCATIONS': {},
# {<section_name>: <function(name, content) -> str>}
'SPIDERDOCS_SECTION_PROCESSORS': {},
'LOG_ENABLED': False
}
SECTION_PREFIX = ';'
SECTION_END = 'end'
_locations = {}
def short_desc(self):
return "Generate spiders documentation md file for specified module."
def add_options(self, parser):
parser.usage = "usage: scrapy spiderdocs [<module.name>] [-o <filename.md>]"
ScrapyCommand.add_options(self, parser)
parser.add_option("-o", "--output", dest="output_filename", metavar="FILE", help="Output file name.")
def process_options(self, args, opts):
ScrapyCommand.process_options(self, args, opts)
if args:
self._locations[args[0]] = opts.output_filename
else:
locations = self.settings.get('SPIDERDOCS_LOCATIONS', None)
if locations:
self._locations = locations
else:
raise UsageError("Module name is required.", print_help=False)
def run(self, args, opts):
section_processors = self.settings.get('SPIDERDOCS_SECTION_PROCESSORS') or {}
for module, location in self._locations.items():
output = ["# {module_name} spiders".format(module_name=module)]
spiders_count_total = 0
spiders_count_documented = 0
for spider_name in sorted(self.crawler_process.spider_loader.list()):
spider = self.crawler_process.spider_loader.load(spider_name)
spiders_count_total += 1
if not spider.__module__.startswith(module):
continue
if not spider.__doc__:
continue
sections = []
doc_lines = spider.__doc__.split('\n')
# calculate base text indent
indent = None
for line in doc_lines:
line_indent = get_line_indent(line)
if line_indent > 0 and (indent is None or line_indent < indent):
indent = line_indent
indent = indent or 0
current_section = None
for line in doc_lines:
line_indent = get_line_indent(line)
if line_indent > 0:
line = line[indent:]
if line.startswith(self.SECTION_PREFIX):
if current_section:
sections.append(current_section.to_md())
section_name = line[len(self.SECTION_PREFIX):].strip()
if section_name.lower().strip() == self.SECTION_END:
current_section = None
else:
current_section = SpiderDocsSection(
section_name,
processor=section_processors.get(section_name.lower())
)
continue
if current_section:
current_section.append(line)
if current_section:
sections.append(current_section.to_md())
if sections:
output.append(
"## {spider_name} ({class_name})".format(
spider_name=spider.name,
class_name=spider.__name__
)
)
output.extend(sections)
spiders_count_documented += 1
output = '\n\n'.join(output)
if location:
with open(location, 'w') as f:
f.write(output)
print(
"{module} -> {location} ({documented}/{total} spiders)".format(
module=module,
location=location,
total=spiders_count_total,
documented=spiders_count_documented
)
)
else:
print(output)
| from __future__ import print_function
import re
from scrapy.commands import ScrapyCommand
from scrapy.exceptions import UsageError
__all__ = ('Command',)
INDENT_RE = re.compile('^(\s+)')
def get_line_indent(line):
matches = INDENT_RE.match(line)
return matches and len(matches.groups()[0]) or 0
class SpiderDocsSection(object):
_name = None
_lines = []
def __init__(self, name, processor=None):
self._name = name
self._processor = processor
self._lines = []
def append(self, line):
self._lines.append(line)
def _default_processor(self, name, content):
return "### {name}\n\n{content}".format(
name=name,
content=content
)
def to_md(self):
content = '\n'.join(self._lines).strip()
return (self._processor or self._default_processor)(name=self._name, content=content)
class Command(ScrapyCommand):
requires_project = True
default_settings = {
# {<module>: <destination>}
'SPIDERDOCS_LOCATIONS': {},
# {<section_name>: <function(name, content) -> str>}
'SPIDERDOCS_SECTION_PROCESSORS': {},
'LOG_ENABLED': False
}
SECTION_PREFIX = ';'
SECTION_END = 'end'
_locations = {}
def short_desc(self):
return "Generate spiders documentation md file for specified module."
def add_options(self, parser):
parser.usage = "usage: scrapy spiderdocs [<module.name>] [-o <filename.md>]"
ScrapyCommand.add_options(self, parser)
parser.add_option("-o", "--output", dest="output_filename", metavar="FILE", help="Output file name.")
def process_options(self, args, opts):
ScrapyCommand.process_options(self, args, opts)
if args:
self._locations[args[0]] = opts.output_filename
else:
locations = self.settings.get('SPIDERDOCS_LOCATIONS', None)
if locations:
self._locations = locations
else:
raise UsageError("Module name is required.", print_help=False)
def run(self, args, opts):
section_processors = self.settings.get('SPIDERDOCS_SECTION_PROCESSORS') or {}
for module, location in self._locations.items():
output = ["# {module_name} spiders".format(module_name=module)]
spiders_count_total = 0
spiders_count_documented = 0
for spider_name in sorted(self.crawler_process.spider_loader.list()):
spider = self.crawler_process.spider_loader.load(spider_name)
spiders_count_total += 1
if not spider.__module__.startswith(module):
continue
if not spider.__doc__:
continue
sections = []
doc_lines = spider.__doc__.split('\n')
# calculate base text indent
indent = None
for line in doc_lines:
line_indent = get_line_indent(line)
if line_indent > 0 and (indent is None or line_indent < indent):
indent = line_indent
indent = indent or 0
current_section = None
for line in doc_lines:
line_indent = get_line_indent(line)
if line_indent > 0:
line = line[indent:]
if line.startswith(self.SECTION_PREFIX):
if current_section:
sections.append(current_section.to_md())
section_name = line[len(self.SECTION_PREFIX):].strip()
if section_name.lower().strip() == self.SECTION_END:
current_section = None
else:
current_section = SpiderDocsSection(
section_name,
processor=section_processors.get(section_name.lower())
)
continue
if current_section:
current_section.append(line)
if current_section:
sections.append(current_section.to_md())
if sections:
output.append(
"## {spider_name} ({class_name})".format(
spider_name=spider.name,
class_name=spider.__name__
)
)
output.extend(sections)
spiders_count_documented += 1
output = '\n\n'.join(output)
if location:
with open(location, 'w') as f:
f.write(output)
print(
"{module} -> {location} ({documented}/{total} spiders)".format(
module=module,
location=location,
total=spiders_count_total,
documented=spiders_count_documented
)
)
else:
print(output)
| en | 0.158737 | ## {name}\n\n{content}".format( # {<module>: <destination>} # {<section_name>: <function(name, content) -> str>} # calculate base text indent # {spider_name} ({class_name})".format( | 2.551528 | 3 |
testmodel.py | BTTHuyen/engagement-detection | 9 | 6620359 | #!/usr/bin/env python3
import os
import pickle
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.optimizers import Adam
from data.load_data import get_fer2013_data, get_ckplus_data
from util.baseimgops import resize, grayscale
from models.model_factory import *
X_train, X_validation, X_test, y_train, y_validation, y_test = get_fer2013_data()
# Choose which model to load, and from what directory (model, savedmodels).
# Additionally, choose whether loading only from weights or from architecture + weights.
model = load_keras_model('more-interesting-0.627')
# img = cv2.imread("test_imgs/unnamed.jpg")
# img = grayscale(resize(img))
# print(np.argmax(model.predict(img)))
loss, acc = model.evaluate(X_test, y_test)
print("Accuracy: " + str(acc))
# Confusion Matrix
predictions = list(np.argmax(item) for item in model.predict(X_test))
actual = list(np.argmax(item) for item in y_test)
cf = confusion_matrix(predictions, actual)
svm = sns.heatmap(cf, annot = True)
plt.show()
# Save for example purposes.
save = False
if save:
fig = svm.get_figure()
fig.savefig("examples/confusionmatrix.png")
| #!/usr/bin/env python3
import os
import pickle
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.optimizers import Adam
from data.load_data import get_fer2013_data, get_ckplus_data
from util.baseimgops import resize, grayscale
from models.model_factory import *
X_train, X_validation, X_test, y_train, y_validation, y_test = get_fer2013_data()
# Choose which model to load, and from what directory (model, savedmodels).
# Additionally, choose whether loading only from weights or from architecture + weights.
model = load_keras_model('more-interesting-0.627')
# img = cv2.imread("test_imgs/unnamed.jpg")
# img = grayscale(resize(img))
# print(np.argmax(model.predict(img)))
loss, acc = model.evaluate(X_test, y_test)
print("Accuracy: " + str(acc))
# Confusion Matrix
predictions = list(np.argmax(item) for item in model.predict(X_test))
actual = list(np.argmax(item) for item in y_test)
cf = confusion_matrix(predictions, actual)
svm = sns.heatmap(cf, annot = True)
plt.show()
# Save for example purposes.
save = False
if save:
fig = svm.get_figure()
fig.savefig("examples/confusionmatrix.png")
| en | 0.680525 | #!/usr/bin/env python3 # Choose which model to load, and from what directory (model, savedmodels). # Additionally, choose whether loading only from weights or from architecture + weights. # img = cv2.imread("test_imgs/unnamed.jpg") # img = grayscale(resize(img)) # print(np.argmax(model.predict(img))) # Confusion Matrix # Save for example purposes. | 2.758339 | 3 |
summarize.py | tylerweston/talc | 0 | 6620360 | <reponame>tylerweston/talc
import json
import requests
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
from decouple import UndefinedValueError, config
import re
import nltk
from nltk.corpus import wordnet
from nltk.corpus import stopwords
import random
from hashlib import sha1
from datetime import datetime
from main import console, spinner_choice
from config import *
import pyttsx3
from utils import fix_abbreviations
from pathlib import Path
from TTS.config import load_config
from TTS.utils.manage import ModelManager
from TTS.utils.synthesizer import Synthesizer
import numpy as np
import soundfile as sf
from pedalboard import (
Pedalboard,
Compressor,
Chorus,
Gain,
Reverb,
Limiter,
LadderFilter,
Phaser,
Distortion,
NoiseGate,
)
# Load nltk libraries when summarize is imported
with console.status("[bold green]Loading nltk...", spinner=spinner_choice):
nltk.download('wordnet', quiet=True)
nltk.download('omw-1.4', quiet=True)
def add_audio_effects(in_file, out_file):
console.print("Adding audio effects...", end='')
# use pedalboard to add some random audio effects to in_file and write to out_file
audio, sample_rate = sf.read(in_file)
# Make a Pedalboard object, containing multiple plugins:
board1 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
Chorus(),
LadderFilter(mode=LadderFilter.Mode.HPF12, cutoff_hz=900),
Phaser(),
Reverb(room_size=0.25),
Compressor(threshold_db=-25, ratio=10),
Gain(gain_db=10),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board2 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Reverb(room_size=0.25),
Gain(gain_db=30),
Distortion(),
NoiseGate(),
Phaser(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board3 = Pedalboard([
Reverb(room_size=0.15),
# Distortion(),
LadderFilter(mode=LadderFilter.Mode.LPF12, cutoff_hz=1800),
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
Distortion(),
NoiseGate(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board4 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
LadderFilter(mode=LadderFilter.Mode.LPF12, cutoff_hz=2000),
Phaser(),
Gain(gain_db=10),
Limiter(),
Distortion(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board5 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Reverb(room_size=0.35),
Distortion(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
boards = [board1, board2, board3, board4, board5]
effected = np.zeros_like(audio)
i = 0
while i < audio.shape[0]:
step_size = random.randint(800, 2500)
if i + step_size > audio.shape[0]:
step_size = audio.shape[0] - i
if random.random() < 0.95:
effected[i:i+step_size] = audio[i:i+step_size]
i += step_size
continue
cur_board = random.choice(boards)
chunk = cur_board.process(audio[i:i+step_size], reset=False)
effected[i:i+step_size] = chunk
i += step_size
stutter_window_size = random.randint(300, 800)
random_repeats = random.randint(4, 15)
i = 0
while i + (stutter_window_size * random_repeats) < audio.shape[0]:
update_step_size = stutter_window_size * random_repeats
if random.random() < 0.995:
i += update_step_size
continue
copy_from = effected[i:i+stutter_window_size]
for j in range(1, random_repeats + 1):
effected[i+(j*stutter_window_size):i+((j+1) * stutter_window_size)] = copy_from
stutter_window_size = random.randint(300, 800)
random_repeats = random.randint(4, 15)
i += update_step_size
with sf.SoundFile(out_file, 'w', samplerate=sample_rate, channels=len(effected.shape)) as f:
f.write(effected)
console.print("Done!")
def coqui_tts(text_to_synthesize, output_file):
# ..\wikivids\venv\Lib\site-packages\TTS
# TODO: The user\AppData\Local\tts folder is getting BIG! Should we maybe delete this folder when we're done with it?!
# But we don't want to redownload the models every time we run it either. Hmmm.
voices = [
# r"tts_models/en/ek1/tacotron2",
r"tts_models/en/ljspeech/tacotron2-DDC",
r"tts_models/en/ljspeech/tacotron2-DDC_ph",
r"tts_models/en/ljspeech/glow-tts",
r"tts_models/en/ljspeech/tacotron2-DCA",
# r"tts_models/en/ljspeech/speedy-speech-wn",
# r"tts_models/en/ljspeech/vits",
# r"tts_models/en/vctk/sc-glow-tts",
# r"tts_models/en/vctk/vits",
]
# tacotron2 + wavegrad = hangs?
voice=random.choice(voices)
path = Path(__file__).parent / r"venv/Lib/site-packages/TTS/.models.json"
# print(path)
manager = ModelManager(path)
model_path, config_path, model_item = manager.download_model(voice)
vocoder_name = model_item["default_vocoder"]
vocoder_path, vocoder_config_path, _ = manager.download_model(vocoder_name)
speakers_file_path = None
# load models
synthesizer = Synthesizer(
tts_checkpoint=model_path,
tts_config_path=config_path,
tts_speakers_file=speakers_file_path,
tts_languages_file=None,
vocoder_checkpoint=vocoder_path,
vocoder_config=vocoder_config_path,
encoder_checkpoint="",
encoder_config="",
use_cuda=False,
)
# use_multi_speaker = hasattr(synthesizer.tts_model, "num_speakers") and synthesizer.tts_model.num_speakers > 1
# speaker_manager = getattr(synthesizer.tts_model, "speaker_manager", None)
# print(speaker_manager)
# print(speaker_manager.speaker_ids)
# # TODO: set this from SpeakerManager
# use_gst = synthesizer.tts_config.get("use_gst", False)
# text = "A quick little demo to see if we can get TTS up and running."
speaker_idx = ""
style_wav = ""
wav = synthesizer.tts(text_to_synthesize, speaker_name=speaker_idx, style_wav=style_wav)
synthesizer.save_wav(wav, output_file)
def get_article(use_article=None):
# print("Finding random Wikipedia article", end="")
with console.status("[bold green]Finding random Wikipedia article...",spinner=spinner_choice):
while True:
if use_article is None:
# Get random wikipedia page
wiki_page = requests.get(
"https://en.wikipedia.org/api/rest_v1/page/random/html"
)
soup = BeautifulSoup(wiki_page.content, "html.parser")
# Extract title
# TODO: Sometimes this will fail? Just grab a new random html!
page_link = soup.find("link", href=True)["href"]
title = page_link.split("/")[-1]
else:
title = use_article
# Get text content of page
text_content = requests.get(
f"https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&explaintext&titles={title}&format=json"
)
text_json = json.loads(text_content.content)
wiki_page_content = text_json["query"]["pages"]
_, value = list(wiki_page_content.items())[0]
try:
wiki_page_title = value["title"]
wiki_page_content = value["extract"]
except KeyError as ke:
console.print("[bold red]Warning[/bold red]: Problem getting article, trying again")
console.print(str(ke))
console.print(value)
continue
# Remove everything after == References ==
wiki_page_content = wiki_page_content.split("== References ==")[0].strip()
# TODO: Refactor, this logic below is confusing
if use_article is None and len(wiki_page_content) < MINIMUM_ARTICLE_LENGTH:
# this article is too short, but we can ignore this if we've provided the article.
continue
else:
# We have a good article, either it's the right length or we're using a provided article
if USE_PROMPTS:
console.print(f"\naccept article {wiki_page_title}? y/n:", end='')
res = input()
if res.lower() == 'n':
continue
break
# TODOne? Remove bad punctuation from wiki_page_title!
# wiki_page_title = re.sub(r'[\W\s]+', '', wiki_page_title)
console.print(f"\nFound article [bold green]{wiki_page_title}")
# Remove headers
wiki_page_content = re.sub("===.*===", "", wiki_page_content)
wiki_page_content = re.sub("==.*==", "", wiki_page_content)
wiki_page_content = fix_abbreviations(wiki_page_content)
return title, wiki_page_title, wiki_page_content
def summarize_article(wiki_page_content):
# Summarize
# • SM_API_KEY=N Required, your API key.
# • SM_URL=X Optional, the webpage to summarize.
# • SM_LENGTH=N Optional, the number of sentences returned, default 7.
# • SM_KEYWORD_COUNT=N Optional, N the number of keywords to return.
# • SM_WITH_BREAK Optional, inserts the string [BREAK] between sentences.
# • SM_WITH_ENCODE Optional, converts HTML entities to their applicable chars.
# • SM_IGNORE_LENGTH Optional, returns summary regardless of quality or length.
# • SM_QUOTE_AVOID Optional, sentences with quotations will be excluded.
# • SM_QUESTION_AVOID Optional, sentences with question will be excluded.
# • SM_EXCLAMATION_AVOID Optional, sentences with exclamation marks will be excluded.
API_ENDPOINT = "https://api.smmry.com"
try:
API_KEY = config("SMMRY_API_KEY")
except UndefinedValueError as e:
console.print("[bold red]Error[/bold red]: Please set SMMRY_API_KEY in your .env file to use smmry")
console.print(e)
exit(0)
data = {"sm_api_input": wiki_page_content}
params = {
"SM_API_KEY": API_KEY,
"SM_LENGTH": NUM_SMMRY_SENTENCES,
"SM_KEYWORD_COUNT": 10,
# "SM_QUOTE_AVOID": True,
# "SM_QUESTION_AVOID": True,
}
header_params = {"Expect": "100-continue"}
smmry_response = requests.post(
url=API_ENDPOINT, params=params, data=data, headers=header_params
)
smmry_json = json.loads(smmry_response.content)
try:
summary = smmry_json["sm_api_content"]
keywords = smmry_json["sm_api_keyword_array"]
except KeyError as e:
console.print("[bold red]Error[/bold red]: Problem with results from smmry API!")
console.print(str(e))
exit(1)
keywords = [urllib.parse.unquote(k) for k in keywords]
# # Read in remove keywords from file
# with open("remove_keywords") as f:
# content = f.readlines()
# remove_keywords_list = [x.strip() for x in content]s
remove_keywords_list = list(set(stopwords.words("english")))
# Remove not useful keywords
keywords = [k for k in keywords if k.lower() not in remove_keywords_list]
# Generate some new keywords based on synonyms for existing keywords
for _ in range(5):
syn = get_synonyms(random.choice(keywords))
if len(syn) == 0:
continue
new_syn = random.choice(syn)
keywords.append(new_syn)
# remove duplicates
keywords = list(set(keywords))
# Generate summary hash, use first 12 hex digits of a
# SHA1 hash generated from the summary text
summary_hash = sha1()
summary_hash.update(summary.encode("utf-8"))
summary_hash_text = str(summary_hash.hexdigest())[:12]
console.print(f"Got hash: [bold green]{summary_hash_text}")
# remove all angle brackets from summary, youtube descriptions don't like them
summary = re.sub(r'(<*>*)*', '', summary)
return keywords, summary, summary_hash_text
def get_synonyms(word):
# Get synonyms
synonyms = []
for syn in wordnet.synsets(word):
for l in syn.lemmas():
synonyms.append(l.name())
syns = list(set(synonyms))
# for each word in syns, replace _ with space
syns = [re.sub("_", " ", s) for s in syns]
return syns
def generate_and_write_summary(movie_title, summary, keywords):
summary_text = f"{movie_title}:\n{summary}\n\nkeywords: {', '.join(keywords)}\n\n"
today = datetime.now()
summary_text += f"the aleatoric learning channel\n{today}\n"
with open(
f"finished/{movie_title}.txt", "w", encoding="utf-8"
) as summary_text_file:
summary_text_file.write(summary_text)
def pyttsx(text, file):
# Convert to speech
speech_engine = pyttsx3.init()
# Get list of all available voices and choose a random one
voices = speech_engine.getProperty("voices")
speech_engine.setProperty("voice", random.choice(voices).id)
speech_engine.setProperty("rate", 175)
speech_engine.save_to_file(
text,
file,
)
speech_engine.runAndWait()
def make_narration(text):
with console.status("[bold green]Making narration...",spinner=spinner_choice):
# Always use coqui?
coqui_tts(text, "narration.wav")
# if (random.randint(0,1) == 0):
# coqui_tts(text, "narration.wav")
# else:
# pyttsx(text, "narration.wav")
return
| import json
import requests
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
from decouple import UndefinedValueError, config
import re
import nltk
from nltk.corpus import wordnet
from nltk.corpus import stopwords
import random
from hashlib import sha1
from datetime import datetime
from main import console, spinner_choice
from config import *
import pyttsx3
from utils import fix_abbreviations
from pathlib import Path
from TTS.config import load_config
from TTS.utils.manage import ModelManager
from TTS.utils.synthesizer import Synthesizer
import numpy as np
import soundfile as sf
from pedalboard import (
Pedalboard,
Compressor,
Chorus,
Gain,
Reverb,
Limiter,
LadderFilter,
Phaser,
Distortion,
NoiseGate,
)
# Load nltk libraries when summarize is imported
with console.status("[bold green]Loading nltk...", spinner=spinner_choice):
nltk.download('wordnet', quiet=True)
nltk.download('omw-1.4', quiet=True)
def add_audio_effects(in_file, out_file):
console.print("Adding audio effects...", end='')
# use pedalboard to add some random audio effects to in_file and write to out_file
audio, sample_rate = sf.read(in_file)
# Make a Pedalboard object, containing multiple plugins:
board1 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
Chorus(),
LadderFilter(mode=LadderFilter.Mode.HPF12, cutoff_hz=900),
Phaser(),
Reverb(room_size=0.25),
Compressor(threshold_db=-25, ratio=10),
Gain(gain_db=10),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board2 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Reverb(room_size=0.25),
Gain(gain_db=30),
Distortion(),
NoiseGate(),
Phaser(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board3 = Pedalboard([
Reverb(room_size=0.15),
# Distortion(),
LadderFilter(mode=LadderFilter.Mode.LPF12, cutoff_hz=1800),
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
Distortion(),
NoiseGate(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board4 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
LadderFilter(mode=LadderFilter.Mode.LPF12, cutoff_hz=2000),
Phaser(),
Gain(gain_db=10),
Limiter(),
Distortion(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
board5 = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Reverb(room_size=0.35),
Distortion(),
Limiter(),
Gain(gain_db=-20),
], sample_rate=sample_rate)
boards = [board1, board2, board3, board4, board5]
effected = np.zeros_like(audio)
i = 0
while i < audio.shape[0]:
step_size = random.randint(800, 2500)
if i + step_size > audio.shape[0]:
step_size = audio.shape[0] - i
if random.random() < 0.95:
effected[i:i+step_size] = audio[i:i+step_size]
i += step_size
continue
cur_board = random.choice(boards)
chunk = cur_board.process(audio[i:i+step_size], reset=False)
effected[i:i+step_size] = chunk
i += step_size
stutter_window_size = random.randint(300, 800)
random_repeats = random.randint(4, 15)
i = 0
while i + (stutter_window_size * random_repeats) < audio.shape[0]:
update_step_size = stutter_window_size * random_repeats
if random.random() < 0.995:
i += update_step_size
continue
copy_from = effected[i:i+stutter_window_size]
for j in range(1, random_repeats + 1):
effected[i+(j*stutter_window_size):i+((j+1) * stutter_window_size)] = copy_from
stutter_window_size = random.randint(300, 800)
random_repeats = random.randint(4, 15)
i += update_step_size
with sf.SoundFile(out_file, 'w', samplerate=sample_rate, channels=len(effected.shape)) as f:
f.write(effected)
console.print("Done!")
def coqui_tts(text_to_synthesize, output_file):
# ..\wikivids\venv\Lib\site-packages\TTS
# TODO: The user\AppData\Local\tts folder is getting BIG! Should we maybe delete this folder when we're done with it?!
# But we don't want to redownload the models every time we run it either. Hmmm.
voices = [
# r"tts_models/en/ek1/tacotron2",
r"tts_models/en/ljspeech/tacotron2-DDC",
r"tts_models/en/ljspeech/tacotron2-DDC_ph",
r"tts_models/en/ljspeech/glow-tts",
r"tts_models/en/ljspeech/tacotron2-DCA",
# r"tts_models/en/ljspeech/speedy-speech-wn",
# r"tts_models/en/ljspeech/vits",
# r"tts_models/en/vctk/sc-glow-tts",
# r"tts_models/en/vctk/vits",
]
# tacotron2 + wavegrad = hangs?
voice=random.choice(voices)
path = Path(__file__).parent / r"venv/Lib/site-packages/TTS/.models.json"
# print(path)
manager = ModelManager(path)
model_path, config_path, model_item = manager.download_model(voice)
vocoder_name = model_item["default_vocoder"]
vocoder_path, vocoder_config_path, _ = manager.download_model(vocoder_name)
speakers_file_path = None
# load models
synthesizer = Synthesizer(
tts_checkpoint=model_path,
tts_config_path=config_path,
tts_speakers_file=speakers_file_path,
tts_languages_file=None,
vocoder_checkpoint=vocoder_path,
vocoder_config=vocoder_config_path,
encoder_checkpoint="",
encoder_config="",
use_cuda=False,
)
# use_multi_speaker = hasattr(synthesizer.tts_model, "num_speakers") and synthesizer.tts_model.num_speakers > 1
# speaker_manager = getattr(synthesizer.tts_model, "speaker_manager", None)
# print(speaker_manager)
# print(speaker_manager.speaker_ids)
# # TODO: set this from SpeakerManager
# use_gst = synthesizer.tts_config.get("use_gst", False)
# text = "A quick little demo to see if we can get TTS up and running."
speaker_idx = ""
style_wav = ""
wav = synthesizer.tts(text_to_synthesize, speaker_name=speaker_idx, style_wav=style_wav)
synthesizer.save_wav(wav, output_file)
def get_article(use_article=None):
# print("Finding random Wikipedia article", end="")
with console.status("[bold green]Finding random Wikipedia article...",spinner=spinner_choice):
while True:
if use_article is None:
# Get random wikipedia page
wiki_page = requests.get(
"https://en.wikipedia.org/api/rest_v1/page/random/html"
)
soup = BeautifulSoup(wiki_page.content, "html.parser")
# Extract title
# TODO: Sometimes this will fail? Just grab a new random html!
page_link = soup.find("link", href=True)["href"]
title = page_link.split("/")[-1]
else:
title = use_article
# Get text content of page
text_content = requests.get(
f"https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&explaintext&titles={title}&format=json"
)
text_json = json.loads(text_content.content)
wiki_page_content = text_json["query"]["pages"]
_, value = list(wiki_page_content.items())[0]
try:
wiki_page_title = value["title"]
wiki_page_content = value["extract"]
except KeyError as ke:
console.print("[bold red]Warning[/bold red]: Problem getting article, trying again")
console.print(str(ke))
console.print(value)
continue
# Remove everything after == References ==
wiki_page_content = wiki_page_content.split("== References ==")[0].strip()
# TODO: Refactor, this logic below is confusing
if use_article is None and len(wiki_page_content) < MINIMUM_ARTICLE_LENGTH:
# this article is too short, but we can ignore this if we've provided the article.
continue
else:
# We have a good article, either it's the right length or we're using a provided article
if USE_PROMPTS:
console.print(f"\naccept article {wiki_page_title}? y/n:", end='')
res = input()
if res.lower() == 'n':
continue
break
# TODOne? Remove bad punctuation from wiki_page_title!
# wiki_page_title = re.sub(r'[\W\s]+', '', wiki_page_title)
console.print(f"\nFound article [bold green]{wiki_page_title}")
# Remove headers
wiki_page_content = re.sub("===.*===", "", wiki_page_content)
wiki_page_content = re.sub("==.*==", "", wiki_page_content)
wiki_page_content = fix_abbreviations(wiki_page_content)
return title, wiki_page_title, wiki_page_content
def summarize_article(wiki_page_content):
# Summarize
# • SM_API_KEY=N Required, your API key.
# • SM_URL=X Optional, the webpage to summarize.
# • SM_LENGTH=N Optional, the number of sentences returned, default 7.
# • SM_KEYWORD_COUNT=N Optional, N the number of keywords to return.
# • SM_WITH_BREAK Optional, inserts the string [BREAK] between sentences.
# • SM_WITH_ENCODE Optional, converts HTML entities to their applicable chars.
# • SM_IGNORE_LENGTH Optional, returns summary regardless of quality or length.
# • SM_QUOTE_AVOID Optional, sentences with quotations will be excluded.
# • SM_QUESTION_AVOID Optional, sentences with question will be excluded.
# • SM_EXCLAMATION_AVOID Optional, sentences with exclamation marks will be excluded.
API_ENDPOINT = "https://api.smmry.com"
try:
API_KEY = config("SMMRY_API_KEY")
except UndefinedValueError as e:
console.print("[bold red]Error[/bold red]: Please set SMMRY_API_KEY in your .env file to use smmry")
console.print(e)
exit(0)
data = {"sm_api_input": wiki_page_content}
params = {
"SM_API_KEY": API_KEY,
"SM_LENGTH": NUM_SMMRY_SENTENCES,
"SM_KEYWORD_COUNT": 10,
# "SM_QUOTE_AVOID": True,
# "SM_QUESTION_AVOID": True,
}
header_params = {"Expect": "100-continue"}
smmry_response = requests.post(
url=API_ENDPOINT, params=params, data=data, headers=header_params
)
smmry_json = json.loads(smmry_response.content)
try:
summary = smmry_json["sm_api_content"]
keywords = smmry_json["sm_api_keyword_array"]
except KeyError as e:
console.print("[bold red]Error[/bold red]: Problem with results from smmry API!")
console.print(str(e))
exit(1)
keywords = [urllib.parse.unquote(k) for k in keywords]
# # Read in remove keywords from file
# with open("remove_keywords") as f:
# content = f.readlines()
# remove_keywords_list = [x.strip() for x in content]s
remove_keywords_list = list(set(stopwords.words("english")))
# Remove not useful keywords
keywords = [k for k in keywords if k.lower() not in remove_keywords_list]
# Generate some new keywords based on synonyms for existing keywords
for _ in range(5):
syn = get_synonyms(random.choice(keywords))
if len(syn) == 0:
continue
new_syn = random.choice(syn)
keywords.append(new_syn)
# remove duplicates
keywords = list(set(keywords))
# Generate summary hash, use first 12 hex digits of a
# SHA1 hash generated from the summary text
summary_hash = sha1()
summary_hash.update(summary.encode("utf-8"))
summary_hash_text = str(summary_hash.hexdigest())[:12]
console.print(f"Got hash: [bold green]{summary_hash_text}")
# remove all angle brackets from summary, youtube descriptions don't like them
summary = re.sub(r'(<*>*)*', '', summary)
return keywords, summary, summary_hash_text
def get_synonyms(word):
# Get synonyms
synonyms = []
for syn in wordnet.synsets(word):
for l in syn.lemmas():
synonyms.append(l.name())
syns = list(set(synonyms))
# for each word in syns, replace _ with space
syns = [re.sub("_", " ", s) for s in syns]
return syns
def generate_and_write_summary(movie_title, summary, keywords):
summary_text = f"{movie_title}:\n{summary}\n\nkeywords: {', '.join(keywords)}\n\n"
today = datetime.now()
summary_text += f"the aleatoric learning channel\n{today}\n"
with open(
f"finished/{movie_title}.txt", "w", encoding="utf-8"
) as summary_text_file:
summary_text_file.write(summary_text)
def pyttsx(text, file):
# Convert to speech
speech_engine = pyttsx3.init()
# Get list of all available voices and choose a random one
voices = speech_engine.getProperty("voices")
speech_engine.setProperty("voice", random.choice(voices).id)
speech_engine.setProperty("rate", 175)
speech_engine.save_to_file(
text,
file,
)
speech_engine.runAndWait()
def make_narration(text):
with console.status("[bold green]Making narration...",spinner=spinner_choice):
# Always use coqui?
coqui_tts(text, "narration.wav")
# if (random.randint(0,1) == 0):
# coqui_tts(text, "narration.wav")
# else:
# pyttsx(text, "narration.wav")
return | en | 0.688738 | # Load nltk libraries when summarize is imported # use pedalboard to add some random audio effects to in_file and write to out_file # Make a Pedalboard object, containing multiple plugins: # Distortion(), # ..\wikivids\venv\Lib\site-packages\TTS # TODO: The user\AppData\Local\tts folder is getting BIG! Should we maybe delete this folder when we're done with it?! # But we don't want to redownload the models every time we run it either. Hmmm. # r"tts_models/en/ek1/tacotron2", # r"tts_models/en/ljspeech/speedy-speech-wn", # r"tts_models/en/ljspeech/vits", # r"tts_models/en/vctk/sc-glow-tts", # r"tts_models/en/vctk/vits", # tacotron2 + wavegrad = hangs? # print(path) # load models # use_multi_speaker = hasattr(synthesizer.tts_model, "num_speakers") and synthesizer.tts_model.num_speakers > 1 # speaker_manager = getattr(synthesizer.tts_model, "speaker_manager", None) # print(speaker_manager) # print(speaker_manager.speaker_ids) # # TODO: set this from SpeakerManager # use_gst = synthesizer.tts_config.get("use_gst", False) # text = "A quick little demo to see if we can get TTS up and running." # print("Finding random Wikipedia article", end="") # Get random wikipedia page # Extract title # TODO: Sometimes this will fail? Just grab a new random html! # Get text content of page # Remove everything after == References == # TODO: Refactor, this logic below is confusing # this article is too short, but we can ignore this if we've provided the article. # We have a good article, either it's the right length or we're using a provided article # TODOne? Remove bad punctuation from wiki_page_title! # wiki_page_title = re.sub(r'[\W\s]+', '', wiki_page_title) # Remove headers # Summarize # • SM_API_KEY=N Required, your API key. # • SM_URL=X Optional, the webpage to summarize. # • SM_LENGTH=N Optional, the number of sentences returned, default 7. # • SM_KEYWORD_COUNT=N Optional, N the number of keywords to return. # • SM_WITH_BREAK Optional, inserts the string [BREAK] between sentences. # • SM_WITH_ENCODE Optional, converts HTML entities to their applicable chars. # • SM_IGNORE_LENGTH Optional, returns summary regardless of quality or length. # • SM_QUOTE_AVOID Optional, sentences with quotations will be excluded. # • SM_QUESTION_AVOID Optional, sentences with question will be excluded. # • SM_EXCLAMATION_AVOID Optional, sentences with exclamation marks will be excluded. # "SM_QUOTE_AVOID": True, # "SM_QUESTION_AVOID": True, # # Read in remove keywords from file # with open("remove_keywords") as f: # content = f.readlines() # remove_keywords_list = [x.strip() for x in content]s # Remove not useful keywords # Generate some new keywords based on synonyms for existing keywords # remove duplicates # Generate summary hash, use first 12 hex digits of a # SHA1 hash generated from the summary text # remove all angle brackets from summary, youtube descriptions don't like them # Get synonyms # for each word in syns, replace _ with space # Convert to speech # Get list of all available voices and choose a random one # Always use coqui? # if (random.randint(0,1) == 0): # coqui_tts(text, "narration.wav") # else: # pyttsx(text, "narration.wav") | 2.497185 | 2 |
mathseq/seq.py | TheGreatestShoaib/MathSeq | 1 | 6620361 | <gh_stars>1-10
"""
this is the doc string of this model
i'll just write it someday just yeah thats all
"""
import time
import random
def composite_numbers():
'''
-It generates composite numbers which are just opposite of prime numbers,,
it means real numbers that
aren't a prime number is a composite number
'''
n = 2
while n > 0:
for x in range(2, n):
if n % x == 0:
yield n
break
n+=1
def prime_numbers(end):
'''
- A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
- Prime numbers are very useful in cryptography
Prime numbers are considered as the most exciting numbers among the math lovers..
'''
for n in range(2,end):
for x in range(2, n):
if n % x == 0:
pass
else:
yield n
def odd_seq(inverse=False):
'''
This function generates odd sequence
An odd number is a number which is not divisible by 2.
'''
if inverse is False:
n = 1
while True:
yield n
n+=2
else:
n = -1
while True:
yield n
n-=2
def even_seq(inverse=False):
'''
- even_seq generates infinite sequence of even numbers
-A number which is divisible by 2 and generates a remainder of 0 is called an even number.
'''
n = 0
if inverse is False:
while True:
yield n
n+=2
else:
while True:
yield n
n-=2
def fibonacci():
'''
- In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence,
called the Fibonacci sequence, such that each number is the sum of the two preceding ones,
starting from 0 and 1.
- The Following Formula is "fn = fn-1 + fn-2 ".
- Fibonacci is really a mysterious sequence !
'''
x , y = 0 ,1
while True:
r = x + y
x = y
y = r
yield x
def xibonacci(x,inverse=False):
'''
- xibonacci isn't a real sequence rather it's just a method that generates
a sequence of number such that each term from the "x"
onward is the sum of previous "x" terms.
similar as fibonacci that sums previous "x" terms.
-xibonacci usually requires one positional arguments that is the value of "x".
- possible sequences that could be generated through this method:
- fibonacci
- tribonacci
- tetrabonacci
- hexabonacci
And so on ... to the infinity !
'''
inp = int(x)
empty_list = []
for _ in range(inp-1):
empty_list.append(0)
if inverse is False:
empty_list.append(1)
else:
empty_list.append(-1)
while True:
x = empty_list[-inp:]
empty_list = empty_list[-inp:]
y = sum(empty_list)
yield empty_list[-1]
empty_list.append(y)
def lucas_number(inverse=False):
'''
- The Lucas sequence has the same recursive relationship as the "Fibonacci" sequence,
where each term is the sum of the two previous terms, but with different starting values
- This produces a sequence where the ratios of successive terms approach the golden ratio,
and in fact the terms themselves are roundings("round()") of integer powers of the golden ratio.
- `x` and `y` are the constant starting_point for `Lucas Sequence`.
'''
if not inverse:
x,y,r = 2,1,0
else:
x ,y,r = -2,-1,0
while True:
yield x
r = x+y
x = y
y = r
def catalan_numbers():
"""
- In combinatorial mathematics,the Catalan numbers form a sequence of natural numbers
that occur in various counting problems,often involving recursively defined objects.
- Follows "n = 1/(n+1)(2n*n)"
"""
res = 0
catalan_list = [1,1]
i = 0
while True:
yield catalan_list[i]
res = 0
for x in range(len(catalan_list)):
res += catalan_list[x] * catalan_list [-(x+1)]
catalan_list.append(res)
i+=1
def vaneck_seq(inverse=False):
'''
-This Algorithm was taked from OEIS and the author is <NAME>..
'''
try:
list_vanseq = [0]
last_pos = {}
i = 0
while True:
new_value = i - last_pos.get(list_vanseq[i], i)
list_vanseq.append(new_value)
last_pos[list_vanseq[i]] = i
yield new_value
i += 1
except KeyError:
pass
def pronic_numbers():
'''
- A pronic number is a number which is the product of two consecutive integers,
that is, a number of the form n(n + 1).
- Details:
* https://en.wikipedia.org/wiki/Pronic_number
* https://oeis.org/A002378
'''
increase , digit = 0 , 0
while True:
digit += increase
yield digit
increase+=2
def random_numbers(number_type="regular",limits=1000,seed=None):
'''
- Random Numbers Are Just Random Numbers As It Looks By Its Name,
- Use Seed For Controlling their Randomness,
- `Limits` Defines The Range.
'''
while True:
if seed is not None:
random.seed(seed)
breh = random.randint(0,10**4)
yield breh
def looknsay(starting_point="1",inverse=None):
'''
- To generate a member of the sequence from the previous member, read off the digits of the previous member,
counting the number of digits in groups of the same digit. For example:
- 1 is read off as "one 1" or 11.
- 11 is read off as "two 1s" or 21.
- 21 is read off as "one 2, then one 1" or 1211.
- 1211 is read off as "one 1, one 2, then two 1s" or 1112
- The sequence grows indefinitely. In fact, any variant defined by
starting with a different integer seed number will (eventually) also grow indefinitely,
'''
starting_point = str(starting_point)
def count_next(word):
prev= word[0]
count= 1
say = ''
for curr in word[1:]:
if curr == prev:
count += 1
continue
say += str(count) + prev
prev = curr
count = 1
breh = say + str(count) + prev
return breh
recursed_val = count_next(starting_point)
if recursed_val == "11":
yield "1"
yield recursed_val
yield from looknsay(recursed_val)
| """
this is the doc string of this model
i'll just write it someday just yeah thats all
"""
import time
import random
def composite_numbers():
'''
-It generates composite numbers which are just opposite of prime numbers,,
it means real numbers that
aren't a prime number is a composite number
'''
n = 2
while n > 0:
for x in range(2, n):
if n % x == 0:
yield n
break
n+=1
def prime_numbers(end):
'''
- A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
- Prime numbers are very useful in cryptography
Prime numbers are considered as the most exciting numbers among the math lovers..
'''
for n in range(2,end):
for x in range(2, n):
if n % x == 0:
pass
else:
yield n
def odd_seq(inverse=False):
'''
This function generates odd sequence
An odd number is a number which is not divisible by 2.
'''
if inverse is False:
n = 1
while True:
yield n
n+=2
else:
n = -1
while True:
yield n
n-=2
def even_seq(inverse=False):
'''
- even_seq generates infinite sequence of even numbers
-A number which is divisible by 2 and generates a remainder of 0 is called an even number.
'''
n = 0
if inverse is False:
while True:
yield n
n+=2
else:
while True:
yield n
n-=2
def fibonacci():
'''
- In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence,
called the Fibonacci sequence, such that each number is the sum of the two preceding ones,
starting from 0 and 1.
- The Following Formula is "fn = fn-1 + fn-2 ".
- Fibonacci is really a mysterious sequence !
'''
x , y = 0 ,1
while True:
r = x + y
x = y
y = r
yield x
def xibonacci(x,inverse=False):
'''
- xibonacci isn't a real sequence rather it's just a method that generates
a sequence of number such that each term from the "x"
onward is the sum of previous "x" terms.
similar as fibonacci that sums previous "x" terms.
-xibonacci usually requires one positional arguments that is the value of "x".
- possible sequences that could be generated through this method:
- fibonacci
- tribonacci
- tetrabonacci
- hexabonacci
And so on ... to the infinity !
'''
inp = int(x)
empty_list = []
for _ in range(inp-1):
empty_list.append(0)
if inverse is False:
empty_list.append(1)
else:
empty_list.append(-1)
while True:
x = empty_list[-inp:]
empty_list = empty_list[-inp:]
y = sum(empty_list)
yield empty_list[-1]
empty_list.append(y)
def lucas_number(inverse=False):
'''
- The Lucas sequence has the same recursive relationship as the "Fibonacci" sequence,
where each term is the sum of the two previous terms, but with different starting values
- This produces a sequence where the ratios of successive terms approach the golden ratio,
and in fact the terms themselves are roundings("round()") of integer powers of the golden ratio.
- `x` and `y` are the constant starting_point for `Lucas Sequence`.
'''
if not inverse:
x,y,r = 2,1,0
else:
x ,y,r = -2,-1,0
while True:
yield x
r = x+y
x = y
y = r
def catalan_numbers():
"""
- In combinatorial mathematics,the Catalan numbers form a sequence of natural numbers
that occur in various counting problems,often involving recursively defined objects.
- Follows "n = 1/(n+1)(2n*n)"
"""
res = 0
catalan_list = [1,1]
i = 0
while True:
yield catalan_list[i]
res = 0
for x in range(len(catalan_list)):
res += catalan_list[x] * catalan_list [-(x+1)]
catalan_list.append(res)
i+=1
def vaneck_seq(inverse=False):
'''
-This Algorithm was taked from OEIS and the author is <NAME>..
'''
try:
list_vanseq = [0]
last_pos = {}
i = 0
while True:
new_value = i - last_pos.get(list_vanseq[i], i)
list_vanseq.append(new_value)
last_pos[list_vanseq[i]] = i
yield new_value
i += 1
except KeyError:
pass
def pronic_numbers():
'''
- A pronic number is a number which is the product of two consecutive integers,
that is, a number of the form n(n + 1).
- Details:
* https://en.wikipedia.org/wiki/Pronic_number
* https://oeis.org/A002378
'''
increase , digit = 0 , 0
while True:
digit += increase
yield digit
increase+=2
def random_numbers(number_type="regular",limits=1000,seed=None):
'''
- Random Numbers Are Just Random Numbers As It Looks By Its Name,
- Use Seed For Controlling their Randomness,
- `Limits` Defines The Range.
'''
while True:
if seed is not None:
random.seed(seed)
breh = random.randint(0,10**4)
yield breh
def looknsay(starting_point="1",inverse=None):
'''
- To generate a member of the sequence from the previous member, read off the digits of the previous member,
counting the number of digits in groups of the same digit. For example:
- 1 is read off as "one 1" or 11.
- 11 is read off as "two 1s" or 21.
- 21 is read off as "one 2, then one 1" or 1211.
- 1211 is read off as "one 1, one 2, then two 1s" or 1112
- The sequence grows indefinitely. In fact, any variant defined by
starting with a different integer seed number will (eventually) also grow indefinitely,
'''
starting_point = str(starting_point)
def count_next(word):
prev= word[0]
count= 1
say = ''
for curr in word[1:]:
if curr == prev:
count += 1
continue
say += str(count) + prev
prev = curr
count = 1
breh = say + str(count) + prev
return breh
recursed_val = count_next(starting_point)
if recursed_val == "11":
yield "1"
yield recursed_val
yield from looknsay(recursed_val) | en | 0.924649 | this is the doc string of this model i'll just write it someday just yeah thats all -It generates composite numbers which are just opposite of prime numbers,, it means real numbers that aren't a prime number is a composite number - A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11). - Prime numbers are very useful in cryptography Prime numbers are considered as the most exciting numbers among the math lovers.. This function generates odd sequence An odd number is a number which is not divisible by 2. - even_seq generates infinite sequence of even numbers -A number which is divisible by 2 and generates a remainder of 0 is called an even number. - In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. - The Following Formula is "fn = fn-1 + fn-2 ". - Fibonacci is really a mysterious sequence ! - xibonacci isn't a real sequence rather it's just a method that generates a sequence of number such that each term from the "x" onward is the sum of previous "x" terms. similar as fibonacci that sums previous "x" terms. -xibonacci usually requires one positional arguments that is the value of "x". - possible sequences that could be generated through this method: - fibonacci - tribonacci - tetrabonacci - hexabonacci And so on ... to the infinity ! - The Lucas sequence has the same recursive relationship as the "Fibonacci" sequence, where each term is the sum of the two previous terms, but with different starting values - This produces a sequence where the ratios of successive terms approach the golden ratio, and in fact the terms themselves are roundings("round()") of integer powers of the golden ratio. - `x` and `y` are the constant starting_point for `Lucas Sequence`. - In combinatorial mathematics,the Catalan numbers form a sequence of natural numbers that occur in various counting problems,often involving recursively defined objects. - Follows "n = 1/(n+1)(2n*n)" -This Algorithm was taked from OEIS and the author is <NAME>.. - A pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). - Details: * https://en.wikipedia.org/wiki/Pronic_number * https://oeis.org/A002378 - Random Numbers Are Just Random Numbers As It Looks By Its Name, - Use Seed For Controlling their Randomness, - `Limits` Defines The Range. - To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example: - 1 is read off as "one 1" or 11. - 11 is read off as "two 1s" or 21. - 21 is read off as "one 2, then one 1" or 1211. - 1211 is read off as "one 1, one 2, then two 1s" or 1112 - The sequence grows indefinitely. In fact, any variant defined by starting with a different integer seed number will (eventually) also grow indefinitely, | 4.344954 | 4 |
bin/pymccelib.py | newbooks/Develop-MCCE | 0 | 6620362 | <filename>bin/pymccelib.py
#!/usr/bin/env python
import logging
import os
import glob
from geometry import *
ROOMT = 298.15
PH2KCAL = 1.364
KCAL2KT = 1.688
KJ2KCAL = 0.239
DEFAULT_RAD = 1.5 # for dielectric boundary
AMINO_ACIDS = ["ALA", "ARG", "ASN", "ASP", "CYS", "CYL", "GLN", "GLY", "GLU", "HIS", "HIL", "ILE", "LEU", "LYS",
"MET", "PHE", "PRO", "THR", "TRP", "TYR", "VAL"]
class Env:
def __init__(self):
# Hard coded values
self.runprm = "run.prm"
self.version = "PyMCCE 1.0"
self.fn_conflist1 = "head1.lst"
self.fn_step1_out = "step1_out.pdb"
self.fn_conflist2 = "head2.lst"
self.fn_step2_out = "step2_out.pdb"
self.fn_conflist3 = "head3.lst"
self.energy_dir = "energies"
self.ftpldir = ""
self.prm = {}
self.tpl = {}
self.atomnames = {} # atom names indexed by conformer name
return
def init(self):
logging.info("Step 0. Initialize MCCE run environment.")
# load run.prm
self.prm = self.load_runprm()
self.prm_default()
# load ftpl files
self.ftpldir = self.prm["TPL_FOLDER"]
self.load_ftpldir()
# load extra.ftpl
if "EXTRA" in self.prm and os.path.isfile(self.prm["EXTRA"]):
self.load_ftpl(self.prm["EXTRA"])
# revise self.atomnames to include empty conformer types
for res_conflist in [x for x in self.tpl.keys() if x[0] == "CONFLIST"]:
for conf in [x.strip() for x in self.tpl[res_conflist].strip().split(",")]:
if conf not in self.atomnames:
self.atomnames[conf] = []
logging.info("Step 0. Done.\n")
return
def load_runprm(self):
# All values are stripped string
prm = {}
path = os.path.abspath(self.runprm)
logging.info(" Loading run parameter from %s" % path)
lines = open(self.runprm).readlines()
# Sample line: "t include step 1: pre-run, pdb-> mcce pdb (DO_PREMCCE)"
for line in lines:
line = line.strip()
line = line.split("#")[0] # This cuts off everything after #
left_p = line.rfind("(")
right_p = line.rfind(")")
if left_p > 0 and right_p > left_p + 1:
key = line[left_p + 1:right_p]
fields = line[:left_p].split()
if len(fields) >= 1:
prm[key] = fields[0]
return prm
def print_runprm(self):
for key in self.prm.keys():
print("%-25s:%s" % (key, self.prm[key]))
return
def load_ftpl(self, file):
"""Load a tpl file."""
logging.debug(" Loading from file %s" % file)
lines = open(file).readlines()
for line in lines:
line = line.split("#")[0]
fields = line.split(":")
if len(fields) != 2:
continue
key_string = fields[0].strip()
keys = key_string.split(",")
keys = [x.strip().strip("\"") for x in keys]
keys = [x for x in keys if x]
keys = tuple(keys)
value_string = fields[1].strip()
if keys in self.tpl: # Overwrite
logging.warning(" Value of \"%s\": (%s) is replaced by (%s)" % (",".join(keys), self.tpl[keys],
value_string))
self.tpl[keys] = value_string
# Make an atom list in the natural order of CONNECT record.
if keys[0] == "CONNECT":
atom = keys[1]
conf = keys[2]
if conf in self.atomnames:
self.atomnames[conf].append(atom)
else:
self.atomnames[conf] = [atom]
return
def prm_default(self):
if "TPL_FOLDER" not in self.prm or self.prm["TPL_FOLDER"].upper() == "DEFAULT":
path = str(os.path.dirname(os.path.abspath(__file__)))
tpl_path = 'param'.join(path.rsplit('bin', 1))
self.prm["TPL_FOLDER"] = tpl_path
logging.info(" Default TPL_FOLDER is set to %s" % tpl_path)
if "DELPHI_EXE" not in self.prm or self.prm["DELPHI_EXE"].upper() == "DEFAULT":
path = str(os.path.dirname(os.path.abspath(__file__)))
self.prm["DELPHI_EXE"] = path
logging.info(" Default DELPHI_EXE is set to %s" % path)
if "SCALING_VDW0" not in self.prm or self.prm["SCALING_VDW0"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW0 = 1.0")
self.prm["SCALING_VDW0"] = "1.0"
if "SCALING_VDW1" not in self.prm or self.prm["SCALING_VDW1"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW1 = 1.0")
self.prm["SCALING_VDW1"] = "1.0"
if "SCALING_VDW" not in self.prm or self.prm["SCALING_VDW"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW = 1.0")
self.prm["SCALING_VDW"] = "1.0"
if "SCALING_TORS" not in self.prm or self.prm["SCALING_TORS"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_TORS = 1.0")
self.prm["SCALING_TORS"] = "1.0"
if "SCALING_ELE" not in self.prm or self.prm["SCALING_ELE"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_ELE = 1.0")
self.prm["SCALING_ELE"] = "1.0"
if "SCALING_DSOLV" not in self.prm or self.prm["SCALING_DSOLV"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_DSOLV = 1.0")
self.prm["SCALING_DSOLV"] = "1.0"
return
def print_scaling(self):
"""Print scaling factors."""
# print self.param
print(" Scaling factors:")
print(" VDW0 = %.3f" % self.prm["SCALING_VDW0"])
print(" VDW1 = %.3f" % self.prm["SCALING_VDW1"])
print(" VDW = %.3f" % self.prm["SCALING_VDW"])
print(" TORS = %.3f" % self.prm["SCALING_TORS"])
print(" ELE = %.3f" % self.prm["SCALING_ELE"])
print(" DSOLV = %.3f" % self.prm["SCALING_DSOLV"])
return
def load_ftpldir(self):
cwd = os.getcwd()
os.chdir(self.ftpldir)
files = glob.glob("*.ftpl")
files.sort()
logging.info(" Loading ftpl files from %s" % self.ftpldir)
for fname in files:
self.load_ftpl(fname)
os.chdir(cwd)
return
class Atom:
def __init__(self):
self.icount = 0
self.iconf = 0
self.name = ""
self.confname = ""
self.resname = ""
self.on = False
self.iatom = "0"
self.chainid = ""
self.seqnum = 0
self.icode = "_"
self.xyz=()
self.resid = ()
self.crg = 0.0
self.rad = DEFAULT_RAD
self.history = "__________"
return
def load_nativeline(self, line):
self.name = line[12:16]
self.resname = line[17:20]
self.chainid = line[21]
self.seqnum = int(line[22:26])
if line[26] != " ":
self.icode = line[26]
self.xyz = (float(line[30:38]), float(line[38:46]),float(line[46:54]))
self.resid = (self.resname, self.chainid, self.seqnum, self.icode)
return
def printme(self):
line = "ATOM %5d %4s %3s %c%04d%c%03d%8.3f%8.3f%8.3f%8.3f %8.3f %s\n" % (self.icount, self.name,
self.resname,
self.chainid,
self.seqnum, self.icode, self.iconf, self.xyz[0],
self.xyz[1], self.xyz[2], self.rad, self.crg, self.history)
return line
class Conformer:
def __init__(self):
self.confname = ""
self.resname = ""
self.atoms = []
self.resid = ()
self.history = "__________"
return
class Residue:
def __init__(self, resid):
self.resid = resid
self.resname, self.chainid, self.seqnum, self.icode = resid
conf = Conformer()
conf.history = "BK________"
self.conformers = [conf]
self.flag = "" # flag for ntr, ctr label or other purpose
return
class Protein:
"""Protein structure"""
def __init__(self):
self.residues = []
return
def load_nativepdb(self, pdb):
"""Load native pdb file."""
lines = [x for x in open(pdb).readlines() if x[:6] == "ATOM " or x[:6] == "HETATM"]
atoms = []
for line in lines:
# pdb line
atom = Atom()
atom.load_nativeline(line)
atoms.append(atom)
self.load_atoms_single(atoms)
return
def load_atoms_single(self, atoms):
resids = []
self.residues = []
for atom in atoms:
try:
ires = resids.index(atom.resid)
except ValueError: # new residue
self.residues.append(Residue(atom.resid))
resids.append(atom.resid)
ires = len(self.residues) - 1
# load atoms into conformer 0
self.residues[ires].conformers[0].atoms.append(atom)
# separate side chain atoms from backbone - BK atoms remain in conformer 0, the rest go to conformer 1
for res in self.residues:
conflist = [x.strip() for x in env.tpl[("CONFLIST", res.resname)].strip().split(",")]
if res.conformers:
new_conf0 = []
for atom in res.conformers[0].atoms:
# find the first conformer type this atom fits
for conftype in conflist:
if atom.name in env.atomnames[conftype]:
if conftype[-2:] == "BK": # stays in this conformer, break search conf, next atom
new_conf0.append(atom)
else:
if len(res.conformers) > 1:
res.conformers[1].atoms.append(atom)
else:
conf = Conformer()
conf.history = "%2s________" % (conftype[-2:]) # last two characters
res.conformers.append(conf)
res.conformers[1].confname = conftype
res.conformers[1].resname = res.resname
res.conformers[1].atoms.append(atom)
break # do not search other conformers
res.conformers[0].atoms = new_conf0
# delete atoms don't belong to conformer 1
for res in self.residues:
if len(res.conformers) > 1:
confname = res.conformers[1].confname
valid_atoms = env.atomnames[confname]
conf1_atoms = []
for atom in res.conformers[1].atoms:
if atom.name in valid_atoms:
conf1_atoms.append(atom)
else:
logging.WARNING(" Deleted atom \"%s\" of %s because it doesn't fit into initial conformer." % (
atom.name, res.resname))
return
def pdblines(self):
lines = []
icount = 1
for res in self.residues:
conflist = env.tpl[("CONFLIST", res.resname)]
#logging.debug(conflist)
iconf = 0
for conf in res.conformers:
for atom in conf.atoms:
atom.icount = icount
atom.iconf = iconf
atom.history = conf.history
line = atom.printme()
lines.append(line)
icount += 1
iconf += 1
return lines
def identify_nc(self):
# The first and last amino acid in a chain, and no extra bonded atom from other residues in the same chain
clash_distance = float(env.prm["CLASH_DISTANCE"])
clash_distance2 = clash_distance * clash_distance
confnames = [x.strip() for x in env.tpl[("CONFLIST", "NTR")].split(",")]
NTR_atomnames = set()
for conf in confnames:
NTR_atomnames = NTR_atomnames | set(env.atomnames[conf])
confnames = [x.strip() for x in env.tpl[("CONFLIST", "CTR")].split(",")]
CTR_atomnames = set()
for conf in confnames:
CTR_atomnames = CTR_atomnames | set(env.atomnames[conf])
chains = []
# count chains
for res in self.residues:
if res.chainid not in chains:
chains.append(res.chainid)
for chainid in chains:
# get all residues of this chain
aminoacids_in_chain = []
others_in_chain = []
for res in self.residues:
if res.chainid == chainid:
if res.resname in AMINO_ACIDS:
aminoacids_in_chain.append(res)
else:
others_in_chain.append(res)
if aminoacids_in_chain:
ntr = aminoacids_in_chain[0]
ctr = aminoacids_in_chain[0]
else:
continue
for res in aminoacids_in_chain[1:]:
if res.seqnum < ntr.seqnum:
ntr = res.resid[0]
elif res.seqnum > ctr.seqnum:
ctr = res
# verify bond for NTR
atom_N =None
for atom in ntr.conformers[0].atoms:
if atom.name == " N ":
atom_N = atom
break
if not atom_N:
logging.critical("No N atom found for NTR residue")
return False
ntr.flag = "ntr"
for res in others_in_chain:
if not ntr.flag:
break
for conf in res.conformers:
if not ntr.flag:
break
for atom2 in conf.atoms:
d2 = d2vv(atom2.xyz, atom_N.xyz)
if d2 < clash_distance2:
ntr.flag = ""
break
# verify bond for CTR
atom_C =None
for atom in ntr.conformers[0].atoms:
if atom.name == " C ":
atom_C = atom
break
if not atom_C:
logging.critical("No C atom found for CTR residue")
return False
ctr.flag = "ctr"
for res in others_in_chain:
if not ctr.flag:
break
for conf in res.conformers:
if not ctr.flag:
break
for atom2 in conf.atoms:
d2 = d2vv(atom2.xyz, atom_C.xyz)
if d2 < clash_distance2:
ctr.flag = ""
break
new_atoms = []
for res in self.residues:
for conf in res.conformers:
for atom in conf.atoms:
if res.flag == "ntr" and atom.name in NTR_atomnames:
atom.resname = "NTR"
atom.resid = ("NTR", res.resid[1], res.resid[2], res.resid[3])
elif res.flag == "ctr" and atom.name in CTR_atomnames:
atom.resname = "CTR"
atom.resid = ("CTR", res.resid[1], res.resid[2], res.resid[3])
new_atoms.append(atom)
self.load_atoms_single(new_atoms)
return True
env = Env()
| <filename>bin/pymccelib.py
#!/usr/bin/env python
import logging
import os
import glob
from geometry import *
ROOMT = 298.15
PH2KCAL = 1.364
KCAL2KT = 1.688
KJ2KCAL = 0.239
DEFAULT_RAD = 1.5 # for dielectric boundary
AMINO_ACIDS = ["ALA", "ARG", "ASN", "ASP", "CYS", "CYL", "GLN", "GLY", "GLU", "HIS", "HIL", "ILE", "LEU", "LYS",
"MET", "PHE", "PRO", "THR", "TRP", "TYR", "VAL"]
class Env:
def __init__(self):
# Hard coded values
self.runprm = "run.prm"
self.version = "PyMCCE 1.0"
self.fn_conflist1 = "head1.lst"
self.fn_step1_out = "step1_out.pdb"
self.fn_conflist2 = "head2.lst"
self.fn_step2_out = "step2_out.pdb"
self.fn_conflist3 = "head3.lst"
self.energy_dir = "energies"
self.ftpldir = ""
self.prm = {}
self.tpl = {}
self.atomnames = {} # atom names indexed by conformer name
return
def init(self):
logging.info("Step 0. Initialize MCCE run environment.")
# load run.prm
self.prm = self.load_runprm()
self.prm_default()
# load ftpl files
self.ftpldir = self.prm["TPL_FOLDER"]
self.load_ftpldir()
# load extra.ftpl
if "EXTRA" in self.prm and os.path.isfile(self.prm["EXTRA"]):
self.load_ftpl(self.prm["EXTRA"])
# revise self.atomnames to include empty conformer types
for res_conflist in [x for x in self.tpl.keys() if x[0] == "CONFLIST"]:
for conf in [x.strip() for x in self.tpl[res_conflist].strip().split(",")]:
if conf not in self.atomnames:
self.atomnames[conf] = []
logging.info("Step 0. Done.\n")
return
def load_runprm(self):
# All values are stripped string
prm = {}
path = os.path.abspath(self.runprm)
logging.info(" Loading run parameter from %s" % path)
lines = open(self.runprm).readlines()
# Sample line: "t include step 1: pre-run, pdb-> mcce pdb (DO_PREMCCE)"
for line in lines:
line = line.strip()
line = line.split("#")[0] # This cuts off everything after #
left_p = line.rfind("(")
right_p = line.rfind(")")
if left_p > 0 and right_p > left_p + 1:
key = line[left_p + 1:right_p]
fields = line[:left_p].split()
if len(fields) >= 1:
prm[key] = fields[0]
return prm
def print_runprm(self):
for key in self.prm.keys():
print("%-25s:%s" % (key, self.prm[key]))
return
def load_ftpl(self, file):
"""Load a tpl file."""
logging.debug(" Loading from file %s" % file)
lines = open(file).readlines()
for line in lines:
line = line.split("#")[0]
fields = line.split(":")
if len(fields) != 2:
continue
key_string = fields[0].strip()
keys = key_string.split(",")
keys = [x.strip().strip("\"") for x in keys]
keys = [x for x in keys if x]
keys = tuple(keys)
value_string = fields[1].strip()
if keys in self.tpl: # Overwrite
logging.warning(" Value of \"%s\": (%s) is replaced by (%s)" % (",".join(keys), self.tpl[keys],
value_string))
self.tpl[keys] = value_string
# Make an atom list in the natural order of CONNECT record.
if keys[0] == "CONNECT":
atom = keys[1]
conf = keys[2]
if conf in self.atomnames:
self.atomnames[conf].append(atom)
else:
self.atomnames[conf] = [atom]
return
def prm_default(self):
if "TPL_FOLDER" not in self.prm or self.prm["TPL_FOLDER"].upper() == "DEFAULT":
path = str(os.path.dirname(os.path.abspath(__file__)))
tpl_path = 'param'.join(path.rsplit('bin', 1))
self.prm["TPL_FOLDER"] = tpl_path
logging.info(" Default TPL_FOLDER is set to %s" % tpl_path)
if "DELPHI_EXE" not in self.prm or self.prm["DELPHI_EXE"].upper() == "DEFAULT":
path = str(os.path.dirname(os.path.abspath(__file__)))
self.prm["DELPHI_EXE"] = path
logging.info(" Default DELPHI_EXE is set to %s" % path)
if "SCALING_VDW0" not in self.prm or self.prm["SCALING_VDW0"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW0 = 1.0")
self.prm["SCALING_VDW0"] = "1.0"
if "SCALING_VDW1" not in self.prm or self.prm["SCALING_VDW1"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW1 = 1.0")
self.prm["SCALING_VDW1"] = "1.0"
if "SCALING_VDW" not in self.prm or self.prm["SCALING_VDW"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_VDW = 1.0")
self.prm["SCALING_VDW"] = "1.0"
if "SCALING_TORS" not in self.prm or self.prm["SCALING_TORS"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_TORS = 1.0")
self.prm["SCALING_TORS"] = "1.0"
if "SCALING_ELE" not in self.prm or self.prm["SCALING_ELE"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_ELE = 1.0")
self.prm["SCALING_ELE"] = "1.0"
if "SCALING_DSOLV" not in self.prm or self.prm["SCALING_DSOLV"].upper() == "DEFAULT":
logging.info(" Set to default: SCALING_DSOLV = 1.0")
self.prm["SCALING_DSOLV"] = "1.0"
return
def print_scaling(self):
"""Print scaling factors."""
# print self.param
print(" Scaling factors:")
print(" VDW0 = %.3f" % self.prm["SCALING_VDW0"])
print(" VDW1 = %.3f" % self.prm["SCALING_VDW1"])
print(" VDW = %.3f" % self.prm["SCALING_VDW"])
print(" TORS = %.3f" % self.prm["SCALING_TORS"])
print(" ELE = %.3f" % self.prm["SCALING_ELE"])
print(" DSOLV = %.3f" % self.prm["SCALING_DSOLV"])
return
def load_ftpldir(self):
cwd = os.getcwd()
os.chdir(self.ftpldir)
files = glob.glob("*.ftpl")
files.sort()
logging.info(" Loading ftpl files from %s" % self.ftpldir)
for fname in files:
self.load_ftpl(fname)
os.chdir(cwd)
return
class Atom:
def __init__(self):
self.icount = 0
self.iconf = 0
self.name = ""
self.confname = ""
self.resname = ""
self.on = False
self.iatom = "0"
self.chainid = ""
self.seqnum = 0
self.icode = "_"
self.xyz=()
self.resid = ()
self.crg = 0.0
self.rad = DEFAULT_RAD
self.history = "__________"
return
def load_nativeline(self, line):
self.name = line[12:16]
self.resname = line[17:20]
self.chainid = line[21]
self.seqnum = int(line[22:26])
if line[26] != " ":
self.icode = line[26]
self.xyz = (float(line[30:38]), float(line[38:46]),float(line[46:54]))
self.resid = (self.resname, self.chainid, self.seqnum, self.icode)
return
def printme(self):
line = "ATOM %5d %4s %3s %c%04d%c%03d%8.3f%8.3f%8.3f%8.3f %8.3f %s\n" % (self.icount, self.name,
self.resname,
self.chainid,
self.seqnum, self.icode, self.iconf, self.xyz[0],
self.xyz[1], self.xyz[2], self.rad, self.crg, self.history)
return line
class Conformer:
def __init__(self):
self.confname = ""
self.resname = ""
self.atoms = []
self.resid = ()
self.history = "__________"
return
class Residue:
def __init__(self, resid):
self.resid = resid
self.resname, self.chainid, self.seqnum, self.icode = resid
conf = Conformer()
conf.history = "BK________"
self.conformers = [conf]
self.flag = "" # flag for ntr, ctr label or other purpose
return
class Protein:
"""Protein structure"""
def __init__(self):
self.residues = []
return
def load_nativepdb(self, pdb):
"""Load native pdb file."""
lines = [x for x in open(pdb).readlines() if x[:6] == "ATOM " or x[:6] == "HETATM"]
atoms = []
for line in lines:
# pdb line
atom = Atom()
atom.load_nativeline(line)
atoms.append(atom)
self.load_atoms_single(atoms)
return
def load_atoms_single(self, atoms):
resids = []
self.residues = []
for atom in atoms:
try:
ires = resids.index(atom.resid)
except ValueError: # new residue
self.residues.append(Residue(atom.resid))
resids.append(atom.resid)
ires = len(self.residues) - 1
# load atoms into conformer 0
self.residues[ires].conformers[0].atoms.append(atom)
# separate side chain atoms from backbone - BK atoms remain in conformer 0, the rest go to conformer 1
for res in self.residues:
conflist = [x.strip() for x in env.tpl[("CONFLIST", res.resname)].strip().split(",")]
if res.conformers:
new_conf0 = []
for atom in res.conformers[0].atoms:
# find the first conformer type this atom fits
for conftype in conflist:
if atom.name in env.atomnames[conftype]:
if conftype[-2:] == "BK": # stays in this conformer, break search conf, next atom
new_conf0.append(atom)
else:
if len(res.conformers) > 1:
res.conformers[1].atoms.append(atom)
else:
conf = Conformer()
conf.history = "%2s________" % (conftype[-2:]) # last two characters
res.conformers.append(conf)
res.conformers[1].confname = conftype
res.conformers[1].resname = res.resname
res.conformers[1].atoms.append(atom)
break # do not search other conformers
res.conformers[0].atoms = new_conf0
# delete atoms don't belong to conformer 1
for res in self.residues:
if len(res.conformers) > 1:
confname = res.conformers[1].confname
valid_atoms = env.atomnames[confname]
conf1_atoms = []
for atom in res.conformers[1].atoms:
if atom.name in valid_atoms:
conf1_atoms.append(atom)
else:
logging.WARNING(" Deleted atom \"%s\" of %s because it doesn't fit into initial conformer." % (
atom.name, res.resname))
return
def pdblines(self):
lines = []
icount = 1
for res in self.residues:
conflist = env.tpl[("CONFLIST", res.resname)]
#logging.debug(conflist)
iconf = 0
for conf in res.conformers:
for atom in conf.atoms:
atom.icount = icount
atom.iconf = iconf
atom.history = conf.history
line = atom.printme()
lines.append(line)
icount += 1
iconf += 1
return lines
def identify_nc(self):
# The first and last amino acid in a chain, and no extra bonded atom from other residues in the same chain
clash_distance = float(env.prm["CLASH_DISTANCE"])
clash_distance2 = clash_distance * clash_distance
confnames = [x.strip() for x in env.tpl[("CONFLIST", "NTR")].split(",")]
NTR_atomnames = set()
for conf in confnames:
NTR_atomnames = NTR_atomnames | set(env.atomnames[conf])
confnames = [x.strip() for x in env.tpl[("CONFLIST", "CTR")].split(",")]
CTR_atomnames = set()
for conf in confnames:
CTR_atomnames = CTR_atomnames | set(env.atomnames[conf])
chains = []
# count chains
for res in self.residues:
if res.chainid not in chains:
chains.append(res.chainid)
for chainid in chains:
# get all residues of this chain
aminoacids_in_chain = []
others_in_chain = []
for res in self.residues:
if res.chainid == chainid:
if res.resname in AMINO_ACIDS:
aminoacids_in_chain.append(res)
else:
others_in_chain.append(res)
if aminoacids_in_chain:
ntr = aminoacids_in_chain[0]
ctr = aminoacids_in_chain[0]
else:
continue
for res in aminoacids_in_chain[1:]:
if res.seqnum < ntr.seqnum:
ntr = res.resid[0]
elif res.seqnum > ctr.seqnum:
ctr = res
# verify bond for NTR
atom_N =None
for atom in ntr.conformers[0].atoms:
if atom.name == " N ":
atom_N = atom
break
if not atom_N:
logging.critical("No N atom found for NTR residue")
return False
ntr.flag = "ntr"
for res in others_in_chain:
if not ntr.flag:
break
for conf in res.conformers:
if not ntr.flag:
break
for atom2 in conf.atoms:
d2 = d2vv(atom2.xyz, atom_N.xyz)
if d2 < clash_distance2:
ntr.flag = ""
break
# verify bond for CTR
atom_C =None
for atom in ntr.conformers[0].atoms:
if atom.name == " C ":
atom_C = atom
break
if not atom_C:
logging.critical("No C atom found for CTR residue")
return False
ctr.flag = "ctr"
for res in others_in_chain:
if not ctr.flag:
break
for conf in res.conformers:
if not ctr.flag:
break
for atom2 in conf.atoms:
d2 = d2vv(atom2.xyz, atom_C.xyz)
if d2 < clash_distance2:
ctr.flag = ""
break
new_atoms = []
for res in self.residues:
for conf in res.conformers:
for atom in conf.atoms:
if res.flag == "ntr" and atom.name in NTR_atomnames:
atom.resname = "NTR"
atom.resid = ("NTR", res.resid[1], res.resid[2], res.resid[3])
elif res.flag == "ctr" and atom.name in CTR_atomnames:
atom.resname = "CTR"
atom.resid = ("CTR", res.resid[1], res.resid[2], res.resid[3])
new_atoms.append(atom)
self.load_atoms_single(new_atoms)
return True
env = Env()
| en | 0.744292 | #!/usr/bin/env python # for dielectric boundary # Hard coded values # atom names indexed by conformer name # load run.prm # load ftpl files # load extra.ftpl # revise self.atomnames to include empty conformer types # All values are stripped string # Sample line: "t include step 1: pre-run, pdb-> mcce pdb (DO_PREMCCE)" # This cuts off everything after # Load a tpl file. # Overwrite # Make an atom list in the natural order of CONNECT record. Print scaling factors. # print self.param # flag for ntr, ctr label or other purpose Protein structure Load native pdb file. # pdb line # new residue # load atoms into conformer 0 # separate side chain atoms from backbone - BK atoms remain in conformer 0, the rest go to conformer 1 # find the first conformer type this atom fits # stays in this conformer, break search conf, next atom # last two characters # do not search other conformers # delete atoms don't belong to conformer 1 #logging.debug(conflist) # The first and last amino acid in a chain, and no extra bonded atom from other residues in the same chain # count chains # get all residues of this chain # verify bond for NTR # verify bond for CTR | 2.200006 | 2 |
plugins/datadog/komand_datadog/actions/__init__.py | lukaszlaszuk/insightconnect-plugins | 46 | 6620363 | <reponame>lukaszlaszuk/insightconnect-plugins<filename>plugins/datadog/komand_datadog/actions/__init__.py
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .post_event.action import PostEvent
from .post_metrics.action import PostMetrics
| # GENERATED BY KOMAND SDK - DO NOT EDIT
from .post_event.action import PostEvent
from .post_metrics.action import PostMetrics | en | 0.703588 | # GENERATED BY KOMAND SDK - DO NOT EDIT | 1.015153 | 1 |
LeetCode/weekly-contest-166-2019.12.12/groupThePeople_1282.py | Max-PJB/python-learning2 | 0 | 6620364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2019/12/12 17:05
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
-------------------------------------------------
Description : 用户分组 Group the People Given the Group Size They Belong To
https://leetcode-cn.com/contest/weekly-contest-166/problems/group-the-people-given-the-group-size-they-belong-to/
-------------------------------------------------
"""
import time
from typing import List
# list_to_tree 我自己写的一个 list 转 root 的方法
from LeetCode.leetcode_utils.leetcode_list2tree import list_to_tree, TreeNode
__author__ = 'Max_Pengjb'
start_time = time.time()
# 下面写上代码块
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
from collections import defaultdict
k_dict = defaultdict(list)
for i, k in enumerate(groupSizes):
k_dict[k].append(i)
res = []
for k, index_list in k_dict.items():
for j in range(0, len(index_list), k):
res.append(index_list[j:j + k])
return res
inin = [3, 3, 3, 3, 3, 1, 3]
rr = Solution().groupThePeople(inin)
print(rr)
# 上面中间写上代码块
end_time = time.time()
print('Running time: %s Seconds' % (end_time - start_time))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2019/12/12 17:05
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
-------------------------------------------------
Description : 用户分组 Group the People Given the Group Size They Belong To
https://leetcode-cn.com/contest/weekly-contest-166/problems/group-the-people-given-the-group-size-they-belong-to/
-------------------------------------------------
"""
import time
from typing import List
# list_to_tree 我自己写的一个 list 转 root 的方法
from LeetCode.leetcode_utils.leetcode_list2tree import list_to_tree, TreeNode
__author__ = 'Max_Pengjb'
start_time = time.time()
# 下面写上代码块
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
from collections import defaultdict
k_dict = defaultdict(list)
for i, k in enumerate(groupSizes):
k_dict[k].append(i)
res = []
for k, index_list in k_dict.items():
for j in range(0, len(index_list), k):
res.append(index_list[j:j + k])
return res
inin = [3, 3, 3, 3, 3, 1, 3]
rr = Solution().groupThePeople(inin)
print(rr)
# 上面中间写上代码块
end_time = time.time()
print('Running time: %s Seconds' % (end_time - start_time))
| en | 0.331483 | #!/usr/bin/env python # -*- coding: utf-8 -*- ------------------------------------------------- @ Author : pengj @ date : 2019/12/12 17:05 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : <EMAIL> ------------------------------------------------- Description : 用户分组 Group the People Given the Group Size They Belong To https://leetcode-cn.com/contest/weekly-contest-166/problems/group-the-people-given-the-group-size-they-belong-to/ ------------------------------------------------- # list_to_tree 我自己写的一个 list 转 root 的方法 # 下面写上代码块 # 上面中间写上代码块 | 3.690591 | 4 |
thesis_plots.py | elcymon/inference-analysis | 0 | 6620365 | <filename>thesis_plots.py
import pandas as pd
from zipfile import ZipFile
import re
from io import StringIO
import ntpath
import cv2 as cv
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
from glob import glob
def getPointAngle(pt,centre,degrees=True):
angle = np.arctan2(pt[1] - centre[1], pt[0] - centre[0])
if degrees:
return 180 * angle / np.pi
return angle
# Function to find the circle on
# which the given three points lie
def findCircle(x1, y1, x2, y2, x3, y3) :
x12 = x1 - x2
x13 = x1 - x3
y12 = y1 - y2
y13 = y1 - y3
y31 = y3 - y1
y21 = y2 - y1
x31 = x3 - x1
x21 = x2 - x1
# x1^2 - x3^2
sx13 = pow(x1, 2) - pow(x3, 2)
# y1^2 - y3^2
sy13 = pow(y1, 2) - pow(y3, 2)
sx21 = pow(x2, 2) - pow(x1, 2)
sy21 = pow(y2, 2) - pow(y1, 2)
f = (((sx13) * (x12) + (sy13) *
(x12) + (sx21) * (x13) +
(sy21) * (x13)) // (2 *
((y31) * (x12) - (y21) * (x13))))
g = (((sx13) * (y12) + (sy13) * (y12) +
(sx21) * (y13) + (sy21) * (y13)) //
(2 * ((x31) * (y12) - (x21) * (y13))))
c = (-pow(x1, 2) - pow(y1, 2) -
2 * g * x1 - 2 * f * y1)
# eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0
# where centre is (h = -g, k = -f) and
# radius r as r^2 = h^2 + k^2 - c
h = -g
k = -f
sqr_of_r = h * h + k * k - c
# r is the radius
r = round(sqrt(sqr_of_r), 5)
pt1_angle = getPointAngle((x1,y1),(h,k))
pt2_angle = getPointAngle((x3,y3),(h,k))
return (round(h),round(k)),round(r),pt1_angle,pt2_angle
def shortenNetworkName(name):
if '608' in name:
return 'YOLOv3'
elif '128' in name:
return 'tYOLOv3-128'
elif '224' in name:
return 'tYOLOv3-224'
elif '124' in name:
return 'mSSD-124'
elif '220' in name:
return 'mSSD-220'
def drawBoxes(boxesDF,frame):
for box in boxesDF.index:
color = (255,0,0)
x1,y1,x2,y2 = boxesDF.loc[box,['x1','y1','x2','y2']]
if 'info' in boxesDF.columns:
if 'FP' in boxesDF.loc[box,'info'] or \
'FN' in boxesDF.loc[box,'info'] or \
'TP' in boxesDF.loc[box,'info']:#none ground truth data
if 'FP' in boxesDF.loc[box,'info'] and 'new' in boxesDF.loc[box,'info']:
color = (0,0,255)
elif 'FN' in boxesDF.loc[box,'info']:
color = (255,0,255)
elif 'TP' in boxesDF.loc[box,'info']:
color = (255,0,0)
else:
continue
else:
if 'inter' in boxesDF.loc[box,'info']:
color = (0,0,255)
elif 'new' in boxesDF.loc[box,'info']:
color= (255,0,255)
# insert text information
frame = cv.putText(frame, boxesDF.loc[box,'id'], (x2,y1), \
cv.FONT_HERSHEY_PLAIN, 1, color, 2, cv.LINE_8, False)
cv.rectangle(img=frame,pt1=(x1,y1),pt2=(x2,y2),
color=color,thickness=2)
return frame
def maskFrame(frame,horizon):
center,radius,start_angle,end_angle = findCircle(*horizon)
start_angle = 0; end_angle = 360
axes = (radius,radius)
angle = 0
color = (255,255,255)
thickness = -1
lineType = cv.LINE_AA
shift = 0
ellipse_mask = np.zeros_like(cv.cvtColor(frame,cv.COLOR_BGR2GRAY))
ellipse_mask = cv.ellipse(ellipse_mask,center,axes,angle,start_angle,end_angle,color,thickness,lineType,shift)
_,horizon_mask = cv.threshold(ellipse_mask,1,255,cv.THRESH_BINARY)
newframe = cv.bitwise_and(frame,frame,mask = horizon_mask)
return newframe
def saveFrame(frame,masked,name):
while True:
key = cv.waitKey(1)
if key == ord('s'):
cv.imwrite('../thesis_detection_figs/' + name + '.jpg',frame)
cv.imwrite('../thesis_detection_figs/' + name + '-horizon.jpg',masked)
break
elif key == ord('p'):
break
def raw_detection_video(videoname,networkname,horizon,size=(640,360)):
video = cv.VideoCapture('../data/mp4/' + videoname + '.MP4')
frameNo = 1
zipfile = ZipFile('../data/' + networkname + '.zip')
ntwkname = shortenNetworkName(networkname)
while video.isOpened():
_,frame = video.read()
if frame is None:
print('frame is none')
break
print(frameNo)
frame = cv.resize(frame,size)
if '608' in networkname:
header = ['class','x1','y1','x2','y2']
else:
header = ['class','confidence','x1','y1','x2','y2']
filename = "{0}/1r1c/{1}-{2:05d}.txt".format(networkname,videoname,frameNo)
df = pd.read_csv(zipfile.open(filename),sep=' ',names = header)
#resize df data
if df.shape[0] > 0:
df.loc[:,['x1','x2']] = df.loc[:,['x1','x2']] * 640./960.
df.loc[:,['y1','y2']] = df.loc[:,['y1','y2']] * 360./540.
df.loc[:,['x1','y1','x2','y2']] = df.loc[:,['x1','y1','x2','y2']].astype(int)
frame = drawBoxes(df,frame)
masked = maskFrame(frame,np.round(horizon * 2/3.).astype(np.int))
cv.imshow(ntpath.basename(videoname) + '-masked',masked)
cv.imshow(ntpath.basename(videoname),frame)
key = cv.waitKey(1)
if key == ord('q'):
break
if key == ord('p') or frameNo == 306:
# cv.waitKey(0)
saveFrame(frame,masked,'{}-{}-{:05d}'.format(ntwkname, ntpath.basename(videoname),frameNo) )
frameNo += 1
def detections_from_model_data(videoname,networkname,horizon,size=(640,360)):
video = cv.VideoCapture('../data/mp4/' + videoname + '.MP4')
ntwkname = shortenNetworkName(networkname)
csvfile = '../data/model_data/{}/{}/'.format(videoname,networkname)
if '608' in networkname:
csvfile += '{}-{}-GT-pruned.csv'.format(videoname,networkname)
else:
csvfile += '{}-{}-detection.csv'.format(videoname,networkname)
df = pd.read_csv(csvfile,header=[0,1],index_col=0,low_memory=False)
print(df.shape)
frameNo = 1
mask = None
pause = False
while video.isOpened():
_,frame = video.read()
if frame is None:
print('frame is none')
break
frame = cv.resize(frame,size)
masked = maskFrame(frame,np.round(horizon * 2/3.).astype(np.int))
if frameNo in df.index:
rowseries = df.loc[frameNo,:].dropna()
litters = rowseries.index.get_level_values(0).unique()
if len(litters) > 0:
rowdf = rowseries.unstack(level=1)
rowdf.loc[:,['x1','x2','y1','y2']] = rowdf.loc[:,['x1','x2','y1','y2']].mul(2./3.).astype(int)
frame = drawBoxes(rowdf,frame)
masked = drawBoxes(rowdf,masked)
# print(rowdf['info'],rowdf['info'].str.contains('new'))
if rowdf['info'].str.contains('new').any() and \
rowdf['info'].str.contains('inter').any() and \
rowdf['info'].str.contains('iou').any():
pause = True
print(frameNo,len(litters))
cv.imshow(ntpath.basename(videoname) + '-masked',masked)
cv.imshow(ntpath.basename(videoname),frame)
key = cv.waitKey(1)
if key == ord('q'):
break
if key == ord('p') or pause or frameNo == 306:
# cv.waitKey(0)
saveFrame(frame,masked,'{}-{}-{:05d}-info'.format(ntwkname, ntpath.basename(videoname),frameNo) )
pause = False
frameNo += 1
def bbox_path(resultspath,outputpath,networks,filterby=None):
if filterby is not None:
filterbyDF = pd.read_csv(filterby,header=[0,1],index_col=[0,1])
# cmap = plt.get_cmap('inferno')
for ntwk in networks:
print(ntwk)
fig = plt.figure(figsize=(16,9))
ax = fig.gca()
ax.invert_yaxis()
ax.set_ylim([0,540])
ax.set_xlim([0,960])
ax.set_xticks([])
ax.set_yticks([])
for csvfile in glob(resultspath + '/*/*/*' + ntwk + '-detection.csv'):
video = ntpath.basename(ntpath.dirname(ntpath.dirname(csvfile)))
print(video)
csvDF = pd.read_csv(csvfile,header=[0,1],index_col=0,low_memory=False)
if filterby is not None:
if video in filterbyDF.index.get_level_values(0).unique():
litters = filterbyDF.loc[video,:].index
csvDF = csvDF.loc[:,litters]
else:
continue
else:
litters = []
for lit in csvDF.columns.get_level_values(0).unique():
bbox = csvDF[lit].dropna(axis=0,how='all') #drop nan rows
bbox.loc[:,'cx'] = ((bbox['x1'] + bbox['x2'])/2.0).astype(int)
bbox.loc[:,'cy'] = ((bbox['y1'] + bbox['y2'])/2.0).astype(int)
alpha = 0.2
marker = '.'
markerfacecolor='none'
markersize=4
if bbox['info'].str.contains('inter').any():
ax.plot(bbox.loc[bbox['info'] == 'inter','cx'],
bbox.loc[bbox['info'] == 'inter','cy'],color='r',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=2)
if bbox['info'].str.contains('iou').any():
ax.plot(bbox.loc[bbox['info'] == 'iou','cx'],
bbox.loc[bbox['info'] == 'iou','cy'],color='b',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=1)
if bbox['info'].str.contains('new').any():
ax.plot(bbox.loc[bbox['info'] == 'new','cx'],
bbox.loc[bbox['info'] == 'new','cy'],color='k',marker='.',
markersize=8,alpha=1,linestyle='',zorder=3)
if bbox['info'].str.contains('TP').any():
ax.plot(bbox.loc[bbox['info'] == 'TP','cx'],
bbox.loc[bbox['info'] == 'TP','cy'],color='g',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=2)
if bbox['info'].str.contains('FN').any():
ax.plot(bbox.loc[bbox['info'] == 'FN','cx'],
bbox.loc[bbox['info'] == 'FN','cy'],color='r',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=1)
if '608' in ntwk:
#plot last seen location
ax.plot([bbox['cx'].iloc[-1]],[bbox['cy'].iloc[-1]],
color='g',marker='.',
markersize=8,alpha=1,linestyle='',zorder=3)
plt.show()
fig.savefig(outputpath + '/centre_path_' + ntwk + '.png',bbox_inches='tight')
# break
if __name__ == '__main__':
first_last_appearance = '../data/simplified_data/yolo_608_horizon'
detection_data = '../data/model-data'
video = '20190111GOPR9029-hflip'
networkname = ['yolov3-litter_10000-th0p0-nms0p0-iSz608',
'yolov3-tiny-litter_10000-th0p0-nms0p0-iSz128',
'yolov3-tiny-litter_10000-th0p0-nms0p0-iSz224',
'mobilenetSSD-10000-th0p5-nms0p0-iSz124',
'mobilenetSSD-10000-th0p5-nms0p0-iSz220']
horizon = np.array([18,162,494,59,937,143])
# raw_detection_video(video,networkname[4],horizon)
# detections_from_model_data(video,networkname[2],horizon)
bbox_path('../data/model_data','../thesis_detection_figs',
networkname,filterby='../data/simplified_data/yolo_608_horizon/yolo_608_horizon.csv')
| <filename>thesis_plots.py
import pandas as pd
from zipfile import ZipFile
import re
from io import StringIO
import ntpath
import cv2 as cv
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
from glob import glob
def getPointAngle(pt,centre,degrees=True):
angle = np.arctan2(pt[1] - centre[1], pt[0] - centre[0])
if degrees:
return 180 * angle / np.pi
return angle
# Function to find the circle on
# which the given three points lie
def findCircle(x1, y1, x2, y2, x3, y3) :
x12 = x1 - x2
x13 = x1 - x3
y12 = y1 - y2
y13 = y1 - y3
y31 = y3 - y1
y21 = y2 - y1
x31 = x3 - x1
x21 = x2 - x1
# x1^2 - x3^2
sx13 = pow(x1, 2) - pow(x3, 2)
# y1^2 - y3^2
sy13 = pow(y1, 2) - pow(y3, 2)
sx21 = pow(x2, 2) - pow(x1, 2)
sy21 = pow(y2, 2) - pow(y1, 2)
f = (((sx13) * (x12) + (sy13) *
(x12) + (sx21) * (x13) +
(sy21) * (x13)) // (2 *
((y31) * (x12) - (y21) * (x13))))
g = (((sx13) * (y12) + (sy13) * (y12) +
(sx21) * (y13) + (sy21) * (y13)) //
(2 * ((x31) * (y12) - (x21) * (y13))))
c = (-pow(x1, 2) - pow(y1, 2) -
2 * g * x1 - 2 * f * y1)
# eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0
# where centre is (h = -g, k = -f) and
# radius r as r^2 = h^2 + k^2 - c
h = -g
k = -f
sqr_of_r = h * h + k * k - c
# r is the radius
r = round(sqrt(sqr_of_r), 5)
pt1_angle = getPointAngle((x1,y1),(h,k))
pt2_angle = getPointAngle((x3,y3),(h,k))
return (round(h),round(k)),round(r),pt1_angle,pt2_angle
def shortenNetworkName(name):
if '608' in name:
return 'YOLOv3'
elif '128' in name:
return 'tYOLOv3-128'
elif '224' in name:
return 'tYOLOv3-224'
elif '124' in name:
return 'mSSD-124'
elif '220' in name:
return 'mSSD-220'
def drawBoxes(boxesDF,frame):
for box in boxesDF.index:
color = (255,0,0)
x1,y1,x2,y2 = boxesDF.loc[box,['x1','y1','x2','y2']]
if 'info' in boxesDF.columns:
if 'FP' in boxesDF.loc[box,'info'] or \
'FN' in boxesDF.loc[box,'info'] or \
'TP' in boxesDF.loc[box,'info']:#none ground truth data
if 'FP' in boxesDF.loc[box,'info'] and 'new' in boxesDF.loc[box,'info']:
color = (0,0,255)
elif 'FN' in boxesDF.loc[box,'info']:
color = (255,0,255)
elif 'TP' in boxesDF.loc[box,'info']:
color = (255,0,0)
else:
continue
else:
if 'inter' in boxesDF.loc[box,'info']:
color = (0,0,255)
elif 'new' in boxesDF.loc[box,'info']:
color= (255,0,255)
# insert text information
frame = cv.putText(frame, boxesDF.loc[box,'id'], (x2,y1), \
cv.FONT_HERSHEY_PLAIN, 1, color, 2, cv.LINE_8, False)
cv.rectangle(img=frame,pt1=(x1,y1),pt2=(x2,y2),
color=color,thickness=2)
return frame
def maskFrame(frame,horizon):
center,radius,start_angle,end_angle = findCircle(*horizon)
start_angle = 0; end_angle = 360
axes = (radius,radius)
angle = 0
color = (255,255,255)
thickness = -1
lineType = cv.LINE_AA
shift = 0
ellipse_mask = np.zeros_like(cv.cvtColor(frame,cv.COLOR_BGR2GRAY))
ellipse_mask = cv.ellipse(ellipse_mask,center,axes,angle,start_angle,end_angle,color,thickness,lineType,shift)
_,horizon_mask = cv.threshold(ellipse_mask,1,255,cv.THRESH_BINARY)
newframe = cv.bitwise_and(frame,frame,mask = horizon_mask)
return newframe
def saveFrame(frame,masked,name):
while True:
key = cv.waitKey(1)
if key == ord('s'):
cv.imwrite('../thesis_detection_figs/' + name + '.jpg',frame)
cv.imwrite('../thesis_detection_figs/' + name + '-horizon.jpg',masked)
break
elif key == ord('p'):
break
def raw_detection_video(videoname,networkname,horizon,size=(640,360)):
video = cv.VideoCapture('../data/mp4/' + videoname + '.MP4')
frameNo = 1
zipfile = ZipFile('../data/' + networkname + '.zip')
ntwkname = shortenNetworkName(networkname)
while video.isOpened():
_,frame = video.read()
if frame is None:
print('frame is none')
break
print(frameNo)
frame = cv.resize(frame,size)
if '608' in networkname:
header = ['class','x1','y1','x2','y2']
else:
header = ['class','confidence','x1','y1','x2','y2']
filename = "{0}/1r1c/{1}-{2:05d}.txt".format(networkname,videoname,frameNo)
df = pd.read_csv(zipfile.open(filename),sep=' ',names = header)
#resize df data
if df.shape[0] > 0:
df.loc[:,['x1','x2']] = df.loc[:,['x1','x2']] * 640./960.
df.loc[:,['y1','y2']] = df.loc[:,['y1','y2']] * 360./540.
df.loc[:,['x1','y1','x2','y2']] = df.loc[:,['x1','y1','x2','y2']].astype(int)
frame = drawBoxes(df,frame)
masked = maskFrame(frame,np.round(horizon * 2/3.).astype(np.int))
cv.imshow(ntpath.basename(videoname) + '-masked',masked)
cv.imshow(ntpath.basename(videoname),frame)
key = cv.waitKey(1)
if key == ord('q'):
break
if key == ord('p') or frameNo == 306:
# cv.waitKey(0)
saveFrame(frame,masked,'{}-{}-{:05d}'.format(ntwkname, ntpath.basename(videoname),frameNo) )
frameNo += 1
def detections_from_model_data(videoname,networkname,horizon,size=(640,360)):
video = cv.VideoCapture('../data/mp4/' + videoname + '.MP4')
ntwkname = shortenNetworkName(networkname)
csvfile = '../data/model_data/{}/{}/'.format(videoname,networkname)
if '608' in networkname:
csvfile += '{}-{}-GT-pruned.csv'.format(videoname,networkname)
else:
csvfile += '{}-{}-detection.csv'.format(videoname,networkname)
df = pd.read_csv(csvfile,header=[0,1],index_col=0,low_memory=False)
print(df.shape)
frameNo = 1
mask = None
pause = False
while video.isOpened():
_,frame = video.read()
if frame is None:
print('frame is none')
break
frame = cv.resize(frame,size)
masked = maskFrame(frame,np.round(horizon * 2/3.).astype(np.int))
if frameNo in df.index:
rowseries = df.loc[frameNo,:].dropna()
litters = rowseries.index.get_level_values(0).unique()
if len(litters) > 0:
rowdf = rowseries.unstack(level=1)
rowdf.loc[:,['x1','x2','y1','y2']] = rowdf.loc[:,['x1','x2','y1','y2']].mul(2./3.).astype(int)
frame = drawBoxes(rowdf,frame)
masked = drawBoxes(rowdf,masked)
# print(rowdf['info'],rowdf['info'].str.contains('new'))
if rowdf['info'].str.contains('new').any() and \
rowdf['info'].str.contains('inter').any() and \
rowdf['info'].str.contains('iou').any():
pause = True
print(frameNo,len(litters))
cv.imshow(ntpath.basename(videoname) + '-masked',masked)
cv.imshow(ntpath.basename(videoname),frame)
key = cv.waitKey(1)
if key == ord('q'):
break
if key == ord('p') or pause or frameNo == 306:
# cv.waitKey(0)
saveFrame(frame,masked,'{}-{}-{:05d}-info'.format(ntwkname, ntpath.basename(videoname),frameNo) )
pause = False
frameNo += 1
def bbox_path(resultspath,outputpath,networks,filterby=None):
if filterby is not None:
filterbyDF = pd.read_csv(filterby,header=[0,1],index_col=[0,1])
# cmap = plt.get_cmap('inferno')
for ntwk in networks:
print(ntwk)
fig = plt.figure(figsize=(16,9))
ax = fig.gca()
ax.invert_yaxis()
ax.set_ylim([0,540])
ax.set_xlim([0,960])
ax.set_xticks([])
ax.set_yticks([])
for csvfile in glob(resultspath + '/*/*/*' + ntwk + '-detection.csv'):
video = ntpath.basename(ntpath.dirname(ntpath.dirname(csvfile)))
print(video)
csvDF = pd.read_csv(csvfile,header=[0,1],index_col=0,low_memory=False)
if filterby is not None:
if video in filterbyDF.index.get_level_values(0).unique():
litters = filterbyDF.loc[video,:].index
csvDF = csvDF.loc[:,litters]
else:
continue
else:
litters = []
for lit in csvDF.columns.get_level_values(0).unique():
bbox = csvDF[lit].dropna(axis=0,how='all') #drop nan rows
bbox.loc[:,'cx'] = ((bbox['x1'] + bbox['x2'])/2.0).astype(int)
bbox.loc[:,'cy'] = ((bbox['y1'] + bbox['y2'])/2.0).astype(int)
alpha = 0.2
marker = '.'
markerfacecolor='none'
markersize=4
if bbox['info'].str.contains('inter').any():
ax.plot(bbox.loc[bbox['info'] == 'inter','cx'],
bbox.loc[bbox['info'] == 'inter','cy'],color='r',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=2)
if bbox['info'].str.contains('iou').any():
ax.plot(bbox.loc[bbox['info'] == 'iou','cx'],
bbox.loc[bbox['info'] == 'iou','cy'],color='b',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=1)
if bbox['info'].str.contains('new').any():
ax.plot(bbox.loc[bbox['info'] == 'new','cx'],
bbox.loc[bbox['info'] == 'new','cy'],color='k',marker='.',
markersize=8,alpha=1,linestyle='',zorder=3)
if bbox['info'].str.contains('TP').any():
ax.plot(bbox.loc[bbox['info'] == 'TP','cx'],
bbox.loc[bbox['info'] == 'TP','cy'],color='g',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=2)
if bbox['info'].str.contains('FN').any():
ax.plot(bbox.loc[bbox['info'] == 'FN','cx'],
bbox.loc[bbox['info'] == 'FN','cy'],color='r',marker=marker,
markersize=markersize,alpha=alpha,linestyle='',zorder=1)
if '608' in ntwk:
#plot last seen location
ax.plot([bbox['cx'].iloc[-1]],[bbox['cy'].iloc[-1]],
color='g',marker='.',
markersize=8,alpha=1,linestyle='',zorder=3)
plt.show()
fig.savefig(outputpath + '/centre_path_' + ntwk + '.png',bbox_inches='tight')
# break
if __name__ == '__main__':
first_last_appearance = '../data/simplified_data/yolo_608_horizon'
detection_data = '../data/model-data'
video = '20190111GOPR9029-hflip'
networkname = ['yolov3-litter_10000-th0p0-nms0p0-iSz608',
'yolov3-tiny-litter_10000-th0p0-nms0p0-iSz128',
'yolov3-tiny-litter_10000-th0p0-nms0p0-iSz224',
'mobilenetSSD-10000-th0p5-nms0p0-iSz124',
'mobilenetSSD-10000-th0p5-nms0p0-iSz220']
horizon = np.array([18,162,494,59,937,143])
# raw_detection_video(video,networkname[4],horizon)
# detections_from_model_data(video,networkname[2],horizon)
bbox_path('../data/model_data','../thesis_detection_figs',
networkname,filterby='../data/simplified_data/yolo_608_horizon/yolo_608_horizon.csv')
| en | 0.542773 | # Function to find the circle on # which the given three points lie # x1^2 - x3^2 # y1^2 - y3^2 # eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 # where centre is (h = -g, k = -f) and # radius r as r^2 = h^2 + k^2 - c # r is the radius #none ground truth data # insert text information #resize df data # cv.waitKey(0) # print(rowdf['info'],rowdf['info'].str.contains('new')) # cv.waitKey(0) # cmap = plt.get_cmap('inferno') #drop nan rows #plot last seen location # break # raw_detection_video(video,networkname[4],horizon) # detections_from_model_data(video,networkname[2],horizon) | 3.316075 | 3 |
psipy/model/tests/test_variable.py | jj-gonzalez-aviles/PsiPy | 4 | 6620366 | import pytest
from psipy.model import Variable
def test_var_error(mas_model):
with pytest.raises(RuntimeError, match='not in list of known variables'):
mas_model['not_a_var']
def test_radial_normalised(mas_model):
norm = mas_model['rho'].radial_normalized(-2)
assert isinstance(norm, Variable)
| import pytest
from psipy.model import Variable
def test_var_error(mas_model):
with pytest.raises(RuntimeError, match='not in list of known variables'):
mas_model['not_a_var']
def test_radial_normalised(mas_model):
norm = mas_model['rho'].radial_normalized(-2)
assert isinstance(norm, Variable)
| none | 1 | 2.557171 | 3 | |
TSN/main.py | sanket-pixel/deep-video | 0 | 6620367 | from dataset import RGBFrames, OpticalFlowStack
from model import TSN
from torchvision import utils, transforms, models
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import Compose, Normalize, Resize, RandomHorizontalFlip, RandomApply, RandomCrop, RandomResizedCrop
import torch
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
import pandas as pd
path_to_training = '../data/mini_UCF/train.txt'
path_to_validation = "../data/mini_UCF/validation.txt"
path_to_classes ='../data/mini_UCF/classes.txt'
root_rgb = '../data/mini_UCF/'
root_flow = '../data/mini-ucf101_flow_img_tvl1_gpu'
# rgb dataset
rgb_dataset_train= RGBFrames(path_to_training,path_to_classes,root_rgb , mode = "train", transform = Compose([RandomApply([RandomResizedCrop(256,(0.1,1.0)),RandomCrop(256), RandomHorizontalFlip(0.5)],0.9), Resize((224,224)), Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) ]))
rgb_dataset_validation = RGBFrames(path_to_validation,path_to_classes,root_rgb,mode = "test", transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) ]))
# optical flow dataset
optical_flow_train = OpticalFlowStack(path_to_training,path_to_classes,root_flow,mode = "train",transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449,
0.449],std=[0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226,
0.226])]))
optical_flow_test = OpticalFlowStack(path_to_validation,path_to_classes,root_flow,mode = "test",transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449,
0.449],std=[0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226,
0.226])]))
# general dataloader
dataloader_train = DataLoader(rgb_dataset_train, batch_size=16, shuffle=True, num_workers=16)
dataloader_validation = DataLoader(rgb_dataset_validation, batch_size=16, shuffle=True, num_workers=16)
# get cuda if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# dataloader testing for optical flow
dataloader_validation_optical = DataLoader(optical_flow_test, batch_size=8, shuffle=False, num_workers=8)
# dataloader testing for rgb
dataloader_validation_rgb = DataLoader(rgb_dataset_validation, batch_size=8, shuffle=False, num_workers=8)
# get class names from id
def get_labels(path_to_classes):
classes ={}
with open(path_to_classes) as f:
c = f.readlines()
for x in c:
classes[int(x.strip().split(" ")[0])] = x.strip().split(" ")[1]
return classes
# function to save model and stats
def save_model(model,stats, model_name):
model_dict = {"model":model, "stats":stats}
torch.save(model_dict, "../models/" + model_name + ".pth")
# function to eval model and calculate classwise accuracy
@torch.no_grad()
def eval_model(model,dataloader_validation=dataloader_validation):
""" Computing model accuracy """
correct = 0
total = 0
loss_list = []
pred_list = []
label_list = []
criterion = torch.nn.CrossEntropyLoss().to(device) # cross entropy loss
for batch in dataloader_validation:
snippets = batch[0].to(device) # get snippets
labels = batch[1].to(device) # get label
label_list.append(labels)
# Forward pass only to get logits/output
outputs = model(snippets) # forward pass
loss = criterion(outputs, labels) # find loss
loss_list.append(loss.item())
# Get predictions from the maximum value
preds = torch.argmax(outputs, dim=1) # get prediction
pred_list.append(preds)
correct += len(torch.where(preds == labels)[0])
total += len(labels)
# get classwise accuracy
predictions = torch.cat(pred_list)
labels = torch.cat(label_list)
classes = get_labels(path_to_classes)
classwise_accuracy = {}
for i in range(25):
classwise_accuracy[classes[i]] = len(torch.where((predictions == i) & (predictions == labels))[0]) / len(
torch.where(labels == i)[0])
# Total correct predictions and loss
accuracy = correct / total * 100
loss = np.mean(loss_list)
return accuracy, loss, classwise_accuracy
# function to calculate late fusion
@torch.no_grad()
def late_fusion_eval(model_optical_flow, model_rgb):
""" Computing model accuracy """
correct = 0
total = 0
loss_list = []
pred_list = []
label_list = []
criterion = torch.nn.CrossEntropyLoss().to(device)
for batch_optical, batch_rgb in zip(dataloader_validation_optical,dataloader_validation_rgb):
snippets_optical= batch_optical[0].to(device) # get optical flow snippets
labels_o = batch_optical[1].to(device)
snippets_rgb = batch_rgb[0].to(device) # get rgb snippets
labels = batch_rgb[1].to(device)
label_list.append(labels)
# Forward pass optical flow and rgb models
outputs_optical_flow = model_optical_flow(snippets_optical)
output_rgb = model_rgb(snippets_rgb)
# take average of both models
outputs = torch.add(outputs_optical_flow,output_rgb).divide(2)
# find loss
loss = criterion(outputs, labels)
loss_list.append(loss.item())
# Get predictions from the maximum value
preds = torch.argmax(outputs, dim=1)
pred_list.append(preds)
correct += len(torch.where(preds == labels)[0])
total += len(labels)
# classwise accuracy
predictions = torch.cat(pred_list)
labels = torch.cat(label_list)
classes = get_labels(path_to_classes)
classwise_accuracy = {}
for i in range(25):
classwise_accuracy[classes[i]] = len(torch.where((predictions == i) & (predictions == labels))[0]) / len(torch.where(labels == i)[0])
# Total correct predictions and loss
accuracy = correct / total * 100
loss = np.mean(loss_list)
return accuracy, loss,classwise_accuracy
def train_model():
LR = 1e-4 # learning rate
EPOCHS = 20
EVAL_FREQ = 1
SAVE_FREQ = 5
# initialize model
# for using with optical flow change modality to "optical_flow"
tsn = TSN(4, 25, modality="rgb")
tsn = tsn.to(device)
criterion = torch.nn.CrossEntropyLoss().to(device) # cross entropy loss
optimizer = torch.optim.Adam(params=tsn.parameters(), lr = LR) # define optimizer
stats = {
"epoch": [],
"train_loss": [],
"valid_loss": [],
"accuracy": []
}
init_epoch = 0
loss_hist = []
for epoch in range(init_epoch,EPOCHS): # iterate over epochs
loss_list = []
progress_bar = tqdm(enumerate(dataloader_train), total=len(dataloader_train))
for i, batch in progress_bar: # iterate over batches
snippets = batch[0].to(device)
labels = batch[1].to(device)
optimizer.zero_grad() # remove old grads
y = tsn(snippets) # get predictions
loss = criterion(y, labels) # find loss
loss_list.append(loss.item())
loss.backward() # find gradients
optimizer.step() # update weights
progress_bar.set_description(f"Epoch {0 + 1} Iter {i + 1}: loss {loss.item():.5f}. ")
# update stats
loss_hist.append(np.mean(loss_list))
stats['epoch'].append(epoch)
stats['train_loss'].append(loss_hist[-1])
if epoch % EVAL_FREQ == 0:
accuracy, valid_loss, _ = eval_model(tsn)
print(f"Accuracy at epoch {epoch}: {round(accuracy, 2)}%")
else:
accuracy, valid_loss = -1, -1
stats["accuracy"].append(accuracy)
stats["valid_loss"].append(valid_loss)
# saving checkpoint
if epoch % SAVE_FREQ == 0:
save_model(tsn,stats, "RGB_tsn")
save_model(tsn, stats, "RGB_tsn")
save_model(tsn, stats, "RGB_tsn")
# method to generate results after training
def compare_results(model_list, labels,dataloaders):
train_loss = {}
validation_loss = {}
accuracy = {}
stat_list = [model["stats"] for model in model_list]
models = [m["model"] for m in model_list]
for i,stat in enumerate(stat_list):
accuracy[labels[i]] = stat['accuracy']
validation_loss[labels[i]] = stat['valid_loss']
train_loss[labels[i]] = stat['train_loss']
for i,label in enumerate(labels):
plt.plot(accuracy[label], label=label)
plt.suptitle("Accuracy comparision")
plt.legend()
plt.show()
for i,label in enumerate(labels):
plt.plot(train_loss[label], label=label)
plt.suptitle("Train Loss comparision")
plt.legend()
plt.show()
for i,label in enumerate(labels):
plt.plot(validation_loss[label], label=label)
plt.suptitle("Val Loss comparision")
plt.legend()
plt.show()
testing_accuracy = {}
classwise = {}
for i, model in enumerate(models):
testing_accuracy[labels[i]],t, classwise[labels[i]] = eval_model(model.eval(),dataloaders[i])
plt.bar(range(len(testing_accuracy)), list(testing_accuracy.values()), align='center')
plt.xticks(range(len(testing_accuracy)), list(testing_accuracy.keys()))
plt.legend()
plt.show()
acc_class = np.array([np.fromiter(classwise[model].values(), dtype=float) for model in classwise.keys()]).T
df = pd.DataFrame(classwise)
ax = df.plot.bar()
plt.show()
train_model() # call this to train model
# model_optical_flow = torch.load('../models/optical_flow_pre_trained.pth')
# model_optical_flow_random = torch.load('../models/optical_flow_random.pth')
# model_rgb = torch.load('../models/RGB_tsn.pth')
# result_dict = {}
# result_dict['rgb'] = eval_model(model_rgb['model'].eval(),dataloader_validation_rgb)
# result_dict['optical'] = eval_model(model_optical_flow['model'].eval(),dataloader_validation_optical)
# result_dict['fusion'] = late_fusion_eval(model_optical_flow['model'].eval(), model_rgb['model'].eval())
# torch.save(result_dict,'../result_compare.pth')
# call this to see plots
# compare_results([model_optical_flow_random,model_optical_flow],["OpticalFlowRandom","OpticalFlow"],[dataloader_validation_optical,dataloader_validation_optical]) | from dataset import RGBFrames, OpticalFlowStack
from model import TSN
from torchvision import utils, transforms, models
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import Compose, Normalize, Resize, RandomHorizontalFlip, RandomApply, RandomCrop, RandomResizedCrop
import torch
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
import pandas as pd
path_to_training = '../data/mini_UCF/train.txt'
path_to_validation = "../data/mini_UCF/validation.txt"
path_to_classes ='../data/mini_UCF/classes.txt'
root_rgb = '../data/mini_UCF/'
root_flow = '../data/mini-ucf101_flow_img_tvl1_gpu'
# rgb dataset
rgb_dataset_train= RGBFrames(path_to_training,path_to_classes,root_rgb , mode = "train", transform = Compose([RandomApply([RandomResizedCrop(256,(0.1,1.0)),RandomCrop(256), RandomHorizontalFlip(0.5)],0.9), Resize((224,224)), Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) ]))
rgb_dataset_validation = RGBFrames(path_to_validation,path_to_classes,root_rgb,mode = "test", transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) ]))
# optical flow dataset
optical_flow_train = OpticalFlowStack(path_to_training,path_to_classes,root_flow,mode = "train",transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449,
0.449],std=[0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226,
0.226])]))
optical_flow_test = OpticalFlowStack(path_to_validation,path_to_classes,root_flow,mode = "test",transform = transforms.Compose([Resize((224,224)), Normalize(mean=[0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449, 0.449,
0.449],std=[0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226, 0.226,
0.226])]))
# general dataloader
dataloader_train = DataLoader(rgb_dataset_train, batch_size=16, shuffle=True, num_workers=16)
dataloader_validation = DataLoader(rgb_dataset_validation, batch_size=16, shuffle=True, num_workers=16)
# get cuda if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# dataloader testing for optical flow
dataloader_validation_optical = DataLoader(optical_flow_test, batch_size=8, shuffle=False, num_workers=8)
# dataloader testing for rgb
dataloader_validation_rgb = DataLoader(rgb_dataset_validation, batch_size=8, shuffle=False, num_workers=8)
# get class names from id
def get_labels(path_to_classes):
classes ={}
with open(path_to_classes) as f:
c = f.readlines()
for x in c:
classes[int(x.strip().split(" ")[0])] = x.strip().split(" ")[1]
return classes
# function to save model and stats
def save_model(model,stats, model_name):
model_dict = {"model":model, "stats":stats}
torch.save(model_dict, "../models/" + model_name + ".pth")
# function to eval model and calculate classwise accuracy
@torch.no_grad()
def eval_model(model,dataloader_validation=dataloader_validation):
""" Computing model accuracy """
correct = 0
total = 0
loss_list = []
pred_list = []
label_list = []
criterion = torch.nn.CrossEntropyLoss().to(device) # cross entropy loss
for batch in dataloader_validation:
snippets = batch[0].to(device) # get snippets
labels = batch[1].to(device) # get label
label_list.append(labels)
# Forward pass only to get logits/output
outputs = model(snippets) # forward pass
loss = criterion(outputs, labels) # find loss
loss_list.append(loss.item())
# Get predictions from the maximum value
preds = torch.argmax(outputs, dim=1) # get prediction
pred_list.append(preds)
correct += len(torch.where(preds == labels)[0])
total += len(labels)
# get classwise accuracy
predictions = torch.cat(pred_list)
labels = torch.cat(label_list)
classes = get_labels(path_to_classes)
classwise_accuracy = {}
for i in range(25):
classwise_accuracy[classes[i]] = len(torch.where((predictions == i) & (predictions == labels))[0]) / len(
torch.where(labels == i)[0])
# Total correct predictions and loss
accuracy = correct / total * 100
loss = np.mean(loss_list)
return accuracy, loss, classwise_accuracy
# function to calculate late fusion
@torch.no_grad()
def late_fusion_eval(model_optical_flow, model_rgb):
""" Computing model accuracy """
correct = 0
total = 0
loss_list = []
pred_list = []
label_list = []
criterion = torch.nn.CrossEntropyLoss().to(device)
for batch_optical, batch_rgb in zip(dataloader_validation_optical,dataloader_validation_rgb):
snippets_optical= batch_optical[0].to(device) # get optical flow snippets
labels_o = batch_optical[1].to(device)
snippets_rgb = batch_rgb[0].to(device) # get rgb snippets
labels = batch_rgb[1].to(device)
label_list.append(labels)
# Forward pass optical flow and rgb models
outputs_optical_flow = model_optical_flow(snippets_optical)
output_rgb = model_rgb(snippets_rgb)
# take average of both models
outputs = torch.add(outputs_optical_flow,output_rgb).divide(2)
# find loss
loss = criterion(outputs, labels)
loss_list.append(loss.item())
# Get predictions from the maximum value
preds = torch.argmax(outputs, dim=1)
pred_list.append(preds)
correct += len(torch.where(preds == labels)[0])
total += len(labels)
# classwise accuracy
predictions = torch.cat(pred_list)
labels = torch.cat(label_list)
classes = get_labels(path_to_classes)
classwise_accuracy = {}
for i in range(25):
classwise_accuracy[classes[i]] = len(torch.where((predictions == i) & (predictions == labels))[0]) / len(torch.where(labels == i)[0])
# Total correct predictions and loss
accuracy = correct / total * 100
loss = np.mean(loss_list)
return accuracy, loss,classwise_accuracy
def train_model():
LR = 1e-4 # learning rate
EPOCHS = 20
EVAL_FREQ = 1
SAVE_FREQ = 5
# initialize model
# for using with optical flow change modality to "optical_flow"
tsn = TSN(4, 25, modality="rgb")
tsn = tsn.to(device)
criterion = torch.nn.CrossEntropyLoss().to(device) # cross entropy loss
optimizer = torch.optim.Adam(params=tsn.parameters(), lr = LR) # define optimizer
stats = {
"epoch": [],
"train_loss": [],
"valid_loss": [],
"accuracy": []
}
init_epoch = 0
loss_hist = []
for epoch in range(init_epoch,EPOCHS): # iterate over epochs
loss_list = []
progress_bar = tqdm(enumerate(dataloader_train), total=len(dataloader_train))
for i, batch in progress_bar: # iterate over batches
snippets = batch[0].to(device)
labels = batch[1].to(device)
optimizer.zero_grad() # remove old grads
y = tsn(snippets) # get predictions
loss = criterion(y, labels) # find loss
loss_list.append(loss.item())
loss.backward() # find gradients
optimizer.step() # update weights
progress_bar.set_description(f"Epoch {0 + 1} Iter {i + 1}: loss {loss.item():.5f}. ")
# update stats
loss_hist.append(np.mean(loss_list))
stats['epoch'].append(epoch)
stats['train_loss'].append(loss_hist[-1])
if epoch % EVAL_FREQ == 0:
accuracy, valid_loss, _ = eval_model(tsn)
print(f"Accuracy at epoch {epoch}: {round(accuracy, 2)}%")
else:
accuracy, valid_loss = -1, -1
stats["accuracy"].append(accuracy)
stats["valid_loss"].append(valid_loss)
# saving checkpoint
if epoch % SAVE_FREQ == 0:
save_model(tsn,stats, "RGB_tsn")
save_model(tsn, stats, "RGB_tsn")
save_model(tsn, stats, "RGB_tsn")
# method to generate results after training
def compare_results(model_list, labels,dataloaders):
train_loss = {}
validation_loss = {}
accuracy = {}
stat_list = [model["stats"] for model in model_list]
models = [m["model"] for m in model_list]
for i,stat in enumerate(stat_list):
accuracy[labels[i]] = stat['accuracy']
validation_loss[labels[i]] = stat['valid_loss']
train_loss[labels[i]] = stat['train_loss']
for i,label in enumerate(labels):
plt.plot(accuracy[label], label=label)
plt.suptitle("Accuracy comparision")
plt.legend()
plt.show()
for i,label in enumerate(labels):
plt.plot(train_loss[label], label=label)
plt.suptitle("Train Loss comparision")
plt.legend()
plt.show()
for i,label in enumerate(labels):
plt.plot(validation_loss[label], label=label)
plt.suptitle("Val Loss comparision")
plt.legend()
plt.show()
testing_accuracy = {}
classwise = {}
for i, model in enumerate(models):
testing_accuracy[labels[i]],t, classwise[labels[i]] = eval_model(model.eval(),dataloaders[i])
plt.bar(range(len(testing_accuracy)), list(testing_accuracy.values()), align='center')
plt.xticks(range(len(testing_accuracy)), list(testing_accuracy.keys()))
plt.legend()
plt.show()
acc_class = np.array([np.fromiter(classwise[model].values(), dtype=float) for model in classwise.keys()]).T
df = pd.DataFrame(classwise)
ax = df.plot.bar()
plt.show()
train_model() # call this to train model
# model_optical_flow = torch.load('../models/optical_flow_pre_trained.pth')
# model_optical_flow_random = torch.load('../models/optical_flow_random.pth')
# model_rgb = torch.load('../models/RGB_tsn.pth')
# result_dict = {}
# result_dict['rgb'] = eval_model(model_rgb['model'].eval(),dataloader_validation_rgb)
# result_dict['optical'] = eval_model(model_optical_flow['model'].eval(),dataloader_validation_optical)
# result_dict['fusion'] = late_fusion_eval(model_optical_flow['model'].eval(), model_rgb['model'].eval())
# torch.save(result_dict,'../result_compare.pth')
# call this to see plots
# compare_results([model_optical_flow_random,model_optical_flow],["OpticalFlowRandom","OpticalFlow"],[dataloader_validation_optical,dataloader_validation_optical]) | en | 0.547578 | # rgb dataset # optical flow dataset # general dataloader # get cuda if available # dataloader testing for optical flow # dataloader testing for rgb # get class names from id # function to save model and stats # function to eval model and calculate classwise accuracy Computing model accuracy # cross entropy loss # get snippets # get label # Forward pass only to get logits/output # forward pass # find loss # Get predictions from the maximum value # get prediction # get classwise accuracy # Total correct predictions and loss # function to calculate late fusion Computing model accuracy # get optical flow snippets # get rgb snippets # Forward pass optical flow and rgb models # take average of both models # find loss # Get predictions from the maximum value # classwise accuracy # Total correct predictions and loss # learning rate # initialize model # for using with optical flow change modality to "optical_flow" # cross entropy loss # define optimizer # iterate over epochs # iterate over batches # remove old grads # get predictions # find loss # find gradients # update weights # update stats # saving checkpoint # method to generate results after training # call this to train model # model_optical_flow = torch.load('../models/optical_flow_pre_trained.pth') # model_optical_flow_random = torch.load('../models/optical_flow_random.pth') # model_rgb = torch.load('../models/RGB_tsn.pth') # result_dict = {} # result_dict['rgb'] = eval_model(model_rgb['model'].eval(),dataloader_validation_rgb) # result_dict['optical'] = eval_model(model_optical_flow['model'].eval(),dataloader_validation_optical) # result_dict['fusion'] = late_fusion_eval(model_optical_flow['model'].eval(), model_rgb['model'].eval()) # torch.save(result_dict,'../result_compare.pth') # call this to see plots # compare_results([model_optical_flow_random,model_optical_flow],["OpticalFlowRandom","OpticalFlow"],[dataloader_validation_optical,dataloader_validation_optical]) | 2.214857 | 2 |
script/dataloader.py | SAMMiCA/ChangeSim | 39 | 6620368 | <reponame>SAMMiCA/ChangeSim
import os
import os.path as osp
import numpy as np
import random
import matplotlib.pyplot as plt
import collections
import torch
import torchvision
import torch.nn as nn
from torch.utils import data
from PIL import Image
from utils import Object_Labeling
from torchvision.transforms import ToTensor, Resize, Compose
import torchvision.transforms as transforms
from depth2disp_example import depth2disp
import glob
import pdb
import matplotlib.pyplot as plt
import tkinter
import matplotlib
matplotlib.use('TkAgg')
class ChangeSim(data.Dataset):
def __init__(self, crop_size=(320, 240), num_classes=5, set='train'):
"""
ChangeSim Dataloader
Please download ChangeSim Dataset in https://github.com/SAMMiCA/ChangeSim
Args:
crop_size (tuple): Image resize shape (H,W) (default: (320, 240))
num_classes (int): Number of target change detection class
5 for multi-class change detection
2 for binary change detection (default: 5)
set (str): 'train' or 'test' (defalut: 'train')
"""
self.crop_size = crop_size
self.num_classes = num_classes
self.set = set
self.blacklist=[]
train_list = ['Warehouse_0', 'Warehouse_1', 'Warehouse_2', 'Warehouse_3', 'Warehouse_4', 'Warehouse_5']
test_list = ['Warehouse_6', 'Warehouse_7', 'Warehouse_8', 'Warehouse_9']
self.image_total_files = []
if set == 'train':
for map in train_list:
self.image_total_files += glob.glob('../Query/Query_Seq_Train/' + map + '/Seq_0/rgb/*.png')
self.image_total_files += glob.glob('../Query/Query_Seq_Train/' + map + '/Seq_1/rgb/*.png')
elif set == 'test':
for map in test_list:
self.image_total_files += glob.glob('../Query/Query_Seq_Test/' + map + '/Seq_0/rgb/*.png')
self.image_total_files += glob.glob('../Query/Query_Seq_Test/' + map + '/Seq_1/rgb/*.png')
# if not max_iters == None:
# self.image_total_files = self.image_total_files * int(np.ceil(float(max_iters) / len(self.image_total_files)))
# self.image_total_files = self.image_total_files[:max_iters]
self.seg = Object_Labeling.SegHelper(idx2color_path='./utils/idx2color.txt', num_class=self.num_classes)
#### Color Transform ####
self.color_transform = transforms.Compose([transforms.ColorJitter(0.4, 0.4, 0.4, 0.25),
transforms.ToTensor()])
# self.transform = Compose([Resize(crop_size), ToTensor()])
def __len__(self):
return len(self.image_total_files)
def __getitem__(self, index):
# Train set
if self.set == 'train':
loss = nn.L1Loss()
while True:
if index in self.blacklist:
index=random.randint(0,self.__len__()-1)
continue
test_rgb_path = self.image_total_files[index]
file_idx = test_rgb_path.split('/')[-1].split('.')[0] # ~~ of ~~.png
ref_pose_find_path = test_rgb_path.replace(f'rgb/{file_idx}.png',f't0/idx/{file_idx}.txt')
f = open(ref_pose_find_path,'r',encoding='utf8')
ref_pose_idx = int(f.readlines()[0])
g2o_path = test_rgb_path.replace('/Query/Query_Seq_Train','/Reference/Ref_Seq_Train').replace(f'rgb/{file_idx}.png',f'raw/poses.g2o')
with open(g2o_path,'r',encoding = 'utf8') as f2:
while True:
line = f2.readline()
try:
if line.split()[0] == 'VERTEX_SE3:QUAT' and int(line.split()[1]) == ref_pose_idx:
ref_pose = line.split()[2:]
except:
break
ref_pose = torch.from_numpy(np.array(ref_pose).astype(float))
change_pose_path = test_rgb_path.replace(f'rgb/{file_idx}.png',f'pose/{file_idx}.txt')
with open(change_pose_path,'r',encoding='utf8') as f3:
change_pose = f3.readline().split()
change_pose = torch.from_numpy(np.array(change_pose).astype(float))
distance = loss(ref_pose.cuda(),change_pose.cuda())
if distance.item()<0.5:
break
else:
self.blacklist.append(index)
index=random.randint(0,self.__len__()-1)
# Test set
else:
test_rgb_path = self.image_total_files[index]
# Get File Paths
test_depth_path = test_rgb_path.replace('rgb', 'depth')
ref_rgb_path = test_rgb_path.replace('rgb', 't0/rgb')
ref_depth_path = test_rgb_path.replace('rgb', 't0/depth')
change_segmentation_path = test_rgb_path.replace('rgb', 'change_segmentation')
name = '_'.join(test_rgb_path.split('/')[-5:])
#### Color Transform ####
test_rgb = Image.open(test_rgb_path)
ref_rgb = Image.open(ref_rgb_path)
test_rgb = test_rgb.resize(self.crop_size, Image.BICUBIC)
ref_rgb = ref_rgb.resize(self.crop_size, Image.BICUBIC)
# RGB, Color Transform for train set
if self.set == 'train':
test_rgb = self.color_transform(test_rgb)
ref_rgb = self.color_transform(ref_rgb)
else:
test_rgb = ToTensor()(test_rgb)
ref_rgb = ToTensor()(ref_rgb)
# Depth
# test_depth = Image.open(test_depth_path)
# test_depth = np.asarray(test_depth)
# test_depth = test_depth.astype('float32') / 255
# test_depth = depth2disp(test_depth, 1, 50)
# test_depth = torch.from_numpy(test_depth)
# ref_depth = Image.open(ref_depth_path)
# ref_depth = np.clip(ref_depth, 0, 50) / 50 * 255
# ref_depth = np.asarray(ref_depth)
# ref_depth = ref_depth.astype('float32') / 255
# ref_depth = depth2disp(ref_depth, 1, 50)
# ref_depth = torch.from_numpy(ref_depth)
# Change Label
change_label = Image.open(change_segmentation_path)
change_label = change_label.resize(self.crop_size, Image.NEAREST)
change_label_mapping = np.asarray(change_label).copy()
change_mapping = self.seg.colormap2classmap(change_label_mapping)
label = change_mapping.permute(2,0,1).squeeze(0).long().cpu()
#### Binarization ####
if self.num_classes == 2:
label[label > 0] = 1
# if (label > 5).sum() > 0:
# print(image_path)
# Horizontal Flip
if self.set == 'train' and np.random.rand() <= 0.5:
test_rgb = np.asarray(test_rgb)
test_rgb = test_rgb[:, :, ::-1]
test_rgb = np.ascontiguousarray(test_rgb)
test_rgb = torch.from_numpy(test_rgb)
ref_rgb = np.asarray(ref_rgb)
ref_rgb = ref_rgb[:, :, ::-1]
ref_rgb = np.ascontiguousarray(ref_rgb)
ref_rgb = torch.from_numpy(ref_rgb)
label = np.asarray(label)
label = label[:, ::-1]
label = np.ascontiguousarray(label)
label = torch.from_numpy(label)
return [ref_rgb, test_rgb], label.long(), test_rgb_path
if __name__ == '__main__':
dst = ChangeSim(crop_size=(320, 240), num_classes=5, set='train')
dataloader = data.DataLoader(dst, batch_size=4, num_workers=2)
for i, data in enumerate(dataloader):
imgs, labels, path = data
| import os
import os.path as osp
import numpy as np
import random
import matplotlib.pyplot as plt
import collections
import torch
import torchvision
import torch.nn as nn
from torch.utils import data
from PIL import Image
from utils import Object_Labeling
from torchvision.transforms import ToTensor, Resize, Compose
import torchvision.transforms as transforms
from depth2disp_example import depth2disp
import glob
import pdb
import matplotlib.pyplot as plt
import tkinter
import matplotlib
matplotlib.use('TkAgg')
class ChangeSim(data.Dataset):
def __init__(self, crop_size=(320, 240), num_classes=5, set='train'):
"""
ChangeSim Dataloader
Please download ChangeSim Dataset in https://github.com/SAMMiCA/ChangeSim
Args:
crop_size (tuple): Image resize shape (H,W) (default: (320, 240))
num_classes (int): Number of target change detection class
5 for multi-class change detection
2 for binary change detection (default: 5)
set (str): 'train' or 'test' (defalut: 'train')
"""
self.crop_size = crop_size
self.num_classes = num_classes
self.set = set
self.blacklist=[]
train_list = ['Warehouse_0', 'Warehouse_1', 'Warehouse_2', 'Warehouse_3', 'Warehouse_4', 'Warehouse_5']
test_list = ['Warehouse_6', 'Warehouse_7', 'Warehouse_8', 'Warehouse_9']
self.image_total_files = []
if set == 'train':
for map in train_list:
self.image_total_files += glob.glob('../Query/Query_Seq_Train/' + map + '/Seq_0/rgb/*.png')
self.image_total_files += glob.glob('../Query/Query_Seq_Train/' + map + '/Seq_1/rgb/*.png')
elif set == 'test':
for map in test_list:
self.image_total_files += glob.glob('../Query/Query_Seq_Test/' + map + '/Seq_0/rgb/*.png')
self.image_total_files += glob.glob('../Query/Query_Seq_Test/' + map + '/Seq_1/rgb/*.png')
# if not max_iters == None:
# self.image_total_files = self.image_total_files * int(np.ceil(float(max_iters) / len(self.image_total_files)))
# self.image_total_files = self.image_total_files[:max_iters]
self.seg = Object_Labeling.SegHelper(idx2color_path='./utils/idx2color.txt', num_class=self.num_classes)
#### Color Transform ####
self.color_transform = transforms.Compose([transforms.ColorJitter(0.4, 0.4, 0.4, 0.25),
transforms.ToTensor()])
# self.transform = Compose([Resize(crop_size), ToTensor()])
def __len__(self):
return len(self.image_total_files)
def __getitem__(self, index):
# Train set
if self.set == 'train':
loss = nn.L1Loss()
while True:
if index in self.blacklist:
index=random.randint(0,self.__len__()-1)
continue
test_rgb_path = self.image_total_files[index]
file_idx = test_rgb_path.split('/')[-1].split('.')[0] # ~~ of ~~.png
ref_pose_find_path = test_rgb_path.replace(f'rgb/{file_idx}.png',f't0/idx/{file_idx}.txt')
f = open(ref_pose_find_path,'r',encoding='utf8')
ref_pose_idx = int(f.readlines()[0])
g2o_path = test_rgb_path.replace('/Query/Query_Seq_Train','/Reference/Ref_Seq_Train').replace(f'rgb/{file_idx}.png',f'raw/poses.g2o')
with open(g2o_path,'r',encoding = 'utf8') as f2:
while True:
line = f2.readline()
try:
if line.split()[0] == 'VERTEX_SE3:QUAT' and int(line.split()[1]) == ref_pose_idx:
ref_pose = line.split()[2:]
except:
break
ref_pose = torch.from_numpy(np.array(ref_pose).astype(float))
change_pose_path = test_rgb_path.replace(f'rgb/{file_idx}.png',f'pose/{file_idx}.txt')
with open(change_pose_path,'r',encoding='utf8') as f3:
change_pose = f3.readline().split()
change_pose = torch.from_numpy(np.array(change_pose).astype(float))
distance = loss(ref_pose.cuda(),change_pose.cuda())
if distance.item()<0.5:
break
else:
self.blacklist.append(index)
index=random.randint(0,self.__len__()-1)
# Test set
else:
test_rgb_path = self.image_total_files[index]
# Get File Paths
test_depth_path = test_rgb_path.replace('rgb', 'depth')
ref_rgb_path = test_rgb_path.replace('rgb', 't0/rgb')
ref_depth_path = test_rgb_path.replace('rgb', 't0/depth')
change_segmentation_path = test_rgb_path.replace('rgb', 'change_segmentation')
name = '_'.join(test_rgb_path.split('/')[-5:])
#### Color Transform ####
test_rgb = Image.open(test_rgb_path)
ref_rgb = Image.open(ref_rgb_path)
test_rgb = test_rgb.resize(self.crop_size, Image.BICUBIC)
ref_rgb = ref_rgb.resize(self.crop_size, Image.BICUBIC)
# RGB, Color Transform for train set
if self.set == 'train':
test_rgb = self.color_transform(test_rgb)
ref_rgb = self.color_transform(ref_rgb)
else:
test_rgb = ToTensor()(test_rgb)
ref_rgb = ToTensor()(ref_rgb)
# Depth
# test_depth = Image.open(test_depth_path)
# test_depth = np.asarray(test_depth)
# test_depth = test_depth.astype('float32') / 255
# test_depth = depth2disp(test_depth, 1, 50)
# test_depth = torch.from_numpy(test_depth)
# ref_depth = Image.open(ref_depth_path)
# ref_depth = np.clip(ref_depth, 0, 50) / 50 * 255
# ref_depth = np.asarray(ref_depth)
# ref_depth = ref_depth.astype('float32') / 255
# ref_depth = depth2disp(ref_depth, 1, 50)
# ref_depth = torch.from_numpy(ref_depth)
# Change Label
change_label = Image.open(change_segmentation_path)
change_label = change_label.resize(self.crop_size, Image.NEAREST)
change_label_mapping = np.asarray(change_label).copy()
change_mapping = self.seg.colormap2classmap(change_label_mapping)
label = change_mapping.permute(2,0,1).squeeze(0).long().cpu()
#### Binarization ####
if self.num_classes == 2:
label[label > 0] = 1
# if (label > 5).sum() > 0:
# print(image_path)
# Horizontal Flip
if self.set == 'train' and np.random.rand() <= 0.5:
test_rgb = np.asarray(test_rgb)
test_rgb = test_rgb[:, :, ::-1]
test_rgb = np.ascontiguousarray(test_rgb)
test_rgb = torch.from_numpy(test_rgb)
ref_rgb = np.asarray(ref_rgb)
ref_rgb = ref_rgb[:, :, ::-1]
ref_rgb = np.ascontiguousarray(ref_rgb)
ref_rgb = torch.from_numpy(ref_rgb)
label = np.asarray(label)
label = label[:, ::-1]
label = np.ascontiguousarray(label)
label = torch.from_numpy(label)
return [ref_rgb, test_rgb], label.long(), test_rgb_path
if __name__ == '__main__':
dst = ChangeSim(crop_size=(320, 240), num_classes=5, set='train')
dataloader = data.DataLoader(dst, batch_size=4, num_workers=2)
for i, data in enumerate(dataloader):
imgs, labels, path = data | en | 0.302949 | ChangeSim Dataloader Please download ChangeSim Dataset in https://github.com/SAMMiCA/ChangeSim Args: crop_size (tuple): Image resize shape (H,W) (default: (320, 240)) num_classes (int): Number of target change detection class 5 for multi-class change detection 2 for binary change detection (default: 5) set (str): 'train' or 'test' (defalut: 'train') # if not max_iters == None: # self.image_total_files = self.image_total_files * int(np.ceil(float(max_iters) / len(self.image_total_files))) # self.image_total_files = self.image_total_files[:max_iters] #### Color Transform #### # self.transform = Compose([Resize(crop_size), ToTensor()]) # Train set # ~~ of ~~.png # Test set # Get File Paths #### Color Transform #### # RGB, Color Transform for train set # Depth # test_depth = Image.open(test_depth_path) # test_depth = np.asarray(test_depth) # test_depth = test_depth.astype('float32') / 255 # test_depth = depth2disp(test_depth, 1, 50) # test_depth = torch.from_numpy(test_depth) # ref_depth = Image.open(ref_depth_path) # ref_depth = np.clip(ref_depth, 0, 50) / 50 * 255 # ref_depth = np.asarray(ref_depth) # ref_depth = ref_depth.astype('float32') / 255 # ref_depth = depth2disp(ref_depth, 1, 50) # ref_depth = torch.from_numpy(ref_depth) # Change Label #### Binarization #### # if (label > 5).sum() > 0: # print(image_path) # Horizontal Flip | 2.442134 | 2 |
common/noise.py | wedddy0707/noisyEGG | 1 | 6620369 | <gh_stars>1-10
# Copyright (c) 2021 <NAME>
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
class GaussNoise(nn.Module):
def __init__(self, loc, scale):
super(GaussNoise, self).__init__()
self.loc = loc if loc is not None else 0.0
self.scale = scale if scale is not None else 0.0
def forward(self, x):
return x + float(self.training) * (
self.loc + self.scale * torch.randn_like(x).to(x.device)
)
class Noise(nn.Module):
def __init__(
self,
loc=None,
scale=None,
dropout_p=None,
):
super(Noise, self).__init__()
if dropout_p is not None:
self.layer = nn.Dropout(p=dropout_p)
else:
self.layer = GaussNoise(loc=loc, scale=scale)
def forward(self, x):
return self.layer(x)
| # Copyright (c) 2021 <NAME>
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
class GaussNoise(nn.Module):
def __init__(self, loc, scale):
super(GaussNoise, self).__init__()
self.loc = loc if loc is not None else 0.0
self.scale = scale if scale is not None else 0.0
def forward(self, x):
return x + float(self.training) * (
self.loc + self.scale * torch.randn_like(x).to(x.device)
)
class Noise(nn.Module):
def __init__(
self,
loc=None,
scale=None,
dropout_p=None,
):
super(Noise, self).__init__()
if dropout_p is not None:
self.layer = nn.Dropout(p=dropout_p)
else:
self.layer = GaussNoise(loc=loc, scale=scale)
def forward(self, x):
return self.layer(x) | en | 0.908828 | # Copyright (c) 2021 <NAME> # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. | 2.386999 | 2 |
Movie Recommender System/movie-recommender-system/collaborative_filtering/constants.py | LuciFR1809/IR-Projects | 0 | 6620370 | from sys import maxsize
INT_MIN = -maxsize - 1
| from sys import maxsize
INT_MIN = -maxsize - 1
| none | 1 | 1.237305 | 1 | |
opt/util/waymo_dataset.py | yjcaimeow/svox2 | 0 | 6620371 | <reponame>yjcaimeow/svox2
# Standard NeRF Blender dataset loader
from .util import Rays, Intrin, select_or_shuffle_rays
from .dataset_base import DatasetBase
import torch
import torch.nn.functional as F
from typing import NamedTuple, Optional, Union
from os import path
import imageio
from tqdm import tqdm
import cv2
import json
import numpy as np
# import tensorflow.compat.v1 as tf
import tensorflow as tf
torch.set_default_tensor_type('torch.cuda.FloatTensor')
#tf.enable_eager_execution()
# from waymo_open_dataset.utils import range_image_utils
# from waymo_open_dataset.utils import transform_utils
# from waymo_open_dataset.utils import frame_utils
from waymo_open_dataset import dataset_pb2 as open_dataset
def normalize(x):
return x / np.linalg.norm(x)
def viewmatrix(z, up, pos):
vec2 = normalize(z)
vec1_avg = up
vec0 = normalize(np.cross(vec1_avg, vec2))
vec1 = normalize(np.cross(vec2, vec0))
m = np.stack([vec0, vec1, vec2, pos], 1)
return m
def poses_avg(poses):
hwf = poses[0, :3, -1:]
center = poses[:, :3, 3].mean(0)
vec2 = normalize(poses[:, :3, 2].sum(0))
up = poses[:, :3, 1].sum(0)
c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1)
return c2w
def recenter_poses(poses):
poses_ = poses+0
bottom = np.reshape([0,0,0,1.], [1,4])
c2w = poses_avg(poses)
c2w = np.concatenate([c2w[:3,:4], bottom], -2)
bottom = np.tile(np.reshape(bottom, [1,1,4]), [poses.shape[0],1,1])
poses = np.concatenate([poses[:,:3,:4], bottom], -2)
poses = np.linalg.inv(c2w) @ poses
poses_[:,:3,:4] = poses[:,:3,:4]
poses = poses_
return poses, c2w
class WaymoDataset(DatasetBase):
"""
NeRF dataset loader
"""
focal: float
c2w: torch.Tensor # (n_images, 4, 4)
gt: torch.Tensor # (n_images, h, w, 3)
h: int
w: int
n_images: int
rays: Optional[Rays]
split: str
def __init__(
self,
root,
split,
epoch_size : Optional[int] = None,
device: Union[str, torch.device] = "cpu",
scene_scale: Optional[float] = None,
factor: int = 8,
scale : Optional[float] = None,
permutation: bool = True,
white_bkgd: bool = True,
n_images = None,
**kwargs
):
super().__init__()
assert path.isdir(root), f"'{root}' is not a directory"
if scene_scale is None:
scene_scale = 100.0
#scene_scale = 2/3
if scale is None:
scale = 1.0
self.device = device
self.permutation = permutation
self.epoch_size = epoch_size
all_c2w = []
all_gt = []
split_name = split if split != "test_train" else "train"
dataset=tf.data.TFRecordDataset('/home/xschen/yjcai/segment-10061305430875486848_1080_000_1100_000_with_camera_labels.tfrecord', compression_type='')
all_imgs, all_poses = [], []
for index, data in enumerate(dataset):
#if index>=30 :
# break
frame = open_dataset.Frame()
frame.ParseFromString(bytearray(data.numpy()))
''' image load '''
front_camera = frame.images[0]
data = frame.context
pose_vehicle2world = np.reshape(np.array(frame.pose.transform, np.float32), (4, 4))
img = (np.array(tf.image.decode_jpeg(front_camera.image)) / 255.).astype(np.float32)
if index == 0:
intrinsic = data.camera_calibrations[0].intrinsic
pose_camera2vehicle= np.array(data.camera_calibrations[0].extrinsic.transform,dtype=np.float32).reshape(4,4) #camera-vehicle from the sensor frame to the vehicle frame.
pose_vehicle2camera = np.linalg.inv(pose_camera2vehicle).astype(np.float32)
focal = intrinsic[0]
K = np.array([ \
[intrinsic[0], 0, intrinsic[2]], \
[0, intrinsic[0], intrinsic[3]], \
[0, 0, 1]], dtype=np.float32)
W, H = data.camera_calibrations[0].width, data.camera_calibrations[0].height
hwf = np.reshape([H, W, focal, 0], [4,1])
hwf = hwf[None,:]
undist_img = cv2.undistort(img, K, np.asarray(intrinsic[4:9]), None, K)
pose_camera2world = pose_vehicle2world @ pose_camera2vehicle
all_imgs.append(undist_img)
all_poses.append(pose_camera2world)
self.split = split
if self.split == "train":
self.gt = torch.from_numpy(np.asarray(all_imgs, dtype=np.float32)).cuda()
imgs = np.asarray(all_imgs, dtype=np.float32)
poses = np.asarray(all_poses, dtype=np.float32)
poses = np.concatenate([-poses[:, :, 1:2], poses[:, :, 2:3], -poses[:, :, 0:1], poses[:, :, 3:4]/scene_scale], 2)
self.n_images, self.h_full, self.w_full, _ = imgs.shape
#self.n_images, self.h_full, self.w_full, _ = self.gt.shape
hwf = np.repeat(hwf, self.n_images, axis=0)
poses = np.concatenate([poses, hwf], 2)
poses, _ = recenter_poses(poses)
self.c2w = torch.from_numpy(poses[:,:,:4]).float().cuda()
self.intrins_full : Intrin = Intrin(focal, focal,
intrinsic[2],
intrinsic[3])
self.scene_scale = scene_scale
if self.split == "train":
self.gen_rays(factor=factor)
else:
# Rays are not needed for testing
self.h, self.w = self.h_full//factor, self.w_full//factor
#self.intrins : Intrin = self.intrins_full
self.intrins : Intrin = Intrin(focal/factor, focal/factor,
intrinsic[2]/factor,
intrinsic[3]/factor)
imgs_half_res = np.zeros((imgs.shape[0], self.h, self.w, 3))
for i, img in enumerate(imgs):
imgs_half_res[i] = cv2.resize(img, (self.w, self.h), interpolation=cv2.INTER_AREA)
self.gt = torch.from_numpy(np.asarray(imgs_half_res, dtype=np.float32)).cuda()
print (self.split)
print (self.h, self.w)
print (self.intrins)
self.should_use_background = False # Give warning
| # Standard NeRF Blender dataset loader
from .util import Rays, Intrin, select_or_shuffle_rays
from .dataset_base import DatasetBase
import torch
import torch.nn.functional as F
from typing import NamedTuple, Optional, Union
from os import path
import imageio
from tqdm import tqdm
import cv2
import json
import numpy as np
# import tensorflow.compat.v1 as tf
import tensorflow as tf
torch.set_default_tensor_type('torch.cuda.FloatTensor')
#tf.enable_eager_execution()
# from waymo_open_dataset.utils import range_image_utils
# from waymo_open_dataset.utils import transform_utils
# from waymo_open_dataset.utils import frame_utils
from waymo_open_dataset import dataset_pb2 as open_dataset
def normalize(x):
return x / np.linalg.norm(x)
def viewmatrix(z, up, pos):
vec2 = normalize(z)
vec1_avg = up
vec0 = normalize(np.cross(vec1_avg, vec2))
vec1 = normalize(np.cross(vec2, vec0))
m = np.stack([vec0, vec1, vec2, pos], 1)
return m
def poses_avg(poses):
hwf = poses[0, :3, -1:]
center = poses[:, :3, 3].mean(0)
vec2 = normalize(poses[:, :3, 2].sum(0))
up = poses[:, :3, 1].sum(0)
c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1)
return c2w
def recenter_poses(poses):
poses_ = poses+0
bottom = np.reshape([0,0,0,1.], [1,4])
c2w = poses_avg(poses)
c2w = np.concatenate([c2w[:3,:4], bottom], -2)
bottom = np.tile(np.reshape(bottom, [1,1,4]), [poses.shape[0],1,1])
poses = np.concatenate([poses[:,:3,:4], bottom], -2)
poses = np.linalg.inv(c2w) @ poses
poses_[:,:3,:4] = poses[:,:3,:4]
poses = poses_
return poses, c2w
class WaymoDataset(DatasetBase):
"""
NeRF dataset loader
"""
focal: float
c2w: torch.Tensor # (n_images, 4, 4)
gt: torch.Tensor # (n_images, h, w, 3)
h: int
w: int
n_images: int
rays: Optional[Rays]
split: str
def __init__(
self,
root,
split,
epoch_size : Optional[int] = None,
device: Union[str, torch.device] = "cpu",
scene_scale: Optional[float] = None,
factor: int = 8,
scale : Optional[float] = None,
permutation: bool = True,
white_bkgd: bool = True,
n_images = None,
**kwargs
):
super().__init__()
assert path.isdir(root), f"'{root}' is not a directory"
if scene_scale is None:
scene_scale = 100.0
#scene_scale = 2/3
if scale is None:
scale = 1.0
self.device = device
self.permutation = permutation
self.epoch_size = epoch_size
all_c2w = []
all_gt = []
split_name = split if split != "test_train" else "train"
dataset=tf.data.TFRecordDataset('/home/xschen/yjcai/segment-10061305430875486848_1080_000_1100_000_with_camera_labels.tfrecord', compression_type='')
all_imgs, all_poses = [], []
for index, data in enumerate(dataset):
#if index>=30 :
# break
frame = open_dataset.Frame()
frame.ParseFromString(bytearray(data.numpy()))
''' image load '''
front_camera = frame.images[0]
data = frame.context
pose_vehicle2world = np.reshape(np.array(frame.pose.transform, np.float32), (4, 4))
img = (np.array(tf.image.decode_jpeg(front_camera.image)) / 255.).astype(np.float32)
if index == 0:
intrinsic = data.camera_calibrations[0].intrinsic
pose_camera2vehicle= np.array(data.camera_calibrations[0].extrinsic.transform,dtype=np.float32).reshape(4,4) #camera-vehicle from the sensor frame to the vehicle frame.
pose_vehicle2camera = np.linalg.inv(pose_camera2vehicle).astype(np.float32)
focal = intrinsic[0]
K = np.array([ \
[intrinsic[0], 0, intrinsic[2]], \
[0, intrinsic[0], intrinsic[3]], \
[0, 0, 1]], dtype=np.float32)
W, H = data.camera_calibrations[0].width, data.camera_calibrations[0].height
hwf = np.reshape([H, W, focal, 0], [4,1])
hwf = hwf[None,:]
undist_img = cv2.undistort(img, K, np.asarray(intrinsic[4:9]), None, K)
pose_camera2world = pose_vehicle2world @ pose_camera2vehicle
all_imgs.append(undist_img)
all_poses.append(pose_camera2world)
self.split = split
if self.split == "train":
self.gt = torch.from_numpy(np.asarray(all_imgs, dtype=np.float32)).cuda()
imgs = np.asarray(all_imgs, dtype=np.float32)
poses = np.asarray(all_poses, dtype=np.float32)
poses = np.concatenate([-poses[:, :, 1:2], poses[:, :, 2:3], -poses[:, :, 0:1], poses[:, :, 3:4]/scene_scale], 2)
self.n_images, self.h_full, self.w_full, _ = imgs.shape
#self.n_images, self.h_full, self.w_full, _ = self.gt.shape
hwf = np.repeat(hwf, self.n_images, axis=0)
poses = np.concatenate([poses, hwf], 2)
poses, _ = recenter_poses(poses)
self.c2w = torch.from_numpy(poses[:,:,:4]).float().cuda()
self.intrins_full : Intrin = Intrin(focal, focal,
intrinsic[2],
intrinsic[3])
self.scene_scale = scene_scale
if self.split == "train":
self.gen_rays(factor=factor)
else:
# Rays are not needed for testing
self.h, self.w = self.h_full//factor, self.w_full//factor
#self.intrins : Intrin = self.intrins_full
self.intrins : Intrin = Intrin(focal/factor, focal/factor,
intrinsic[2]/factor,
intrinsic[3]/factor)
imgs_half_res = np.zeros((imgs.shape[0], self.h, self.w, 3))
for i, img in enumerate(imgs):
imgs_half_res[i] = cv2.resize(img, (self.w, self.h), interpolation=cv2.INTER_AREA)
self.gt = torch.from_numpy(np.asarray(imgs_half_res, dtype=np.float32)).cuda()
print (self.split)
print (self.h, self.w)
print (self.intrins)
self.should_use_background = False # Give warning | en | 0.4912 | # Standard NeRF Blender dataset loader # import tensorflow.compat.v1 as tf #tf.enable_eager_execution() # from waymo_open_dataset.utils import range_image_utils # from waymo_open_dataset.utils import transform_utils # from waymo_open_dataset.utils import frame_utils NeRF dataset loader # (n_images, 4, 4) # (n_images, h, w, 3) #scene_scale = 2/3 #if index>=30 : # break image load #camera-vehicle from the sensor frame to the vehicle frame. #self.n_images, self.h_full, self.w_full, _ = self.gt.shape # Rays are not needed for testing #self.intrins : Intrin = self.intrins_full # Give warning | 1.739307 | 2 |
nlp/doc2vec/mergevec.py | ellieandallen/my-own-script | 0 | 6620372 | <filename>nlp/doc2vec/mergevec.py<gh_stars>0
# @author: lionheart
# Created on 2017-11-30
import os
import sys
import logging
import pickle
from itertools import groupby
from operator import itemgetter
def _merge_vec(vector):
vector = sorted(vector, key=itemgetter(0))
# vector = sorted(vector, key=lambda x: x[0])
# merge vectors of the same uid
result = []
for key, group in groupby(vector, lambda x: x[0]):
temp = []
for vec in group:
temp.extend(vec[1])
result.append([key, temp])
# add count of words
for i in range(0, len(result)):
temp = []
for a, b in groupby(sorted(result[i][1]), key=lambda item: item[0]):
temp.append((a, sum([item[1] for item in list(b)])))
result[i][1] = temp
return result
# def _uid_update(j, i):
# # sort a tuple list like [(212, 1), (1675, 1), (1696, 1), (497, 2)] to [(212, 1), (497, 2), (1675, 1), (1696, 1)]
# # use b = sorted(a, key=lambda tup: tup[0])
# length = len(j[1])
# if j[0] == i[0]:
# for k in range(0, length):
# if k[]
#
#
# def _uid_exist(v, i):
# for j in v:
# if j[0] == i[0]:
# return 1
# else:
# pass
# return 0
def merge_vec(merged_vector, fullname):
# read vector
with open(fullname, 'rb') as data_file:
sms_vector = pickle.load(data_file)
merged_vector.extend(sms_vector)
merged_vector = _merge_vec(merged_vector)
return merged_vector
if __name__ == '__main__':
program = os.path.basename(sys.argv[0]) # get file name
logger = logging.getLogger(program)
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
logging.root.setLevel(level=logging.INFO)
# input dir
inp = '/data'
foldername = 'sms_process2'
logger.info("running " + foldername + " files.")
rootdir = inp + '/' + foldername
merged = [] # init the merged vector
# 3 args:1.parent dir 2.all dir names(without path) 3.all file names
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
sms_file = rootdir + '/' + filename
logger.info("Dealing with file: " + sms_file)
merged = merge_vec(merged, sms_file)
with open('/data/sms_commonfiles/uid_vector.vec', 'wb') as vector_file:
pickle.dump(merged, vector_file, pickle.HIGHEST_PROTOCOL)
print 'game over'
| <filename>nlp/doc2vec/mergevec.py<gh_stars>0
# @author: lionheart
# Created on 2017-11-30
import os
import sys
import logging
import pickle
from itertools import groupby
from operator import itemgetter
def _merge_vec(vector):
vector = sorted(vector, key=itemgetter(0))
# vector = sorted(vector, key=lambda x: x[0])
# merge vectors of the same uid
result = []
for key, group in groupby(vector, lambda x: x[0]):
temp = []
for vec in group:
temp.extend(vec[1])
result.append([key, temp])
# add count of words
for i in range(0, len(result)):
temp = []
for a, b in groupby(sorted(result[i][1]), key=lambda item: item[0]):
temp.append((a, sum([item[1] for item in list(b)])))
result[i][1] = temp
return result
# def _uid_update(j, i):
# # sort a tuple list like [(212, 1), (1675, 1), (1696, 1), (497, 2)] to [(212, 1), (497, 2), (1675, 1), (1696, 1)]
# # use b = sorted(a, key=lambda tup: tup[0])
# length = len(j[1])
# if j[0] == i[0]:
# for k in range(0, length):
# if k[]
#
#
# def _uid_exist(v, i):
# for j in v:
# if j[0] == i[0]:
# return 1
# else:
# pass
# return 0
def merge_vec(merged_vector, fullname):
# read vector
with open(fullname, 'rb') as data_file:
sms_vector = pickle.load(data_file)
merged_vector.extend(sms_vector)
merged_vector = _merge_vec(merged_vector)
return merged_vector
if __name__ == '__main__':
program = os.path.basename(sys.argv[0]) # get file name
logger = logging.getLogger(program)
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
logging.root.setLevel(level=logging.INFO)
# input dir
inp = '/data'
foldername = 'sms_process2'
logger.info("running " + foldername + " files.")
rootdir = inp + '/' + foldername
merged = [] # init the merged vector
# 3 args:1.parent dir 2.all dir names(without path) 3.all file names
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
sms_file = rootdir + '/' + filename
logger.info("Dealing with file: " + sms_file)
merged = merge_vec(merged, sms_file)
with open('/data/sms_commonfiles/uid_vector.vec', 'wb') as vector_file:
pickle.dump(merged, vector_file, pickle.HIGHEST_PROTOCOL)
print 'game over'
| en | 0.59862 | # @author: lionheart # Created on 2017-11-30 # vector = sorted(vector, key=lambda x: x[0]) # merge vectors of the same uid # add count of words # def _uid_update(j, i): # # sort a tuple list like [(212, 1), (1675, 1), (1696, 1), (497, 2)] to [(212, 1), (497, 2), (1675, 1), (1696, 1)] # # use b = sorted(a, key=lambda tup: tup[0]) # length = len(j[1]) # if j[0] == i[0]: # for k in range(0, length): # if k[] # # # def _uid_exist(v, i): # for j in v: # if j[0] == i[0]: # return 1 # else: # pass # return 0 # read vector # get file name # input dir # init the merged vector # 3 args:1.parent dir 2.all dir names(without path) 3.all file names | 2.931659 | 3 |
Mundo 01 e 02/Desconto.py | AlanyLourenco/Python | 0 | 6620373 | <filename>Mundo 01 e 02/Desconto.py
n=int(input('Digite um valor : '))
d=n-(n*0.05)
print('O novo valor do produro é RS{:.2f}'.format(d))
| <filename>Mundo 01 e 02/Desconto.py
n=int(input('Digite um valor : '))
d=n-(n*0.05)
print('O novo valor do produro é RS{:.2f}'.format(d))
| none | 1 | 3.413755 | 3 | |
tests/i2b2modeltests/metadatatests/test_modifier_dimension.py | BD2KOnFHIR/i2b2model | 1 | 6620374 | <reponame>BD2KOnFHIR/i2b2model<gh_stars>1-10
import unittest
from collections import OrderedDict
from datetime import datetime
from dynprops import as_dict, clear
from i2b2model.shared.i2b2core import I2B2Core
from i2b2model.testingutils.base_test_case import BaseTestCase
class ModifierDimensionTestCase(BaseTestCase):
def setUp(self):
clear(I2B2Core)
def tearDown(self):
clear(I2B2Core)
def test_basics(self):
from i2b2model.metadata.i2b2modifierdimension import ModifierDimension
I2B2Core.download_date = datetime(2017, 5, 25)
I2B2Core.sourcesystem_cd = "MOD_TEST"
I2B2Core.import_date = datetime(2017, 5, 25)
md = ModifierDimension('MODTEST', 'baboon', 'Wild baboons', ['Earth', 'Africa', 'Zimbabwai'])
self.assertAlmostNow(md.update_date)
I2B2Core.update_date = datetime(2001, 12, 1)
expected = OrderedDict([
('modifier_path', '\\Earth\\Africa\\Zimbabwai\\baboon\\'),
('modifier_cd', 'MODTEST:baboon'),
('name_char', 'MODTEST Wild baboons'),
('modifier_blob', ''),
('update_date', datetime(2001, 12, 1, 0, 0)),
('download_date', datetime(2017, 5, 25, 0, 0)),
('import_date', datetime(2017, 5, 25, 0, 0)),
('sourcesystem_cd', 'MOD_TEST'),
('upload_id', None)])
self.assertEqual(expected, as_dict(md))
if __name__ == '__main__':
unittest.main()
| import unittest
from collections import OrderedDict
from datetime import datetime
from dynprops import as_dict, clear
from i2b2model.shared.i2b2core import I2B2Core
from i2b2model.testingutils.base_test_case import BaseTestCase
class ModifierDimensionTestCase(BaseTestCase):
def setUp(self):
clear(I2B2Core)
def tearDown(self):
clear(I2B2Core)
def test_basics(self):
from i2b2model.metadata.i2b2modifierdimension import ModifierDimension
I2B2Core.download_date = datetime(2017, 5, 25)
I2B2Core.sourcesystem_cd = "MOD_TEST"
I2B2Core.import_date = datetime(2017, 5, 25)
md = ModifierDimension('MODTEST', 'baboon', 'Wild baboons', ['Earth', 'Africa', 'Zimbabwai'])
self.assertAlmostNow(md.update_date)
I2B2Core.update_date = datetime(2001, 12, 1)
expected = OrderedDict([
('modifier_path', '\\Earth\\Africa\\Zimbabwai\\baboon\\'),
('modifier_cd', 'MODTEST:baboon'),
('name_char', 'MODTEST Wild baboons'),
('modifier_blob', ''),
('update_date', datetime(2001, 12, 1, 0, 0)),
('download_date', datetime(2017, 5, 25, 0, 0)),
('import_date', datetime(2017, 5, 25, 0, 0)),
('sourcesystem_cd', 'MOD_TEST'),
('upload_id', None)])
self.assertEqual(expected, as_dict(md))
if __name__ == '__main__':
unittest.main() | none | 1 | 2.522855 | 3 | |
Backend/dummy_consumer/dummyfrontend.py | horizonfleet/horizon | 0 | 6620375 | from pykafka import KafkaClient
from pykafka.common import OffsetType
# Process incoming Data
def consume_message():
client = KafkaClient(hosts="kafka:9092")
topic = client.topics["frontend"]
consumer = topic.get_simple_consumer(auto_offset_reset=OffsetType.LATEST, reset_offset_on_start=True)
for message in consumer:
if message is not None:
print(message.value.decode())
consume_message() | from pykafka import KafkaClient
from pykafka.common import OffsetType
# Process incoming Data
def consume_message():
client = KafkaClient(hosts="kafka:9092")
topic = client.topics["frontend"]
consumer = topic.get_simple_consumer(auto_offset_reset=OffsetType.LATEST, reset_offset_on_start=True)
for message in consumer:
if message is not None:
print(message.value.decode())
consume_message() | en | 0.649288 | # Process incoming Data | 2.757098 | 3 |
akaocr/utils/data/collates.py | qai-research/Efficient_Text_Detection | 2 | 6620376 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By : <NAME> - Bacnv6, <NAME> - Trangnm5
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
_____________________________________________________________________________
This file contain collate classes which convert data to torch array and other
operations.
_____________________________________________________________________________
"""
import os
import json
import math
from PIL import Image
import numpy as np
import torch
import torchvision.transforms as transforms
from utils.transforms.gaussian import GaussianTransformer
from utils.transforms.heatproc import transform2heatmap
class AlignCollate(object):
def __init__(self, img_h=32, img_w=254, keep_ratio_with_pad=True):
"""
Custom collate function for normalize image
:param img_h: image height
:param img_w: image width
:param keep_ratio_with_pad: pad image with 0
"""
self.img_h = img_h
self.img_w = img_w
self.keep_ratio_with_pad = keep_ratio_with_pad
def __call__(self, batch):
batch = filter(lambda x: x is not None, batch)
images, labels = zip(*batch)
if self.keep_ratio_with_pad: # same concept with 'Rosetta' paper
resized_max_w = self.img_w
input_channel = 3 if images[0].mode == 'RGB' else 1
transform = NormalizePAD((input_channel, self.img_h, resized_max_w))
resized_images = []
for image in images:
w, h = image.size
ratio = w / float(h)
if math.ceil(self.img_h * ratio) > self.img_w:
resized_w = self.img_w
else:
resized_w = math.ceil(self.img_h * ratio)
resized_image = transform(image.resize((resized_w, self.img_h), Image.BICUBIC))
resized_images.append(resized_image)
image_tensors = torch.cat([t.unsqueeze(0) for t in resized_images], 0)
else:
transform = ResizeNormalize((self.img_w, self.img_h))
image_tensors = [transform(image) for image in images]
image_tensors = torch.cat([t.unsqueeze(0) for t in image_tensors], 0)
return image_tensors, labels
class ResizeNormalize(object):
def __init__(self, size, interpolation=Image.BICUBIC):
"""
Resizing input images by stretching them
:param size: width of output image
:param interpolation: type of interpolate
"""
self.size = size
self.interpolation = interpolation
self.toTensor = transforms.ToTensor()
def __call__(self, img):
img = img.resize(self.size, self.interpolation)
img = self.toTensor(img)
img.sub_(0.5).div_(0.5) # [0, 1] => [-1, 1]
return img
class NormalizePAD(object):
def __init__(self, max_size, pad_type='right'):
"""
Resizing input images by padding with zeros
:param max_size: width of output image
:param pad_type: direction to pad image
"""
self.toTensor = transforms.ToTensor()
self.max_size = max_size
self.max_width_half = math.floor(max_size[2] / 2)
self.PAD_type = pad_type
def __call__(self, img):
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
c, h, w = img.size()
pad_img = torch.FloatTensor(*self.max_size).fill_(0)
pad_img[:, :, :w] = img # right pad
if self.max_size[2] != w: # add border Pad
pad_img[:, :, w:] = img[:, :, w - 1].unsqueeze(2).expand(c, h, self.max_size[2] - w)
return pad_img
class GaussianCollate(object):
def __init__(self, min_size, max_size):
"""
Return label in heatmap representation
:param min_size: min image size
:param max_size: max image size
"""
self.gaussian_transformer = GaussianTransformer(img_size=512, region_threshold=0.35, affinity_threshold=0.15)
self.min_size = min_size
self.max_size = max_size
def __call__(self, batch):
batch = filter(lambda x: x is not None, batch)
images, labels = zip(*batch)
images_proc = list()
regions_proc = list()
affinities_proc = list()
confidences_proc = list()
for img, label in zip(images, labels):
img = np.array(img)
heat_data = transform2heatmap(img, label,
self.gaussian_transformer,
self.min_size, self.max_size)
img, region_scores, affinity_scores, confidence_mask, confidences = heat_data
img = torch.from_numpy(img).float().permute(2, 0, 1)
region_scores_torch = torch.from_numpy(region_scores / 255).float()
affinity_scores_torch = torch.from_numpy(affinity_scores / 255).float()
confidence_mask_torch = torch.from_numpy(confidence_mask).float()
images_proc.append(img)
regions_proc.append(region_scores_torch)
affinities_proc.append(affinity_scores_torch)
confidences_proc.append(confidence_mask_torch)
image_tensors = torch.cat([t.unsqueeze(0) for t in images_proc], 0)
region_tensors = torch.cat([t.unsqueeze(0) for t in regions_proc], 0)
affinity_tensors = torch.cat([t.unsqueeze(0) for t in affinities_proc], 0)
confidence_tensors = torch.cat([t.unsqueeze(0) for t in confidences_proc], 0)
return image_tensors, region_tensors, affinity_tensors, confidence_tensors
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By : <NAME> - Bacnv6, <NAME> - Trangnm5
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
_____________________________________________________________________________
This file contain collate classes which convert data to torch array and other
operations.
_____________________________________________________________________________
"""
import os
import json
import math
from PIL import Image
import numpy as np
import torch
import torchvision.transforms as transforms
from utils.transforms.gaussian import GaussianTransformer
from utils.transforms.heatproc import transform2heatmap
class AlignCollate(object):
def __init__(self, img_h=32, img_w=254, keep_ratio_with_pad=True):
"""
Custom collate function for normalize image
:param img_h: image height
:param img_w: image width
:param keep_ratio_with_pad: pad image with 0
"""
self.img_h = img_h
self.img_w = img_w
self.keep_ratio_with_pad = keep_ratio_with_pad
def __call__(self, batch):
batch = filter(lambda x: x is not None, batch)
images, labels = zip(*batch)
if self.keep_ratio_with_pad: # same concept with 'Rosetta' paper
resized_max_w = self.img_w
input_channel = 3 if images[0].mode == 'RGB' else 1
transform = NormalizePAD((input_channel, self.img_h, resized_max_w))
resized_images = []
for image in images:
w, h = image.size
ratio = w / float(h)
if math.ceil(self.img_h * ratio) > self.img_w:
resized_w = self.img_w
else:
resized_w = math.ceil(self.img_h * ratio)
resized_image = transform(image.resize((resized_w, self.img_h), Image.BICUBIC))
resized_images.append(resized_image)
image_tensors = torch.cat([t.unsqueeze(0) for t in resized_images], 0)
else:
transform = ResizeNormalize((self.img_w, self.img_h))
image_tensors = [transform(image) for image in images]
image_tensors = torch.cat([t.unsqueeze(0) for t in image_tensors], 0)
return image_tensors, labels
class ResizeNormalize(object):
def __init__(self, size, interpolation=Image.BICUBIC):
"""
Resizing input images by stretching them
:param size: width of output image
:param interpolation: type of interpolate
"""
self.size = size
self.interpolation = interpolation
self.toTensor = transforms.ToTensor()
def __call__(self, img):
img = img.resize(self.size, self.interpolation)
img = self.toTensor(img)
img.sub_(0.5).div_(0.5) # [0, 1] => [-1, 1]
return img
class NormalizePAD(object):
def __init__(self, max_size, pad_type='right'):
"""
Resizing input images by padding with zeros
:param max_size: width of output image
:param pad_type: direction to pad image
"""
self.toTensor = transforms.ToTensor()
self.max_size = max_size
self.max_width_half = math.floor(max_size[2] / 2)
self.PAD_type = pad_type
def __call__(self, img):
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
c, h, w = img.size()
pad_img = torch.FloatTensor(*self.max_size).fill_(0)
pad_img[:, :, :w] = img # right pad
if self.max_size[2] != w: # add border Pad
pad_img[:, :, w:] = img[:, :, w - 1].unsqueeze(2).expand(c, h, self.max_size[2] - w)
return pad_img
class GaussianCollate(object):
def __init__(self, min_size, max_size):
"""
Return label in heatmap representation
:param min_size: min image size
:param max_size: max image size
"""
self.gaussian_transformer = GaussianTransformer(img_size=512, region_threshold=0.35, affinity_threshold=0.15)
self.min_size = min_size
self.max_size = max_size
def __call__(self, batch):
batch = filter(lambda x: x is not None, batch)
images, labels = zip(*batch)
images_proc = list()
regions_proc = list()
affinities_proc = list()
confidences_proc = list()
for img, label in zip(images, labels):
img = np.array(img)
heat_data = transform2heatmap(img, label,
self.gaussian_transformer,
self.min_size, self.max_size)
img, region_scores, affinity_scores, confidence_mask, confidences = heat_data
img = torch.from_numpy(img).float().permute(2, 0, 1)
region_scores_torch = torch.from_numpy(region_scores / 255).float()
affinity_scores_torch = torch.from_numpy(affinity_scores / 255).float()
confidence_mask_torch = torch.from_numpy(confidence_mask).float()
images_proc.append(img)
regions_proc.append(region_scores_torch)
affinities_proc.append(affinity_scores_torch)
confidences_proc.append(confidence_mask_torch)
image_tensors = torch.cat([t.unsqueeze(0) for t in images_proc], 0)
region_tensors = torch.cat([t.unsqueeze(0) for t in regions_proc], 0)
affinity_tensors = torch.cat([t.unsqueeze(0) for t in affinities_proc], 0)
confidence_tensors = torch.cat([t.unsqueeze(0) for t in confidences_proc], 0)
return image_tensors, region_tensors, affinity_tensors, confidence_tensors
| en | 0.583161 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- _____________________________________________________________________________
Created By : <NAME> - Bacnv6, <NAME> - Trangnm5
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
_____________________________________________________________________________
This file contain collate classes which convert data to torch array and other
operations.
_____________________________________________________________________________ Custom collate function for normalize image
:param img_h: image height
:param img_w: image width
:param keep_ratio_with_pad: pad image with 0 # same concept with 'Rosetta' paper Resizing input images by stretching them
:param size: width of output image
:param interpolation: type of interpolate # [0, 1] => [-1, 1] Resizing input images by padding with zeros
:param max_size: width of output image
:param pad_type: direction to pad image # right pad # add border Pad Return label in heatmap representation
:param min_size: min image size
:param max_size: max image size | 2.24678 | 2 |
catalogService/utils/x509.py | sassoftware/-catalog-service | 3 | 6620377 | #
# Copyright (c) SAS Institute 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.
#
"Simple module for generating x509 certificates"
import os
from rmake3.lib import gencert
class X509(object):
class Options(object):
__slots__ = ['C', 'ST', 'L', 'O', 'OU', 'CN', 'site_user',
'key_length', 'expiry', 'output', 'output_key']
_defaults = dict(key_length = 2048, expiry = 10 * 365)
def __init__(self, **kwargs):
params = self._defaults.copy()
params.update(kwargs)
# Initialize from slots
for slot in self.__slots__:
val = params.get(slot, None)
setattr(self, slot, val)
@classmethod
def new(cls, commonName, certDir):
"""
Generate X509 certificate with the specified commonName
Returns absolute paths to cert file and key file
"""
o = cls.Options(CN = commonName)
subject, extensions = gencert.name_from_options(o)
rsa, x509 = gencert.new_cert(o.key_length,
subject, o.expiry, isCA=False, extensions=extensions,
timestamp_offset=-86400)
certHash = cls.computeHashFromX509(x509)
certFile = os.path.join(certDir, certHash + '.0')
keyFile = os.path.join(certDir, certHash + '.0.key')
o.output = certFile
o.output_key = keyFile
gencert.writeCert(o, rsa, x509)
return certFile, keyFile
@classmethod
def load(cls, certFile):
x509 = gencert.X509.load_cert(certFile)
return x509
@classmethod
def computeHash(cls, certFile):
x509 = cls.load(certFile)
return cls.computeHashFromX509(x509)
@classmethod
def computeHashFromX509(cls, x509):
certHash = "%08x" % x509.get_issuer().as_hash()
return certHash
| #
# Copyright (c) SAS Institute 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.
#
"Simple module for generating x509 certificates"
import os
from rmake3.lib import gencert
class X509(object):
class Options(object):
__slots__ = ['C', 'ST', 'L', 'O', 'OU', 'CN', 'site_user',
'key_length', 'expiry', 'output', 'output_key']
_defaults = dict(key_length = 2048, expiry = 10 * 365)
def __init__(self, **kwargs):
params = self._defaults.copy()
params.update(kwargs)
# Initialize from slots
for slot in self.__slots__:
val = params.get(slot, None)
setattr(self, slot, val)
@classmethod
def new(cls, commonName, certDir):
"""
Generate X509 certificate with the specified commonName
Returns absolute paths to cert file and key file
"""
o = cls.Options(CN = commonName)
subject, extensions = gencert.name_from_options(o)
rsa, x509 = gencert.new_cert(o.key_length,
subject, o.expiry, isCA=False, extensions=extensions,
timestamp_offset=-86400)
certHash = cls.computeHashFromX509(x509)
certFile = os.path.join(certDir, certHash + '.0')
keyFile = os.path.join(certDir, certHash + '.0.key')
o.output = certFile
o.output_key = keyFile
gencert.writeCert(o, rsa, x509)
return certFile, keyFile
@classmethod
def load(cls, certFile):
x509 = gencert.X509.load_cert(certFile)
return x509
@classmethod
def computeHash(cls, certFile):
x509 = cls.load(certFile)
return cls.computeHashFromX509(x509)
@classmethod
def computeHashFromX509(cls, x509):
certHash = "%08x" % x509.get_issuer().as_hash()
return certHash
| en | 0.845838 | # # Copyright (c) SAS Institute 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. # # Initialize from slots Generate X509 certificate with the specified commonName Returns absolute paths to cert file and key file | 1.96306 | 2 |
tests/MPUSensor/MPUSensorTest.py | murrayireland/Rover-Code | 0 | 6620378 | #!/usr/bin/env python
"""MPUSensorTest.py: Receives raw data from MPU 9DOF click IMU+Magnetometer and displays it."""
import smbus
import math
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def dist(a, b):
return math.sqrt((a*a) + (b*b))
def get_y_rotation(x, y, z):
radians = math.atan2(x, dist(y, z))
return -math.degrees(radians)
def get_x_rotation(x, y, z):
radians = math.atan2(y, dist(x, z))
return math.degrees(radians)
bus = smbus.SMBus(1) # or bus = smbus.SMBus(0) for Revision 1 boards
address = 0x69 # Address via i2cdetect
# Now wake up the IMU as it starts in sleep mode
bus.write_byte_data(address, power_mgmt_1, 0)
print "Gyro data"
print "---------"
gyro_xout = read_word_2c(0x43)
gyro_yout = read_word_2c(0x45)
gyro_zout = read_word_2c(0x47)
print "gyro_xout: {}, scaled: {}".format(gyro_xout, gyro_xout/131.0)
print "gyro_yout: {}, scaled: {}".format(gyro_yout, gyro_yout/131.0)
print "gyro_zout: {}, scaled: {}".format(gyro_zout, gyro_zout/131.0)
print
print "Accelerometer data"
print "------------------"
accel_xout = read_word_2c(0x3b)
accel_yout = read_word_2c(0x3d)
accel_zout = read_word_2c(0x3f)
accel_xout_scaled = accel_xout/16384.0
accel_yout_scaled = accel_yout/16384.0
accel_zout_scaled = accel_zout/16384.0
print "accel_xout: {}, scaled: {}".format(accel_xout, accel_xout_scaled)
print "accel_yout: {}, scaled: {}".format(accel_yout, accel_yout_scaled)
print "accel_zout: {}, scaled: {}".format(accel_zout, accel_zout_scaled)
print "x rotation: {}".format(get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
print "y rotation: {}".format(get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
| #!/usr/bin/env python
"""MPUSensorTest.py: Receives raw data from MPU 9DOF click IMU+Magnetometer and displays it."""
import smbus
import math
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def dist(a, b):
return math.sqrt((a*a) + (b*b))
def get_y_rotation(x, y, z):
radians = math.atan2(x, dist(y, z))
return -math.degrees(radians)
def get_x_rotation(x, y, z):
radians = math.atan2(y, dist(x, z))
return math.degrees(radians)
bus = smbus.SMBus(1) # or bus = smbus.SMBus(0) for Revision 1 boards
address = 0x69 # Address via i2cdetect
# Now wake up the IMU as it starts in sleep mode
bus.write_byte_data(address, power_mgmt_1, 0)
print "Gyro data"
print "---------"
gyro_xout = read_word_2c(0x43)
gyro_yout = read_word_2c(0x45)
gyro_zout = read_word_2c(0x47)
print "gyro_xout: {}, scaled: {}".format(gyro_xout, gyro_xout/131.0)
print "gyro_yout: {}, scaled: {}".format(gyro_yout, gyro_yout/131.0)
print "gyro_zout: {}, scaled: {}".format(gyro_zout, gyro_zout/131.0)
print
print "Accelerometer data"
print "------------------"
accel_xout = read_word_2c(0x3b)
accel_yout = read_word_2c(0x3d)
accel_zout = read_word_2c(0x3f)
accel_xout_scaled = accel_xout/16384.0
accel_yout_scaled = accel_yout/16384.0
accel_zout_scaled = accel_zout/16384.0
print "accel_xout: {}, scaled: {}".format(accel_xout, accel_xout_scaled)
print "accel_yout: {}, scaled: {}".format(accel_yout, accel_yout_scaled)
print "accel_zout: {}, scaled: {}".format(accel_zout, accel_zout_scaled)
print "x rotation: {}".format(get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
print "y rotation: {}".format(get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
| en | 0.72702 | #!/usr/bin/env python MPUSensorTest.py: Receives raw data from MPU 9DOF click IMU+Magnetometer and displays it. # Power management registers # or bus = smbus.SMBus(0) for Revision 1 boards # Address via i2cdetect # Now wake up the IMU as it starts in sleep mode | 2.95034 | 3 |
jmetal/util/test/test_replacement.py | 12yuens2/jMetalPy | 335 | 6620379 | import unittest
from jmetal.core.solution import Solution
from jmetal.util.density_estimator import KNearestNeighborDensityEstimator
from jmetal.util.ranking import StrengthRanking, FastNonDominatedRanking
from jmetal.util.replacement import RankingAndDensityEstimatorReplacement
class RankingAndDensityEstimatorReplacementTestCases(unittest.TestCase):
def test_should_replacement_return_the_list_if_the_offspring_list_is_empty(self):
"""
5 1
4 2
3 3
2
1 4
0 1 2 3 4 5
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution_list = [solution1, solution2, solution3, solution4]
result_list = replacement.replace(solution_list, [])
self.assertEqual(4, len(result_list))
self.assertEqual(0, solution1.attributes['strength_ranking'])
self.assertEqual(0, solution2.attributes['strength_ranking'])
self.assertEqual(0, solution3.attributes['strength_ranking'])
self.assertEqual(0, solution4.attributes['strength_ranking'])
def test_should_replacement_return_the_right_value_case1(self):
"""
5 1
4 2
3 3
2
1 4
0 1 2 3 4 5
List: 1,2,3 OffspringList: 4
Expected result: 4, 1, 3
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution_list = [solution1, solution2, solution3]
offspring_list = [solution4]
result_list = replacement.replace(solution_list, offspring_list)
self.assertEqual(3, len(result_list))
self.assertTrue(solution1 in result_list)
self.assertTrue(solution3 in result_list)
self.assertTrue(solution4 in result_list)
def test_should_replacement_return_the_right_value_case2(self):
"""
5 1
4 2
3 3
2 5
1 4
0 1 2 3 4 5
List: 1,2,4 OffspringList: 3,5
Expected result: 1, 5, 4
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution5 = Solution(2, 2)
solution5.objectives = [2.5, 2.5]
solution_list = [solution1, solution2, solution4]
offspring_list = [solution3, solution5]
result_list = replacement.replace(solution_list, offspring_list)
self.assertEqual(0, solution1.attributes['strength_ranking'])
self.assertEqual(0, solution2.attributes['strength_ranking'])
self.assertEqual(1, solution3.attributes['strength_ranking'])
self.assertEqual(0, solution4.attributes['strength_ranking'])
self.assertEqual(0, solution5.attributes['strength_ranking'])
self.assertEqual(3, len(result_list))
self.assertTrue(solution1 in result_list)
self.assertTrue(solution5 in result_list)
self.assertTrue(solution4 in result_list)
def test_should_replacement_return_the_right_value_case3(self):
"""
"""
points_population = [[0.13436424411240122, 4.323216008886963],
[0.23308445025757263, 4.574937990387161],
[0.17300740157905092, 4.82329350808847],
[0.9571162814602269, 3.443495331489301],
[0.25529404008730594, 3.36387501100745],
[0.020818108509287336, 5.1051826661880515],
[0.8787178982088466, 3.2716009445324103],
[0.6744550697237632, 3.901350307095427],
[0.7881164487252263, 3.1796004913916516],
[0.1028341459863098, 4.9409270526888935]]
points_offspring_population = [[0.3150521745650882, 4.369120371847888],
[0.8967291504209932, 2.506948771242972],
[0.6744550697237632, 3.9361442668874504],
[0.9571162814602269, 3.4388386707431433],
[0.13436424411240122, 4.741872175943253],
[0.25529404008730594, 2.922302861104415],
[0.23308445025757263, 4.580180404770213],
[0.23308445025757263, 4.591260299892424],
[0.9571162814602269, 2.9865495383518694],
[0.25529404008730594, 3.875587748122183]]
ranking = FastNonDominatedRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
population = []
for i in range(len(points_population)):
population.append(Solution(2, 2))
population[i].objectives = points_population[i]
offspring_population = []
for i in range(len(points_offspring_population)):
offspring_population.append(Solution(2, 2))
offspring_population[i].objectives = points_offspring_population[i]
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
result_list = replacement.replace(population, offspring_population)
self.assertEqual(10,len(result_list))
for solution in result_list[0:4]:
self.assertEqual(0, solution.attributes['dominance_ranking'])
for solution in result_list[5:9]:
self.assertEqual(1, solution.attributes['dominance_ranking'])
if __name__ == '__main__':
unittest.main()
| import unittest
from jmetal.core.solution import Solution
from jmetal.util.density_estimator import KNearestNeighborDensityEstimator
from jmetal.util.ranking import StrengthRanking, FastNonDominatedRanking
from jmetal.util.replacement import RankingAndDensityEstimatorReplacement
class RankingAndDensityEstimatorReplacementTestCases(unittest.TestCase):
def test_should_replacement_return_the_list_if_the_offspring_list_is_empty(self):
"""
5 1
4 2
3 3
2
1 4
0 1 2 3 4 5
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution_list = [solution1, solution2, solution3, solution4]
result_list = replacement.replace(solution_list, [])
self.assertEqual(4, len(result_list))
self.assertEqual(0, solution1.attributes['strength_ranking'])
self.assertEqual(0, solution2.attributes['strength_ranking'])
self.assertEqual(0, solution3.attributes['strength_ranking'])
self.assertEqual(0, solution4.attributes['strength_ranking'])
def test_should_replacement_return_the_right_value_case1(self):
"""
5 1
4 2
3 3
2
1 4
0 1 2 3 4 5
List: 1,2,3 OffspringList: 4
Expected result: 4, 1, 3
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution_list = [solution1, solution2, solution3]
offspring_list = [solution4]
result_list = replacement.replace(solution_list, offspring_list)
self.assertEqual(3, len(result_list))
self.assertTrue(solution1 in result_list)
self.assertTrue(solution3 in result_list)
self.assertTrue(solution4 in result_list)
def test_should_replacement_return_the_right_value_case2(self):
"""
5 1
4 2
3 3
2 5
1 4
0 1 2 3 4 5
List: 1,2,4 OffspringList: 3,5
Expected result: 1, 5, 4
"""
ranking = StrengthRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
solution1 = Solution(2, 2)
solution1.objectives = [1, 5]
solution2 = Solution(2, 2)
solution2.objectives = [2, 4]
solution3 = Solution(2, 2)
solution3.objectives = [3, 3]
solution4 = Solution(2, 2)
solution4.objectives = [5, 1]
solution5 = Solution(2, 2)
solution5.objectives = [2.5, 2.5]
solution_list = [solution1, solution2, solution4]
offspring_list = [solution3, solution5]
result_list = replacement.replace(solution_list, offspring_list)
self.assertEqual(0, solution1.attributes['strength_ranking'])
self.assertEqual(0, solution2.attributes['strength_ranking'])
self.assertEqual(1, solution3.attributes['strength_ranking'])
self.assertEqual(0, solution4.attributes['strength_ranking'])
self.assertEqual(0, solution5.attributes['strength_ranking'])
self.assertEqual(3, len(result_list))
self.assertTrue(solution1 in result_list)
self.assertTrue(solution5 in result_list)
self.assertTrue(solution4 in result_list)
def test_should_replacement_return_the_right_value_case3(self):
"""
"""
points_population = [[0.13436424411240122, 4.323216008886963],
[0.23308445025757263, 4.574937990387161],
[0.17300740157905092, 4.82329350808847],
[0.9571162814602269, 3.443495331489301],
[0.25529404008730594, 3.36387501100745],
[0.020818108509287336, 5.1051826661880515],
[0.8787178982088466, 3.2716009445324103],
[0.6744550697237632, 3.901350307095427],
[0.7881164487252263, 3.1796004913916516],
[0.1028341459863098, 4.9409270526888935]]
points_offspring_population = [[0.3150521745650882, 4.369120371847888],
[0.8967291504209932, 2.506948771242972],
[0.6744550697237632, 3.9361442668874504],
[0.9571162814602269, 3.4388386707431433],
[0.13436424411240122, 4.741872175943253],
[0.25529404008730594, 2.922302861104415],
[0.23308445025757263, 4.580180404770213],
[0.23308445025757263, 4.591260299892424],
[0.9571162814602269, 2.9865495383518694],
[0.25529404008730594, 3.875587748122183]]
ranking = FastNonDominatedRanking()
density_estimator = KNearestNeighborDensityEstimator(1)
population = []
for i in range(len(points_population)):
population.append(Solution(2, 2))
population[i].objectives = points_population[i]
offspring_population = []
for i in range(len(points_offspring_population)):
offspring_population.append(Solution(2, 2))
offspring_population[i].objectives = points_offspring_population[i]
replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator)
result_list = replacement.replace(population, offspring_population)
self.assertEqual(10,len(result_list))
for solution in result_list[0:4]:
self.assertEqual(0, solution.attributes['dominance_ranking'])
for solution in result_list[5:9]:
self.assertEqual(1, solution.attributes['dominance_ranking'])
if __name__ == '__main__':
unittest.main()
| de | 0.168556 | 5 1 4 2 3 3 2 1 4 0 1 2 3 4 5 5 1 4 2 3 3 2 1 4 0 1 2 3 4 5 List: 1,2,3 OffspringList: 4 Expected result: 4, 1, 3 5 1 4 2 3 3 2 5 1 4 0 1 2 3 4 5 List: 1,2,4 OffspringList: 3,5 Expected result: 1, 5, 4 | 2.433715 | 2 |
fsm_eigenvalue/compute/core.py | petarmaric/fsm_eigenvalue | 1 | 6620380 | import physical_dualism as pd
import numpy as np
from .matrices import compute_global_matrices
from .utils import clip_small_eigenvalues, get_relative_error
def solve_eigenvalue_problem(inv_G, A, normalize_eigenvalues=None):
# As per eq. 6.48 from [Milasinovic1997]
H = inv_G * A * inv_G.T
eigenvalues, eigenvectors = np.linalg.eigh(H)
# Clip the extremely small eigenvalues
clip_small_eigenvalues(eigenvalues)
if normalize_eigenvalues:
eigenvalues = normalize_eigenvalues(eigenvalues)
# As per eq. 6.45 from [Milasinovic1997]
mode_shapes = inv_G.T * eigenvectors
# According to Milasinovic the minimal eigenvalue is the one closest to 0
min_idx = np.argmin(eigenvalues)
eigenvalue_min = eigenvalues[min_idx]
mode_shape_min = mode_shapes[:,min_idx].A1
return eigenvalue_min, mode_shape_min
def perform_iteration(integral_db, beam_type, strip_data, materials, astiff_shape, a, t_b, m):
K_hat, K_sigma, M = compute_global_matrices(
integral_db, beam_type, strip_data, materials, astiff_shape, a, t_b, m
)
# As per eq. 6.40,6.41 from [Milasinovic1997]
# ``G`` is the lower triangle matrix factorized from ``K_hat = G * G.T``
inv_G = np.linalg.cholesky(K_hat).I
# As per eq. 6.22,6.39,6.48 from [Milasinovic1997]
# ``omega`` [rad/s] is the natural frequency, and ``Phi_omega`` is its mode shape
omega, Phi_omega = solve_eigenvalue_problem(
inv_G, M, normalize_eigenvalues=lambda x: np.sqrt(1./x)
)
# As per eq. 6.48,6.63,6.82 from [Milasinovic1997]
# ``sigma_cr`` [MPa] is the critical buckling stress, and ``Phi_sigma_cr`` is its mode shape
N_cr, Phi_sigma_cr = solve_eigenvalue_problem(
inv_G, K_sigma, normalize_eigenvalues=lambda x: 1./x
)
sigma_cr = N_cr / (2*t_b)
ro = float(np.mean([mat['ro'] for mat in materials.values()]))
omega_approx = pd.approximate_natural_frequency_from_stress(m, a, sigma_cr, ro)
omega_rel_err = get_relative_error(omega, omega_approx)
sigma_cr_approx = pd.approximate_stress_from_natural_frequency(m, a, omega, ro)
sigma_cr_rel_err = get_relative_error(sigma_cr, sigma_cr_approx)
Phi_rel_err = get_relative_error(Phi_omega, Phi_sigma_cr)
return (
a, t_b, m,
omega, omega_approx, omega_rel_err,
sigma_cr, sigma_cr_approx, sigma_cr_rel_err,
Phi_omega, Phi_sigma_cr, Phi_rel_err,
)
def get_modal_composite(modal_raw_results):
best_result = min(modal_raw_results, key=lambda x: x[6]) # modal composite via sigma_cr
return best_result[:-3] # Exclude the `Phi_*` matrices, as we don't need them in modal composites
| import physical_dualism as pd
import numpy as np
from .matrices import compute_global_matrices
from .utils import clip_small_eigenvalues, get_relative_error
def solve_eigenvalue_problem(inv_G, A, normalize_eigenvalues=None):
# As per eq. 6.48 from [Milasinovic1997]
H = inv_G * A * inv_G.T
eigenvalues, eigenvectors = np.linalg.eigh(H)
# Clip the extremely small eigenvalues
clip_small_eigenvalues(eigenvalues)
if normalize_eigenvalues:
eigenvalues = normalize_eigenvalues(eigenvalues)
# As per eq. 6.45 from [Milasinovic1997]
mode_shapes = inv_G.T * eigenvectors
# According to Milasinovic the minimal eigenvalue is the one closest to 0
min_idx = np.argmin(eigenvalues)
eigenvalue_min = eigenvalues[min_idx]
mode_shape_min = mode_shapes[:,min_idx].A1
return eigenvalue_min, mode_shape_min
def perform_iteration(integral_db, beam_type, strip_data, materials, astiff_shape, a, t_b, m):
K_hat, K_sigma, M = compute_global_matrices(
integral_db, beam_type, strip_data, materials, astiff_shape, a, t_b, m
)
# As per eq. 6.40,6.41 from [Milasinovic1997]
# ``G`` is the lower triangle matrix factorized from ``K_hat = G * G.T``
inv_G = np.linalg.cholesky(K_hat).I
# As per eq. 6.22,6.39,6.48 from [Milasinovic1997]
# ``omega`` [rad/s] is the natural frequency, and ``Phi_omega`` is its mode shape
omega, Phi_omega = solve_eigenvalue_problem(
inv_G, M, normalize_eigenvalues=lambda x: np.sqrt(1./x)
)
# As per eq. 6.48,6.63,6.82 from [Milasinovic1997]
# ``sigma_cr`` [MPa] is the critical buckling stress, and ``Phi_sigma_cr`` is its mode shape
N_cr, Phi_sigma_cr = solve_eigenvalue_problem(
inv_G, K_sigma, normalize_eigenvalues=lambda x: 1./x
)
sigma_cr = N_cr / (2*t_b)
ro = float(np.mean([mat['ro'] for mat in materials.values()]))
omega_approx = pd.approximate_natural_frequency_from_stress(m, a, sigma_cr, ro)
omega_rel_err = get_relative_error(omega, omega_approx)
sigma_cr_approx = pd.approximate_stress_from_natural_frequency(m, a, omega, ro)
sigma_cr_rel_err = get_relative_error(sigma_cr, sigma_cr_approx)
Phi_rel_err = get_relative_error(Phi_omega, Phi_sigma_cr)
return (
a, t_b, m,
omega, omega_approx, omega_rel_err,
sigma_cr, sigma_cr_approx, sigma_cr_rel_err,
Phi_omega, Phi_sigma_cr, Phi_rel_err,
)
def get_modal_composite(modal_raw_results):
best_result = min(modal_raw_results, key=lambda x: x[6]) # modal composite via sigma_cr
return best_result[:-3] # Exclude the `Phi_*` matrices, as we don't need them in modal composites
| en | 0.867512 | # As per eq. 6.48 from [Milasinovic1997] # Clip the extremely small eigenvalues # As per eq. 6.45 from [Milasinovic1997] # According to Milasinovic the minimal eigenvalue is the one closest to 0 # As per eq. 6.40,6.41 from [Milasinovic1997] # ``G`` is the lower triangle matrix factorized from ``K_hat = G * G.T`` # As per eq. 6.22,6.39,6.48 from [Milasinovic1997] # ``omega`` [rad/s] is the natural frequency, and ``Phi_omega`` is its mode shape # As per eq. 6.48,6.63,6.82 from [Milasinovic1997] # ``sigma_cr`` [MPa] is the critical buckling stress, and ``Phi_sigma_cr`` is its mode shape # modal composite via sigma_cr # Exclude the `Phi_*` matrices, as we don't need them in modal composites | 2.198238 | 2 |
blog/tests.py | elkoutwest/Pound-Cake | 0 | 6620381 | <reponame>elkoutwest/Pound-Cake<filename>blog/tests.py
"""integration tests for blog app"""
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from portal.fixtures import USERS
from .models import Category, Post
BASE_URL_ADMIN = '/admin/blog/post/'
class TestCaseBase(TestCase):
"""helps create fixtures"""
maxDiff = None
@staticmethod
def create_users():
"""create users from global USERS"""
for u in USERS:
user = USERS[u]
try:
get_user_model().objects.get(username=user['username'])
except ObjectDoesNotExist:
if u == 'superuser':
get_user_model().objects.create_superuser(**user)
else:
get_user_model().objects.create_user(**user)
@staticmethod
def create_blog_categories():
"""create object from category fixtures"""
for c in Category.fixtures():
Category.objects.create(**c)
@staticmethod
def create_blog_posts():
"""create objects from post fixtures"""
user = get_user_model().objects.get(username=USERS['superuser']['username'])
for p in Post.fixtures():
c_name = p.pop('category')
category = Category.objects.get(name=c_name)
p['author'] = user
p['category'] = category
Post.objects.create(**p)
@classmethod
def setUpClass(cls):
"""prepare test environment"""
# setup fixtures
cls.create_users()
cls.create_blog_categories()
cls.create_blog_posts()
class PostAdminView(TestCaseBase):
"""integration tests for Post model"""
def test_admin_add(self):
"""check django admin add page"""
c = Client()
url = BASE_URL_ADMIN + 'add/'
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 302) # this should've been 403
# test as superuser
self.assertEqual(c.login(**USERS['superuser']), True)
response = c.get(url)
self.assertEqual(response.status_code, 200)
def test_admin_list_change(self):
"""check django admin list page"""
c = Client()
url = BASE_URL_ADMIN
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 302) # this should've been 403
# test as superuser
self.assertEqual(c.login(**USERS['superuser']), True)
response = c.get(url)
self.assertEqual(response.status_code, 200)
class PostNormalView(TestCase):
"""integration tests for Post model"""
def test_detail(self):
"""check detail page for Post"""
c = Client()
# test as anonymous
for p in Post.fixtures():
url = reverse('blog:detail', kwargs={'slug': p['slug']})
response = c.get(url)
self.assertEqual(response.status_code, 200)
def test_index(self):
"""check index page for Post"""
c = Client()
url = '/'
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 200)
| """integration tests for blog app"""
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from portal.fixtures import USERS
from .models import Category, Post
BASE_URL_ADMIN = '/admin/blog/post/'
class TestCaseBase(TestCase):
"""helps create fixtures"""
maxDiff = None
@staticmethod
def create_users():
"""create users from global USERS"""
for u in USERS:
user = USERS[u]
try:
get_user_model().objects.get(username=user['username'])
except ObjectDoesNotExist:
if u == 'superuser':
get_user_model().objects.create_superuser(**user)
else:
get_user_model().objects.create_user(**user)
@staticmethod
def create_blog_categories():
"""create object from category fixtures"""
for c in Category.fixtures():
Category.objects.create(**c)
@staticmethod
def create_blog_posts():
"""create objects from post fixtures"""
user = get_user_model().objects.get(username=USERS['superuser']['username'])
for p in Post.fixtures():
c_name = p.pop('category')
category = Category.objects.get(name=c_name)
p['author'] = user
p['category'] = category
Post.objects.create(**p)
@classmethod
def setUpClass(cls):
"""prepare test environment"""
# setup fixtures
cls.create_users()
cls.create_blog_categories()
cls.create_blog_posts()
class PostAdminView(TestCaseBase):
"""integration tests for Post model"""
def test_admin_add(self):
"""check django admin add page"""
c = Client()
url = BASE_URL_ADMIN + 'add/'
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 302) # this should've been 403
# test as superuser
self.assertEqual(c.login(**USERS['superuser']), True)
response = c.get(url)
self.assertEqual(response.status_code, 200)
def test_admin_list_change(self):
"""check django admin list page"""
c = Client()
url = BASE_URL_ADMIN
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 302) # this should've been 403
# test as superuser
self.assertEqual(c.login(**USERS['superuser']), True)
response = c.get(url)
self.assertEqual(response.status_code, 200)
class PostNormalView(TestCase):
"""integration tests for Post model"""
def test_detail(self):
"""check detail page for Post"""
c = Client()
# test as anonymous
for p in Post.fixtures():
url = reverse('blog:detail', kwargs={'slug': p['slug']})
response = c.get(url)
self.assertEqual(response.status_code, 200)
def test_index(self):
"""check index page for Post"""
c = Client()
url = '/'
# test as anonymous
response = c.get(url)
self.assertEqual(response.status_code, 200) | en | 0.876347 | integration tests for blog app helps create fixtures create users from global USERS create object from category fixtures create objects from post fixtures prepare test environment # setup fixtures integration tests for Post model check django admin add page # test as anonymous # this should've been 403 # test as superuser check django admin list page # test as anonymous # this should've been 403 # test as superuser integration tests for Post model check detail page for Post # test as anonymous check index page for Post # test as anonymous | 2.355275 | 2 |
examples/affect/affect_early_fusion.py | kapikantzari/MultiBench | 148 | 6620382 | <gh_stars>100-1000
import torch
import sys
import os
sys.path.append(os.getcwd())
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
from unimodals.common_models import GRU, MLP, Sequential, Identity # noqa
from training_structures.Supervised_Learning import train, test # noqa
from datasets.affect.get_data import get_dataloader # noqa
from fusions.common_fusions import ConcatEarly # noqa
# mosi_data.pkl, mosei_senti_data.pkl
# mosi_raw.pkl, mosei_senti_data.pkl, sarcasm.pkl, humor.pkl
# raw_path: mosi.hdf5, mosei.hdf5, sarcasm_raw_text.pkl, humor_raw_text.pkl
# traindata, validdata, testdata = get_dataloader('/home/pliang/multibench/affect/pack/mosi/mosi_raw.pkl', robust_test=False)
traindata, validdata, testdata = get_dataloader(
'/home/arav/MultiBench/MultiBench/mosi_raw.pkl', robust_test=False, max_pad=True, data_type='mosi', max_seq_len=50)
# mosi/mosei
encoders = [Identity().cuda(), Identity().cuda(), Identity().cuda()]
head = Sequential(GRU(409, 512, dropout=True, has_padding=False,
batch_first=True, last_only=True), MLP(512, 512, 1)).cuda()
# humor/sarcasm
# encoders = [Identity().cuda(),Identity().cuda(),Identity().cuda()]
# head = Sequential(GRU(752, 1128, dropout=True, has_padding=False, batch_first=True, last_only=True), MLP(1128, 512, 1)).cuda()
fusion = ConcatEarly().cuda()
train(encoders, fusion, head, traindata, validdata, 100, task="regression", optimtype=torch.optim.AdamW,
is_packed=False, lr=1e-3, save='mosi_ef_r0.pt', weight_decay=0.01, objective=torch.nn.L1Loss())
print("Testing:")
model = torch.load('mosi_ef_r0.pt').cuda()
test(model, testdata, 'affect', is_packed=False,
criterion=torch.nn.L1Loss(), task="posneg-classification", no_robust=True)
| import torch
import sys
import os
sys.path.append(os.getcwd())
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
from unimodals.common_models import GRU, MLP, Sequential, Identity # noqa
from training_structures.Supervised_Learning import train, test # noqa
from datasets.affect.get_data import get_dataloader # noqa
from fusions.common_fusions import ConcatEarly # noqa
# mosi_data.pkl, mosei_senti_data.pkl
# mosi_raw.pkl, mosei_senti_data.pkl, sarcasm.pkl, humor.pkl
# raw_path: mosi.hdf5, mosei.hdf5, sarcasm_raw_text.pkl, humor_raw_text.pkl
# traindata, validdata, testdata = get_dataloader('/home/pliang/multibench/affect/pack/mosi/mosi_raw.pkl', robust_test=False)
traindata, validdata, testdata = get_dataloader(
'/home/arav/MultiBench/MultiBench/mosi_raw.pkl', robust_test=False, max_pad=True, data_type='mosi', max_seq_len=50)
# mosi/mosei
encoders = [Identity().cuda(), Identity().cuda(), Identity().cuda()]
head = Sequential(GRU(409, 512, dropout=True, has_padding=False,
batch_first=True, last_only=True), MLP(512, 512, 1)).cuda()
# humor/sarcasm
# encoders = [Identity().cuda(),Identity().cuda(),Identity().cuda()]
# head = Sequential(GRU(752, 1128, dropout=True, has_padding=False, batch_first=True, last_only=True), MLP(1128, 512, 1)).cuda()
fusion = ConcatEarly().cuda()
train(encoders, fusion, head, traindata, validdata, 100, task="regression", optimtype=torch.optim.AdamW,
is_packed=False, lr=1e-3, save='mosi_ef_r0.pt', weight_decay=0.01, objective=torch.nn.L1Loss())
print("Testing:")
model = torch.load('mosi_ef_r0.pt').cuda()
test(model, testdata, 'affect', is_packed=False,
criterion=torch.nn.L1Loss(), task="posneg-classification", no_robust=True) | en | 0.188848 | # noqa # noqa # noqa # noqa # mosi_data.pkl, mosei_senti_data.pkl # mosi_raw.pkl, mosei_senti_data.pkl, sarcasm.pkl, humor.pkl # raw_path: mosi.hdf5, mosei.hdf5, sarcasm_raw_text.pkl, humor_raw_text.pkl # traindata, validdata, testdata = get_dataloader('/home/pliang/multibench/affect/pack/mosi/mosi_raw.pkl', robust_test=False) # mosi/mosei # humor/sarcasm # encoders = [Identity().cuda(),Identity().cuda(),Identity().cuda()] # head = Sequential(GRU(752, 1128, dropout=True, has_padding=False, batch_first=True, last_only=True), MLP(1128, 512, 1)).cuda() | 1.908945 | 2 |
legalnlp/get_premodel.py | kauecapellato/legalnlp | 86 | 6620383 | <filename>legalnlp/get_premodel.py<gh_stars>10-100
import wget
import zipfile
def get_premodel(model):
modelv = False
d = None
if model == 'bert':
# BERTikal
url = 'https://ndownloader.figshare.com/files/30446754'
filename = wget.download(url, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename, "r") as zip_ref:
zip_ref.extractall(d+filename.replace('.zip', ''))
modelv = True
# Download files to use in Word2Vec and Doc2Vec
if model == 'wodc':
url2 = 'https://ndownloader.figshare.com/files/30446736'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download Word2Vec of NILC
if model == 'w2vnilc':
url2 = 'http://192.168.3.11:22980/download.php?file=embeddings/word2vec/cbow_s100.zip'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use Phraser model
if model == 'phraser':
url2 = 'https://ndownloader.figshare.com/files/30446727'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use Fast Text model
if model == 'fasttext':
url2 = 'https://ndownloader.figshare.com/files/30446739'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use NeuralMind pre-model base
if model == 'neuralmindbase':
url2 = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-base-portuguese-cased/bert-base-portuguese-cased_pytorch_checkpoint.zip'
url_vocab = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-base-portuguese-cased/vocab.txt'
filename2 = wget.download(url2, out=d)
filename3 = wget.download(url_vocab, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use NeuralMind pre-model large
if model == 'neuralmindlarge':
url2 = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-large-portuguese-cased/bert-large-portuguese-cased_pytorch_checkpoint.zip'
url_vocab = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-large-portuguese-cased/vocab.txt'
filename2 = wget.download(url2, out=d)
filename3 = wget.download(url_vocab, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# If don't download any model return false, else return true
return modelv
| <filename>legalnlp/get_premodel.py<gh_stars>10-100
import wget
import zipfile
def get_premodel(model):
modelv = False
d = None
if model == 'bert':
# BERTikal
url = 'https://ndownloader.figshare.com/files/30446754'
filename = wget.download(url, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename, "r") as zip_ref:
zip_ref.extractall(d+filename.replace('.zip', ''))
modelv = True
# Download files to use in Word2Vec and Doc2Vec
if model == 'wodc':
url2 = 'https://ndownloader.figshare.com/files/30446736'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download Word2Vec of NILC
if model == 'w2vnilc':
url2 = 'http://192.168.3.11:22980/download.php?file=embeddings/word2vec/cbow_s100.zip'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use Phraser model
if model == 'phraser':
url2 = 'https://ndownloader.figshare.com/files/30446727'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use Fast Text model
if model == 'fasttext':
url2 = 'https://ndownloader.figshare.com/files/30446739'
filename2 = wget.download(url2, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use NeuralMind pre-model base
if model == 'neuralmindbase':
url2 = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-base-portuguese-cased/bert-base-portuguese-cased_pytorch_checkpoint.zip'
url_vocab = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-base-portuguese-cased/vocab.txt'
filename2 = wget.download(url2, out=d)
filename3 = wget.download(url_vocab, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# Download files to use NeuralMind pre-model large
if model == 'neuralmindlarge':
url2 = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-large-portuguese-cased/bert-large-portuguese-cased_pytorch_checkpoint.zip'
url_vocab = 'https://neuralmind-ai.s3.us-east-2.amazonaws.com/nlp/bert-large-portuguese-cased/vocab.txt'
filename2 = wget.download(url2, out=d)
filename3 = wget.download(url_vocab, out=d)
if d == None:
d = ''
with zipfile.ZipFile(d+filename2, "r") as zip_ref:
zip_ref.extractall(d+filename2.replace('.zip', ''))
modelv = True
# If don't download any model return false, else return true
return modelv
| en | 0.612386 | # BERTikal # Download files to use in Word2Vec and Doc2Vec # Download Word2Vec of NILC # Download files to use Phraser model # Download files to use Fast Text model # Download files to use NeuralMind pre-model base # Download files to use NeuralMind pre-model large # If don't download any model return false, else return true | 2.782051 | 3 |
test.py | ciaid-colombia/Taller-Python | 0 | 6620384 | <gh_stars>0
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print('producto escalar entre a:{0} y b:{1} = {2}'.format(a,b,np.dot(a,b)))
| import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print('producto escalar entre a:{0} y b:{1} = {2}'.format(a,b,np.dot(a,b))) | none | 1 | 3.61644 | 4 | |
battleship/ui_manager.py | jcobian/battleship-ai | 0 | 6620385 | from os import system
import time
from battleship.player import Player
class UiManager:
def __init__(self, player_top: Player, player_bottom: Player):
self.player_top = player_top
self.player_bottom = player_bottom
self.board_top = player_top.board
self.board_bottom = player_bottom.board
# TODO: pick a random position where there is not a ship
self.cursor_row = 0
self.cursor_col = 0
def pick_move(self):
# TODO: check for out of bounds
user_input = None
while True:
user_input = input()
if user_input in {'j', 'k', 'h', 'l'}:
self._handle_cursor_move(user_input)
self.render()
elif user_input == 'f':
fire_row = self.cursor_row
fire_col = self.cursor_col
# now move the cursor so they can see what happened
surrounding_positions = self.board_top.surrounding_positions(
[(fire_row, fire_col)])
for row, col in surrounding_positions:
board_cell = self.board_top.game_board[row][col]
if not board_cell.has_been_attempted():
self.cursor_row = row
self.cursor_col = col
break
# if we didn't find an empty surrounding spot,
# just move anywhere
if self.cursor_row == fire_row and self.cursor_col == fire_col:
first_surrounding_pos = list(surrounding_positions)[0]
row, col = first_surrounding_pos
self.cursor_row = row
self.cursor_col = col
return (fire_row, fire_col)
def _handle_cursor_move(self, user_input):
if user_input == "j":
# move down
self.cursor_row += 1
elif user_input == "k":
# move up
self.cursor_row -= 1
elif user_input == "h":
# move left
self.cursor_col -= 1
elif user_input == "l":
# move right
self.cursor_col += 1
def render(self):
system('clear')
self._show_boards()
def delay(self, num_seconds):
time.sleep(num_seconds)
def _show_boards(self):
print(f"{self.player_top}'s Board:")
print(self.board_top.show(self.cursor_row,
self.cursor_col, show_cursor=True))
print("\n")
print(f"{self.player_bottom}'s Board:")
print(self.board_bottom.show(
self.cursor_row, self.cursor_col,
show_cursor=False, censored=False))
print("\n")
| from os import system
import time
from battleship.player import Player
class UiManager:
def __init__(self, player_top: Player, player_bottom: Player):
self.player_top = player_top
self.player_bottom = player_bottom
self.board_top = player_top.board
self.board_bottom = player_bottom.board
# TODO: pick a random position where there is not a ship
self.cursor_row = 0
self.cursor_col = 0
def pick_move(self):
# TODO: check for out of bounds
user_input = None
while True:
user_input = input()
if user_input in {'j', 'k', 'h', 'l'}:
self._handle_cursor_move(user_input)
self.render()
elif user_input == 'f':
fire_row = self.cursor_row
fire_col = self.cursor_col
# now move the cursor so they can see what happened
surrounding_positions = self.board_top.surrounding_positions(
[(fire_row, fire_col)])
for row, col in surrounding_positions:
board_cell = self.board_top.game_board[row][col]
if not board_cell.has_been_attempted():
self.cursor_row = row
self.cursor_col = col
break
# if we didn't find an empty surrounding spot,
# just move anywhere
if self.cursor_row == fire_row and self.cursor_col == fire_col:
first_surrounding_pos = list(surrounding_positions)[0]
row, col = first_surrounding_pos
self.cursor_row = row
self.cursor_col = col
return (fire_row, fire_col)
def _handle_cursor_move(self, user_input):
if user_input == "j":
# move down
self.cursor_row += 1
elif user_input == "k":
# move up
self.cursor_row -= 1
elif user_input == "h":
# move left
self.cursor_col -= 1
elif user_input == "l":
# move right
self.cursor_col += 1
def render(self):
system('clear')
self._show_boards()
def delay(self, num_seconds):
time.sleep(num_seconds)
def _show_boards(self):
print(f"{self.player_top}'s Board:")
print(self.board_top.show(self.cursor_row,
self.cursor_col, show_cursor=True))
print("\n")
print(f"{self.player_bottom}'s Board:")
print(self.board_bottom.show(
self.cursor_row, self.cursor_col,
show_cursor=False, censored=False))
print("\n")
| en | 0.873676 | # TODO: pick a random position where there is not a ship # TODO: check for out of bounds # now move the cursor so they can see what happened # if we didn't find an empty surrounding spot, # just move anywhere # move down # move up # move left # move right | 3.507338 | 4 |
mlnx-ofed-4.9-driver/rdma-core-50mlnx1/tests/test_parent_domain.py | Hf7WCdtO/KRCore | 0 | 6620386 | <filename>mlnx-ofed-4.9-driver/rdma-core-50mlnx1/tests/test_parent_domain.py<gh_stars>0
# SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB)
# Copyright (c) 2019 Mellanox Technologies, Inc. All rights reserved. See COPYING file
"""
Test module for Pyverbs' ParentDomain.
"""
from pyverbs.pd import ParentDomainInitAttr, ParentDomain, ParentDomainContext
from pyverbs.pyverbs_error import PyverbsRDMAError
from pyverbs.srq import SrqAttr, SrqInitAttr, SRQ
from pyverbs.qp import QPInitAttr, QP
from tests.base import BaseResources
from tests.base import RDMATestCase
import pyverbs.mem_alloc as mem
import pyverbs.enums as e
from pyverbs.cq import CQ
import tests.utils as u
import unittest
class ParentDomainRes(BaseResources):
def __init__(self, dev_name, ib_port=None, gid_index=None):
super().__init__(dev_name=dev_name, ib_port=ib_port,
gid_index=gid_index)
# Parent Domain will be created according to the test
self.pd_ctx = None
self.parent_domain = None
class ParentDomainTestCase(RDMATestCase):
def setUp(self):
super().setUp()
self.pd_res = ParentDomainRes(self.dev_name)
def _create_parent_domain_with_allocators(self, alloc_func, free_func):
if alloc_func and free_func:
self.pd_res.pd_ctx = ParentDomainContext(self.pd_res.pd, alloc_func,
free_func)
pd_attr = ParentDomainInitAttr(pd=self.pd_res.pd,
pd_context=self.pd_res.pd_ctx)
try:
self.pd_res.parent_domain = ParentDomain(self.pd_res.ctx,
attr=pd_attr)
except PyverbsRDMAError as ex:
if 'not supported' in str(ex) or 'not implemented' in str(ex):
raise unittest.SkipTest('Parent Domain is not supported on this device')
raise ex
def _create_rdma_objects(self):
cq = CQ(self.pd_res.ctx, 100, None, None, 0)
dev_attr = self.pd_res.ctx.query_device()
qp_cap = u.random_qp_cap(dev_attr)
qia = QPInitAttr(scq=cq, rcq=cq, cap=qp_cap)
qia.qp_type = e.IBV_QPT_RC
QP(self.pd_res.parent_domain, qia)
srq_init_attr = SrqInitAttr(SrqAttr())
SRQ(self.pd_res.parent_domain, srq_init_attr)
def test_without_allocators(self):
self._create_parent_domain_with_allocators(None, None)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
def test_default_allocators(self):
def alloc_p_func(pd, context, size, alignment, resource_type):
return e._IBV_ALLOCATOR_USE_DEFAULT
def free_p_func(pd, context, ptr, resource_type):
return e._IBV_ALLOCATOR_USE_DEFAULT
self._create_parent_domain_with_allocators(alloc_p_func, free_p_func)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
def test_mem_align_allocators(self):
def alloc_p_func(pd, context, size, alignment, resource_type):
p = mem.posix_memalign(size, alignment)
return p
def free_p_func(pd, context, ptr, resource_type):
mem.free(ptr)
self._create_parent_domain_with_allocators(alloc_p_func, free_p_func)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
| <filename>mlnx-ofed-4.9-driver/rdma-core-50mlnx1/tests/test_parent_domain.py<gh_stars>0
# SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB)
# Copyright (c) 2019 Mellanox Technologies, Inc. All rights reserved. See COPYING file
"""
Test module for Pyverbs' ParentDomain.
"""
from pyverbs.pd import ParentDomainInitAttr, ParentDomain, ParentDomainContext
from pyverbs.pyverbs_error import PyverbsRDMAError
from pyverbs.srq import SrqAttr, SrqInitAttr, SRQ
from pyverbs.qp import QPInitAttr, QP
from tests.base import BaseResources
from tests.base import RDMATestCase
import pyverbs.mem_alloc as mem
import pyverbs.enums as e
from pyverbs.cq import CQ
import tests.utils as u
import unittest
class ParentDomainRes(BaseResources):
def __init__(self, dev_name, ib_port=None, gid_index=None):
super().__init__(dev_name=dev_name, ib_port=ib_port,
gid_index=gid_index)
# Parent Domain will be created according to the test
self.pd_ctx = None
self.parent_domain = None
class ParentDomainTestCase(RDMATestCase):
def setUp(self):
super().setUp()
self.pd_res = ParentDomainRes(self.dev_name)
def _create_parent_domain_with_allocators(self, alloc_func, free_func):
if alloc_func and free_func:
self.pd_res.pd_ctx = ParentDomainContext(self.pd_res.pd, alloc_func,
free_func)
pd_attr = ParentDomainInitAttr(pd=self.pd_res.pd,
pd_context=self.pd_res.pd_ctx)
try:
self.pd_res.parent_domain = ParentDomain(self.pd_res.ctx,
attr=pd_attr)
except PyverbsRDMAError as ex:
if 'not supported' in str(ex) or 'not implemented' in str(ex):
raise unittest.SkipTest('Parent Domain is not supported on this device')
raise ex
def _create_rdma_objects(self):
cq = CQ(self.pd_res.ctx, 100, None, None, 0)
dev_attr = self.pd_res.ctx.query_device()
qp_cap = u.random_qp_cap(dev_attr)
qia = QPInitAttr(scq=cq, rcq=cq, cap=qp_cap)
qia.qp_type = e.IBV_QPT_RC
QP(self.pd_res.parent_domain, qia)
srq_init_attr = SrqInitAttr(SrqAttr())
SRQ(self.pd_res.parent_domain, srq_init_attr)
def test_without_allocators(self):
self._create_parent_domain_with_allocators(None, None)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
def test_default_allocators(self):
def alloc_p_func(pd, context, size, alignment, resource_type):
return e._IBV_ALLOCATOR_USE_DEFAULT
def free_p_func(pd, context, ptr, resource_type):
return e._IBV_ALLOCATOR_USE_DEFAULT
self._create_parent_domain_with_allocators(alloc_p_func, free_p_func)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
def test_mem_align_allocators(self):
def alloc_p_func(pd, context, size, alignment, resource_type):
p = mem.posix_memalign(size, alignment)
return p
def free_p_func(pd, context, ptr, resource_type):
mem.free(ptr)
self._create_parent_domain_with_allocators(alloc_p_func, free_p_func)
self._create_rdma_objects()
self.pd_res.parent_domain.close()
| en | 0.619265 | # SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB) # Copyright (c) 2019 Mellanox Technologies, Inc. All rights reserved. See COPYING file Test module for Pyverbs' ParentDomain. # Parent Domain will be created according to the test | 1.850384 | 2 |
tests/__init__.py | halfguru/player-tech-assignment | 0 | 6620387 | """Unit test package for player_tech_assignment."""
| """Unit test package for player_tech_assignment."""
| en | 0.826186 | Unit test package for player_tech_assignment. | 1.097029 | 1 |
install.py | trinamic/PyTrinamicMicro | 4 | 6620388 | <gh_stars>1-10
'''
Install script to copy the required files in correct structure on the SD card.
Created on 13.10.2020
@author: LK
'''
import argparse
import os
import shutil
import logging
MPY_CROSS = "mpy-cross"
# Initialize install logger
logger = logging.getLogger(__name__)
formatter = logging.Formatter("[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s")
logger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
def clean_pytrinamic(path):
logger.info("Cleaning PyTrinamic ...")
shutil.rmtree(os.path.join(path, "PyTrinamic"), ignore_errors=True)
logger.info("PyTrinamic cleaned.")
def clean_motionpy(path):
logger.info("Cleaning MotionPy ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy1"), ignore_errors=True)
logger.info("MotionPy cleaned.")
def clean_pytrinamicmicro_api(path):
logger.info("Cleaning PyTrinamicMicro API ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "connections"), ignore_errors=True)
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "examples"), ignore_errors=True)
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "__init__.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "__init__.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "PyTrinamicMicro.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "PyTrinamicMicro.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "tmcl_bootloader.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "tmcl_bootloader.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "TMCL_Bridge.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "TMCL_Bridge.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "TMCL_Slave.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "TMCL_Slave.py"))
logger.info("PyTrinamicMicro API cleaned.")
def clean_pytrinamicmicro(path):
logger.info("Cleaning PyTrinamicMicro ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro"), ignore_errors=True)
logger.info("PyTrinamicMicro cleaned.")
def clean_lib(path):
logger.info("Cleaning libraries ...")
logger.info("Cleaning logging ...")
shutil.rmtree(os.path.join(path, "logging"), ignore_errors=True)
logger.info("logging cleaned.")
logger.info("Cleaning argparse ...")
shutil.rmtree(os.path.join(path, "argparse"), ignore_errors=True)
logger.info("argparse cleaned.")
logger.info("Libraries cleaned.")
def clean_full(path):
logger.info("Cleaning ...")
clean_pytrinamic(path)
clean_pytrinamicmicro(path)
clean_lib(path)
logger.info("Cleaned.")
def compile_recursive(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in [f for f in filenames if f.endswith(".py")]:
current = os.path.join(dirpath, filename)
logger.info("Compiling {}".format(current))
os.system("{} {}".format(MPY_CROSS, current))
def install_pytrinamic(path, compile, clean):
if(clean):
clean_pytrinamic(path)
base = os.path.join("PyTrinamic", "PyTrinamic")
logger.info("Installing PyTrinamic ...")
if(compile):
logger.info("Compiling PyTrinamic ...")
compile_recursive(base)
logger.info("PyTrinamic compiled.")
logger.info("Copying PyTrinamic ...")
shutil.copytree(base, os.path.join(path, "PyTrinamic"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("PyTrinamic copied.")
logger.info("PyTrinamic installed.")
def install_motionpy1_boot(path, compile, clean):
del clean
logger.info("Installing MotionPy v1 boot ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy1", "boot.py"), path)
logger.info("MotionPy v1 boot installed.")
def install_motionpy1_main(path, compile, clean):
del clean
logger.info("Installing MotionPy v1 main ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy1", "main.py"), path)
logger.info("MotionPy v1 main installed.")
def install_motionpy1(path, compile, clean):
if(clean):
clean_motionpy(path)
base = os.path.join("PyTrinamicMicro", "platforms", "motionpy1")
logger.info("Installing platform MotionPy v1 ...")
os.makedirs(os.path.join(path, "PyTrinamicMicro", "platforms"), exist_ok=True)
if(compile):
logger.info("Compiling MotionPy v1 ...")
compile_recursive(base)
logger.info("MotionPy v1 compiled.")
logger.info("Copying MotionPy v1 ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy1"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("MotionPy v1 copied.")
logger.info("MotionPy v1 installed.")
def install_motionpy2_boot(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 boot ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "boot.py"), path)
logger.info("MotionPy v2 boot installed.")
def install_motionpy2_main(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 main ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "main.py"), path)
logger.info("MotionPy v2 main installed.")
def install_motionpy2_test(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 test ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "main_test.py"), path)
shutil.move(os.path.join(path, "main_test.py"), os.path.join(path, "main.py"))
logger.info("MotionPy v2 test installed.")
def install_motionpy2(path, compile, clean):
if(clean):
clean_motionpy(path)
base = os.path.join("PyTrinamicMicro", "platforms", "motionpy2")
logger.info("Installing platform MotionPy v2 ...")
os.makedirs(os.path.join(path, "PyTrinamicMicro", "platforms"), exist_ok=True)
if(compile):
logger.info("Compiling MotionPy v2 ...")
compile_recursive(base)
logger.info("MotionPy v2 compiled.")
logger.info("Copying MotionPy v2 ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy2"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("MotionPy v2 copied.")
logger.info("MotionPy v2 installed.")
def install_pytrinamicmicro_api(path, compile, clean):
if(clean):
clean_pytrinamicmicro_api(path)
logger.info("Installing PyTrinamicMicro API ...")
shutil.copytree(os.path.join("PyTrinamicMicro", "connections"), os.path.join(path, "PyTrinamicMicro", "connections"))
shutil.copy(os.path.join("PyTrinamicMicro", "__init__.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "PyTrinamicMicro.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "tmcl_bootloader.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "TMCL_Bridge.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "TMCL_Slave.py"), os.path.join(path, "PyTrinamicMicro"))
logger.info("PyTrinamicMicro API installed.")
def install_pytrinamicmicro(path, compile, clean):
if(clean):
clean_pytrinamicmicro(path)
base = "PyTrinamicMicro"
logger.info("Installing PyTrinamicMicro ...")
if(compile):
logger.info("Compiling PyTrinamicMicro ...")
compile_recursive(base)
logger.info("PyTrinamicMicro compiled.")
logger.info("Copying PyTrinamicMicro ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("PyTrinamicMicro copied.")
logger.info("PyTrinamicMicro installed.")
def install_lib(path, compile, clean):
if(clean):
clean_lib(path)
logger.info("Installing libraries ...")
logger.info("Installing logging ...")
base = os.path.join("pycopy-lib", "logging", "logging")
if(compile):
logger.info("Compiling logging ...")
compile_recursive(base)
logger.info("logging compiled.")
logger.info("Copying logging ...")
shutil.copytree(os.path.join("pycopy-lib", "logging", "logging"), os.path.join(path, "logging"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("logging copied.")
logger.info("logging installed.")
logger.info("Installing argparse ...")
base = os.path.join("pycopy-lib", "argparse", "argparse")
if(compile):
logger.info("Compiling argparse ...")
compile_recursive(base)
logger.info("argparse compiled.")
logger.info("Copying argparse ...")
shutil.copytree(os.path.join("pycopy-lib", "argparse", "argparse"), os.path.join(path, "argparse"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("argparse copied.")
logger.info("argparse installed.")
logger.info("Libraries installed.")
def install_full(path, compile, clean):
logger.info("Installing full ...")
install_pytrinamic(path, compile, clean)
install_pytrinamicmicro(path, compile, clean)
install_lib(path, compile, clean)
logger.info("Fully installed.")
SELECTION_MAP = {
"full": install_full,
"pytrinamic": install_pytrinamic,
"pytrinamicmicro": install_pytrinamicmicro,
"pytrinamicmicro-full": install_pytrinamicmicro,
"pytrinamicmicro-api": install_pytrinamicmicro_api,
"motionpy1": install_motionpy1,
"motionpy1-boot": install_motionpy1_boot,
"motionpy1-main": install_motionpy1_main,
"motionpy2": install_motionpy2,
"motionpy2-boot": install_motionpy2_boot,
"motionpy2-main": install_motionpy2_main,
"motionpy2-test": install_motionpy2_test,
"lib": install_lib
}
# Argument parsing and mode execution
parser = argparse.ArgumentParser(description='Install the required files in correct structure on the SD card.')
parser.add_argument('path', metavar="path", type=str, nargs=1, default=".",
help='Path to the root of the SD card (default: %(default)s).')
parser.add_argument('-s', "--selection", dest='selection', action='store', nargs="*", type=str.lower,
choices=SELECTION_MAP.keys(),
default=['full'], help='Install selection (default: %(default)s).')
parser.add_argument('-c', "--clean", dest='clean', action='store_true', help='Clean module target directory before installing it there (default: %(default)s).')
parser.add_argument("--compile", dest='compile', action='store_true', help='Compile every module (default: %(default)s).')
args = parser.parse_args()
os.makedirs(args.path[0], exist_ok=True)
for s in args.selection:
SELECTION_MAP.get(s)(args.path[0], args.compile, args.clean)
logger.info("Done.")
| '''
Install script to copy the required files in correct structure on the SD card.
Created on 13.10.2020
@author: LK
'''
import argparse
import os
import shutil
import logging
MPY_CROSS = "mpy-cross"
# Initialize install logger
logger = logging.getLogger(__name__)
formatter = logging.Formatter("[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s")
logger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
def clean_pytrinamic(path):
logger.info("Cleaning PyTrinamic ...")
shutil.rmtree(os.path.join(path, "PyTrinamic"), ignore_errors=True)
logger.info("PyTrinamic cleaned.")
def clean_motionpy(path):
logger.info("Cleaning MotionPy ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy1"), ignore_errors=True)
logger.info("MotionPy cleaned.")
def clean_pytrinamicmicro_api(path):
logger.info("Cleaning PyTrinamicMicro API ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "connections"), ignore_errors=True)
shutil.rmtree(os.path.join(path, "PyTrinamicMicro", "examples"), ignore_errors=True)
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "__init__.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "__init__.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "PyTrinamicMicro.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "PyTrinamicMicro.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "tmcl_bootloader.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "tmcl_bootloader.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "TMCL_Bridge.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "TMCL_Bridge.py"))
if(os.path.exists(os.path.join(path, "PyTrinamicMicro", "TMCL_Slave.py"))):
os.remove(os.path.join(path, "PyTrinamicMicro", "TMCL_Slave.py"))
logger.info("PyTrinamicMicro API cleaned.")
def clean_pytrinamicmicro(path):
logger.info("Cleaning PyTrinamicMicro ...")
shutil.rmtree(os.path.join(path, "PyTrinamicMicro"), ignore_errors=True)
logger.info("PyTrinamicMicro cleaned.")
def clean_lib(path):
logger.info("Cleaning libraries ...")
logger.info("Cleaning logging ...")
shutil.rmtree(os.path.join(path, "logging"), ignore_errors=True)
logger.info("logging cleaned.")
logger.info("Cleaning argparse ...")
shutil.rmtree(os.path.join(path, "argparse"), ignore_errors=True)
logger.info("argparse cleaned.")
logger.info("Libraries cleaned.")
def clean_full(path):
logger.info("Cleaning ...")
clean_pytrinamic(path)
clean_pytrinamicmicro(path)
clean_lib(path)
logger.info("Cleaned.")
def compile_recursive(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in [f for f in filenames if f.endswith(".py")]:
current = os.path.join(dirpath, filename)
logger.info("Compiling {}".format(current))
os.system("{} {}".format(MPY_CROSS, current))
def install_pytrinamic(path, compile, clean):
if(clean):
clean_pytrinamic(path)
base = os.path.join("PyTrinamic", "PyTrinamic")
logger.info("Installing PyTrinamic ...")
if(compile):
logger.info("Compiling PyTrinamic ...")
compile_recursive(base)
logger.info("PyTrinamic compiled.")
logger.info("Copying PyTrinamic ...")
shutil.copytree(base, os.path.join(path, "PyTrinamic"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("PyTrinamic copied.")
logger.info("PyTrinamic installed.")
def install_motionpy1_boot(path, compile, clean):
del clean
logger.info("Installing MotionPy v1 boot ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy1", "boot.py"), path)
logger.info("MotionPy v1 boot installed.")
def install_motionpy1_main(path, compile, clean):
del clean
logger.info("Installing MotionPy v1 main ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy1", "main.py"), path)
logger.info("MotionPy v1 main installed.")
def install_motionpy1(path, compile, clean):
if(clean):
clean_motionpy(path)
base = os.path.join("PyTrinamicMicro", "platforms", "motionpy1")
logger.info("Installing platform MotionPy v1 ...")
os.makedirs(os.path.join(path, "PyTrinamicMicro", "platforms"), exist_ok=True)
if(compile):
logger.info("Compiling MotionPy v1 ...")
compile_recursive(base)
logger.info("MotionPy v1 compiled.")
logger.info("Copying MotionPy v1 ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy1"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("MotionPy v1 copied.")
logger.info("MotionPy v1 installed.")
def install_motionpy2_boot(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 boot ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "boot.py"), path)
logger.info("MotionPy v2 boot installed.")
def install_motionpy2_main(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 main ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "main.py"), path)
logger.info("MotionPy v2 main installed.")
def install_motionpy2_test(path, compile, clean):
del clean
logger.info("Installing MotionPy v2 test ...")
shutil.copy(os.path.join("PyTrinamicMicro", "platforms", "motionpy2", "main_test.py"), path)
shutil.move(os.path.join(path, "main_test.py"), os.path.join(path, "main.py"))
logger.info("MotionPy v2 test installed.")
def install_motionpy2(path, compile, clean):
if(clean):
clean_motionpy(path)
base = os.path.join("PyTrinamicMicro", "platforms", "motionpy2")
logger.info("Installing platform MotionPy v2 ...")
os.makedirs(os.path.join(path, "PyTrinamicMicro", "platforms"), exist_ok=True)
if(compile):
logger.info("Compiling MotionPy v2 ...")
compile_recursive(base)
logger.info("MotionPy v2 compiled.")
logger.info("Copying MotionPy v2 ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro", "platforms", "motionpy2"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("MotionPy v2 copied.")
logger.info("MotionPy v2 installed.")
def install_pytrinamicmicro_api(path, compile, clean):
if(clean):
clean_pytrinamicmicro_api(path)
logger.info("Installing PyTrinamicMicro API ...")
shutil.copytree(os.path.join("PyTrinamicMicro", "connections"), os.path.join(path, "PyTrinamicMicro", "connections"))
shutil.copy(os.path.join("PyTrinamicMicro", "__init__.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "PyTrinamicMicro.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "tmcl_bootloader.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "TMCL_Bridge.py"), os.path.join(path, "PyTrinamicMicro"))
shutil.copy(os.path.join("PyTrinamicMicro", "TMCL_Slave.py"), os.path.join(path, "PyTrinamicMicro"))
logger.info("PyTrinamicMicro API installed.")
def install_pytrinamicmicro(path, compile, clean):
if(clean):
clean_pytrinamicmicro(path)
base = "PyTrinamicMicro"
logger.info("Installing PyTrinamicMicro ...")
if(compile):
logger.info("Compiling PyTrinamicMicro ...")
compile_recursive(base)
logger.info("PyTrinamicMicro compiled.")
logger.info("Copying PyTrinamicMicro ...")
shutil.copytree(base, os.path.join(path, "PyTrinamicMicro"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("PyTrinamicMicro copied.")
logger.info("PyTrinamicMicro installed.")
def install_lib(path, compile, clean):
if(clean):
clean_lib(path)
logger.info("Installing libraries ...")
logger.info("Installing logging ...")
base = os.path.join("pycopy-lib", "logging", "logging")
if(compile):
logger.info("Compiling logging ...")
compile_recursive(base)
logger.info("logging compiled.")
logger.info("Copying logging ...")
shutil.copytree(os.path.join("pycopy-lib", "logging", "logging"), os.path.join(path, "logging"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("logging copied.")
logger.info("logging installed.")
logger.info("Installing argparse ...")
base = os.path.join("pycopy-lib", "argparse", "argparse")
if(compile):
logger.info("Compiling argparse ...")
compile_recursive(base)
logger.info("argparse compiled.")
logger.info("Copying argparse ...")
shutil.copytree(os.path.join("pycopy-lib", "argparse", "argparse"), os.path.join(path, "argparse"), ignore=shutil.ignore_patterns("*.py" if compile else "*.mpy"))
logger.info("argparse copied.")
logger.info("argparse installed.")
logger.info("Libraries installed.")
def install_full(path, compile, clean):
logger.info("Installing full ...")
install_pytrinamic(path, compile, clean)
install_pytrinamicmicro(path, compile, clean)
install_lib(path, compile, clean)
logger.info("Fully installed.")
SELECTION_MAP = {
"full": install_full,
"pytrinamic": install_pytrinamic,
"pytrinamicmicro": install_pytrinamicmicro,
"pytrinamicmicro-full": install_pytrinamicmicro,
"pytrinamicmicro-api": install_pytrinamicmicro_api,
"motionpy1": install_motionpy1,
"motionpy1-boot": install_motionpy1_boot,
"motionpy1-main": install_motionpy1_main,
"motionpy2": install_motionpy2,
"motionpy2-boot": install_motionpy2_boot,
"motionpy2-main": install_motionpy2_main,
"motionpy2-test": install_motionpy2_test,
"lib": install_lib
}
# Argument parsing and mode execution
parser = argparse.ArgumentParser(description='Install the required files in correct structure on the SD card.')
parser.add_argument('path', metavar="path", type=str, nargs=1, default=".",
help='Path to the root of the SD card (default: %(default)s).')
parser.add_argument('-s', "--selection", dest='selection', action='store', nargs="*", type=str.lower,
choices=SELECTION_MAP.keys(),
default=['full'], help='Install selection (default: %(default)s).')
parser.add_argument('-c', "--clean", dest='clean', action='store_true', help='Clean module target directory before installing it there (default: %(default)s).')
parser.add_argument("--compile", dest='compile', action='store_true', help='Compile every module (default: %(default)s).')
args = parser.parse_args()
os.makedirs(args.path[0], exist_ok=True)
for s in args.selection:
SELECTION_MAP.get(s)(args.path[0], args.compile, args.clean)
logger.info("Done.") | en | 0.712434 | Install script to copy the required files in correct structure on the SD card. Created on 13.10.2020 @author: LK # Initialize install logger # Argument parsing and mode execution | 2.263335 | 2 |
2.Basic/1.py | MajkutP/VisualPython-Fourth-Semester | 0 | 6620389 | <filename>2.Basic/1.py<gh_stars>0
import math
def func(x):
piNumber = 4
for i in range(1,x):
if i % 2 == 0:
piNumber += 4/((2 * i) + 1)
else:
piNumber -= 4/((2 * i) + 1)
return piNumber
for j in range(1,101):
number = func(j)
print(j, number, number/(math.pi), "\n")
for j in range(3,8):
number = func(10**j)
print(j, number, number/(math.pi), "\n")
| <filename>2.Basic/1.py<gh_stars>0
import math
def func(x):
piNumber = 4
for i in range(1,x):
if i % 2 == 0:
piNumber += 4/((2 * i) + 1)
else:
piNumber -= 4/((2 * i) + 1)
return piNumber
for j in range(1,101):
number = func(j)
print(j, number, number/(math.pi), "\n")
for j in range(3,8):
number = func(10**j)
print(j, number, number/(math.pi), "\n")
| none | 1 | 3.438374 | 3 | |
getData.py | devshah2/Research-Panel-Project- | 0 | 6620390 | import sys
import util
import requests
from bs4 import BeautifulSoup
import re
import argparse
parser = argparse.ArgumentParser(description='Find data about researchers')
parser.add_argument('-l','--link', action="store", help="Enter link to scrape", dest="link")
parser.add_argument('-n','--names', action="store", help="Enter list of names seperated by commas", dest="names")
args = parser.parse_args()
#test link="https://icpe2020.spec.org/program-committee/"
if(args.link!=None):
link=args.link
page = requests.get(link)
soup = BeautifulSoup(page.content, 'html.parser')
soup.beautify
soup=soup.get_text()
data=list(set(re.split(r'\n|\t| {2}|:|,', soup)))
elif(args.names!=None):
data=args.names.split(",")
else:
print("Enter some value try -h for help")
sys.exit()
util.run(data)
ddd=util.data
citedby=[x[0] for x in ddd]
hindex=[x[1] for x in ddd]
i10index=[x[2] for x in ddd]
if(len(citedby)>0):
print("Number of people {}, Average citedby {}, Average h-index {}, Average i10-index {} ".format(len(util.data),sum(citedby)/len(citedby),sum(hindex)/len(hindex),sum(i10index)/len(i10index)))
else:
print("No researcher found")
| import sys
import util
import requests
from bs4 import BeautifulSoup
import re
import argparse
parser = argparse.ArgumentParser(description='Find data about researchers')
parser.add_argument('-l','--link', action="store", help="Enter link to scrape", dest="link")
parser.add_argument('-n','--names', action="store", help="Enter list of names seperated by commas", dest="names")
args = parser.parse_args()
#test link="https://icpe2020.spec.org/program-committee/"
if(args.link!=None):
link=args.link
page = requests.get(link)
soup = BeautifulSoup(page.content, 'html.parser')
soup.beautify
soup=soup.get_text()
data=list(set(re.split(r'\n|\t| {2}|:|,', soup)))
elif(args.names!=None):
data=args.names.split(",")
else:
print("Enter some value try -h for help")
sys.exit()
util.run(data)
ddd=util.data
citedby=[x[0] for x in ddd]
hindex=[x[1] for x in ddd]
i10index=[x[2] for x in ddd]
if(len(citedby)>0):
print("Number of people {}, Average citedby {}, Average h-index {}, Average i10-index {} ".format(len(util.data),sum(citedby)/len(citedby),sum(hindex)/len(hindex),sum(i10index)/len(i10index)))
else:
print("No researcher found")
| en | 0.475568 | #test link="https://icpe2020.spec.org/program-committee/" | 3.271021 | 3 |
Homework1/Q7-sol.py | golden-dino/PoC-1-RiceUniversity-Sols | 0 | 6620391 | val1 = [1, 2, 3]
val2 = val1[1:]
val1[2] = 4
print(val2[1]) | val1 = [1, 2, 3]
val2 = val1[1:]
val1[2] = 4
print(val2[1]) | none | 1 | 3.186678 | 3 | |
opinionated/fastapi/tasks.py | opinionated-code/opinionated-fastapi | 3 | 6620392 | import logging
import os
from typing import List, Optional
import dramatiq
from dramatiq import Broker, Middleware, set_broker
from dramatiq.brokers.rabbitmq import RabbitmqBroker
from dramatiq.brokers.redis import RedisBroker
from dramatiq.brokers.stub import StubBroker
from dramatiq.middleware import (
AgeLimit,
Prometheus,
Retries,
ShutdownNotifications,
TimeLimit,
)
# from dramatiq.results import Results
logger = logging.getLogger(__name__)
def create_broker(
broker_type: str, url: Optional[str], middleware: List[Middleware]
) -> Broker:
if broker_type == "stub":
return StubBroker(middleware=middleware)
if url is None:
raise RuntimeError("Must set WORKER_BROKER_URL")
if broker_type == "redis":
return RedisBroker(url=url, middleware=middleware)
elif broker_type == "rabbitmq":
return RabbitmqBroker(url=url, middleware=middleware)
def init_broker(reload=False):
# Import locally to avoid circular imports
from .config import settings
logger.info("Loading async task broker")
middleware = [
# max time waiting in queue (one day)
AgeLimit(max_age=3600000),
Retries(max_retries=10, min_backoff=15000, max_backoff=604800000),
ShutdownNotifications(notify_shutdown=True),
# max task execution time (10min)
TimeLimit(time_limit=600000, interval=1000),
# fixme: dramatiq uses env vars for prometheus; maybe write our own using settings?
Prometheus(),
# fixme: i doubt we'll use results; anything that requires a result should prob be
# run using fastapi async BackgroundTask, but keep it here to keep our options open
# Results(),
]
set_broker(
create_broker(
settings.WORKER_BROKER_TYPE, settings.WORKER_BROKER_URL, middleware
)
)
def setup_dramatiq():
"""Called by dramatiq worker. Do NOT run this function from anywhere else"""
os.environ.setdefault("FASTAPI_CONFIG_MODULE", "server.config")
os.environ.setdefault("FASTAPI_SETTINGS", "Development")
from .bootstrap import setup
# The main thing this module needs to do is load the tasks modules - setup() will achieve
# that, so that's all we really need to do.
setup()
from dramatiq import get_broker
broker = get_broker()
actors = broker.get_declared_actors()
logger.info("Dramatiq worker loaded: %d actors registered.", len(actors))
for actor in actors:
actor_obj = broker.get_actor(actor)
logger.debug(
" - Actor registered: [%s] %s", actor_obj.queue_name, actor_obj.actor_name
)
| import logging
import os
from typing import List, Optional
import dramatiq
from dramatiq import Broker, Middleware, set_broker
from dramatiq.brokers.rabbitmq import RabbitmqBroker
from dramatiq.brokers.redis import RedisBroker
from dramatiq.brokers.stub import StubBroker
from dramatiq.middleware import (
AgeLimit,
Prometheus,
Retries,
ShutdownNotifications,
TimeLimit,
)
# from dramatiq.results import Results
logger = logging.getLogger(__name__)
def create_broker(
broker_type: str, url: Optional[str], middleware: List[Middleware]
) -> Broker:
if broker_type == "stub":
return StubBroker(middleware=middleware)
if url is None:
raise RuntimeError("Must set WORKER_BROKER_URL")
if broker_type == "redis":
return RedisBroker(url=url, middleware=middleware)
elif broker_type == "rabbitmq":
return RabbitmqBroker(url=url, middleware=middleware)
def init_broker(reload=False):
# Import locally to avoid circular imports
from .config import settings
logger.info("Loading async task broker")
middleware = [
# max time waiting in queue (one day)
AgeLimit(max_age=3600000),
Retries(max_retries=10, min_backoff=15000, max_backoff=604800000),
ShutdownNotifications(notify_shutdown=True),
# max task execution time (10min)
TimeLimit(time_limit=600000, interval=1000),
# fixme: dramatiq uses env vars for prometheus; maybe write our own using settings?
Prometheus(),
# fixme: i doubt we'll use results; anything that requires a result should prob be
# run using fastapi async BackgroundTask, but keep it here to keep our options open
# Results(),
]
set_broker(
create_broker(
settings.WORKER_BROKER_TYPE, settings.WORKER_BROKER_URL, middleware
)
)
def setup_dramatiq():
"""Called by dramatiq worker. Do NOT run this function from anywhere else"""
os.environ.setdefault("FASTAPI_CONFIG_MODULE", "server.config")
os.environ.setdefault("FASTAPI_SETTINGS", "Development")
from .bootstrap import setup
# The main thing this module needs to do is load the tasks modules - setup() will achieve
# that, so that's all we really need to do.
setup()
from dramatiq import get_broker
broker = get_broker()
actors = broker.get_declared_actors()
logger.info("Dramatiq worker loaded: %d actors registered.", len(actors))
for actor in actors:
actor_obj = broker.get_actor(actor)
logger.debug(
" - Actor registered: [%s] %s", actor_obj.queue_name, actor_obj.actor_name
)
| en | 0.870562 | # from dramatiq.results import Results # Import locally to avoid circular imports # max time waiting in queue (one day) # max task execution time (10min) # fixme: dramatiq uses env vars for prometheus; maybe write our own using settings? # fixme: i doubt we'll use results; anything that requires a result should prob be # run using fastapi async BackgroundTask, but keep it here to keep our options open # Results(), Called by dramatiq worker. Do NOT run this function from anywhere else # The main thing this module needs to do is load the tasks modules - setup() will achieve # that, so that's all we really need to do. | 2.074644 | 2 |
datum/generator/image.py | openAGI/datum | 6 | 6620393 | # Copyright 2020 The OpenAGI Datum Authors.
#
# 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 csv
import os
import xml.etree.ElementTree
from ast import literal_eval
from typing import Any, Dict, List, Tuple, no_type_check
import tensorflow as tf
from datum.generator import DatumGenerator
from datum.utils.types_utils import GeneratorReturnType
class ClfDatumGenerator(DatumGenerator):
"""Image classification problem data generator.
An object of this class can be used to iterate over data stored in a specified folder
in the host device in a specified format.
Typically this generator expect the input data to be stored in the following format:
+ data_path
- train (folder with training images, named after split)
- val (folder with validation images, named after split)
- test (folder with test images, named after split)
- train.csv (csv file with columns data as label with respect to filename
(filename without extension) )
```
filename, label_name1, label_name2, ...., label_nameN
test_image1, 1, 2, ..., 1.1
test_image1, 1, 2, ..., 1.3
```
- val.csv (csv file with columns data as label with respect to filename
(filename without extension) )
- test.csv (csv file with columns data as label with respect to filename
(filename without extension) )
It is not mandatory to have all the folders and csv files named after split name. You can control
the folder name by passing it as input the `__call__` method.
For a particular split, image folder name, labels csv fllename, data extension can be
controlled by passing the following keyword arguments the `__call__` method.
All sub directory path are relative to the root path.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: name of the split.
extension: image extension, defualt is '.jpg'.
image_dir: directroy name containing the image, default name is split name.
csv_path: labels filename, default name is `<split>.csv`
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Yields Example instances from given CSV.
Args:
kwargs: Optional kwargs for further input data format customization.
Following inputs for kwargs are accepted:
split: name of the split.
extension: image extension, defualt is '.jpg'.
image_dir: directroy name containing the image, default name is split name.
csv_path: labels filename, default name is `<split>.csv`
Returns:
a tuple of datum id and a dict with key as feature name and values as feature values.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
extension = kwargs.get('extension', '.jpg')
sub_dir = kwargs.get('image_dir', split)
csv_path = kwargs.get('csv_path', split + '.csv')
data_path = os.path.join(self.path, sub_dir)
data: List[Dict] = []
with tf.io.gfile.GFile(os.path.join(self.path, csv_path)) as csv_f:
reader = csv.DictReader(csv_f)
for row in reader:
feature_dict = {}
for feature_name, feature_value in row.items():
if feature_name != 'filename':
feature_dict[feature_name] = literal_eval(feature_value)
else:
feature_value = os.path.join(data_path, feature_value + extension)
feature_dict['image'] = feature_value
data.append(feature_dict)
for idx, datum in enumerate(data):
yield idx, datum
class DetDatumGenerator(DatumGenerator):
"""Image object Detection problem data generator.
This generator expect image data to be stored in the Pascal VOC data format in the
input storage location.
For each input example image, corresponding labels should be stored in a xml file, if
labels loading is enabled.
Input data should be stored in the following format
+ data_dir
- JPEGImages (all images, any number of split, stored together)
- Annotations (All annotations for detection, .xml format)
- ImageSets (Splits file, txt files with split name, each line contain name of the
image to use use for that split
e.g. image1\n image2\n etc)
While the overall directory levels should be as shown in the format, sub-directory names can
be controlled by passing keyword argument to `__call__` method.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: name of the split.
extension: image extension.
set_dir: directory name where split files are stored.
image_dir: directory name where images are stored.
annotation_dir: directory name where xml annotation files are stored.
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Generator to iterate over data stored in the data folder.
Args:
kwargs: optional, keyword arguments can be used to control folder names and image extension.
Following kwargs are supported:
split: name of the split.
extension: image extension.
set_dir: directory name where split files are stored.
image_dir: directory name where images are stored.
annotation_dir: directory name where xml annotation files are stored.
Returns:
a tuple of datum id and a dict with key as feature name and values as feature values.
Raises:
ValueError: if inptut split name is not provided.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
extension = kwargs.get('extension', '.jpg')
set_dir = kwargs.get('set_dir', 'ImageSets')
image_dir = kwargs.get('image_dir', 'JPEGImages')
annon_dir = kwargs.get('annotation_dir', 'Annotations')
set_filepath = os.path.join(self.path, set_dir, split + '.txt')
with tf.io.gfile.GFile(set_filepath, "r") as f:
for line in f:
image_id = line.strip()
example = self._generate_example(self.path, image_dir, annon_dir, image_id, extension,
self.gen_config.has_test_annotations)
yield image_id, example
def _generate_example(self, data_path: str, image_dir: str, annon_dir: str, image_id: str,
extension: str, load_annotations: bool) -> Dict:
"""Generate a single example of the dataset.
Args:
data_path: input dataset storage path.
image_dir: directory name with input images.
annon_dir: directory name with input annotations xml files.
image_id: id of the image, here the image name without extension.
extension: image filename extension.
load_annotations: whether to load annotations. True for training and validation.
Returns:
a dict with keys as feature names and values as feature values.
"""
image_filepath = os.path.join(data_path, image_dir, image_id + extension)
annon_filepath = os.path.join(data_path, annon_dir, image_id + '.xml')
if load_annotations:
xmin, xmax, ymin, ymax, label, pose, is_truncated, is_difficult = self._get_example_objects(
annon_filepath)
else:
xmin = []
xmax = []
ymin = []
ymax = []
label = []
pose = []
is_truncated = []
is_difficult = []
return {
"image": image_filepath,
"xmin": xmin,
"xmax": xmax,
"ymin": ymin,
"ymax": ymax,
"pose": pose,
"labels": label,
"is_truncated": is_truncated,
"labels_difficult": is_difficult,
}
@no_type_check
def _get_example_objects(self, annon_filepath: str) -> Tuple:
"""Function to get all the objects from the annotation XML file."""
with tf.io.gfile.GFile(annon_filepath, "r") as f:
root = xml.etree.ElementTree.parse(f).getroot()
size = root.find("size")
width = float(size.find("width").text)
height = float(size.find("height").text)
xmin: List[float] = []
xmax: List[float] = []
ymin: List[float] = []
ymax: List[float] = []
label: List[int] = []
pose: List[str] = []
is_truncated: List[bool] = []
is_difficult: List[bool] = []
for obj in root.findall("object"):
class_id = obj.find("name").text.lower()
if isinstance(class_id, str):
label.append(self.gen_config.class_map[class_id])
else:
label.append(class_id)
pose.append(obj.find("pose").text.lower())
is_truncated.append((obj.find("truncated").text == "1"))
is_difficult.append((obj.find("difficult").text == "1"))
bndbox = obj.find("bndbox")
xmax.append(float(bndbox.find("xmax").text) / width)
xmin.append(float(bndbox.find("xmin").text) / width)
ymax.append(float(bndbox.find("ymax").text) / height)
ymin.append(float(bndbox.find("ymin").text) / height)
return xmin, xmax, ymin, ymax, label, pose, is_truncated, is_difficult
class SegDatumGenerator(DatumGenerator):
"""Generator for image Segmentation problem.
This generator expects input data in the Pascal VOC segmentation data format.
For each single image there should be a single segmentation map image with class id as
pixel values.
It expects a input data path with the following format:
+ data_dir:
- JPEGImages (all input images for all the splits.)
- SegmentationClass (all segmentation label map images.)
While the overall directory levels should be as shown in the format, sub-directory names can
be controlled by passing keyword argument to `__call__` method.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: split name.
image_dir: name of the directory with input images.
label_dir: name of the directory with segmentation label map images.
image_extension: extension of the input images.
label_extension: extension of the label images.
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Single example generator from data in the storage path.
Args:
kwargs: Optional, keyword arguments to control directory names and exensions.
Followings kwargs are supported:
split: split name.
image_dir: name of the directory with input images.
label_dir: name of the directory with segmentation label map images.
image_extension: extension of the input images.
label_extension: extension of the label images.
Returns:
a tuple containing an unique example id and a dict with keys as feature names and
values as feature values.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
set_dir = kwargs.get('set_dir')
image_dir = kwargs.get('image_dir', 'JPEGImages')
label_dir = kwargs.get('label_dir', 'SegmentationClass')
image_extension = kwargs.get('image_extension', '.jpg')
label_extension = kwargs.get('label_extension', '.png')
set_filepath = os.path.join(self.path, split + '.txt')
if set_dir:
set_filepath = os.path.join(self.path, set_dir, split + '.txt')
with tf.io.gfile.GFile(set_filepath, "r") as f:
data = [line.strip() for line in f]
for image_id in data:
datum = {
'image': os.path.join(self.path, image_dir, image_id + image_extension),
'label': os.path.join(self.path, label_dir, image_id + label_extension),
}
yield image_id, datum
| # Copyright 2020 The OpenAGI Datum Authors.
#
# 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 csv
import os
import xml.etree.ElementTree
from ast import literal_eval
from typing import Any, Dict, List, Tuple, no_type_check
import tensorflow as tf
from datum.generator import DatumGenerator
from datum.utils.types_utils import GeneratorReturnType
class ClfDatumGenerator(DatumGenerator):
"""Image classification problem data generator.
An object of this class can be used to iterate over data stored in a specified folder
in the host device in a specified format.
Typically this generator expect the input data to be stored in the following format:
+ data_path
- train (folder with training images, named after split)
- val (folder with validation images, named after split)
- test (folder with test images, named after split)
- train.csv (csv file with columns data as label with respect to filename
(filename without extension) )
```
filename, label_name1, label_name2, ...., label_nameN
test_image1, 1, 2, ..., 1.1
test_image1, 1, 2, ..., 1.3
```
- val.csv (csv file with columns data as label with respect to filename
(filename without extension) )
- test.csv (csv file with columns data as label with respect to filename
(filename without extension) )
It is not mandatory to have all the folders and csv files named after split name. You can control
the folder name by passing it as input the `__call__` method.
For a particular split, image folder name, labels csv fllename, data extension can be
controlled by passing the following keyword arguments the `__call__` method.
All sub directory path are relative to the root path.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: name of the split.
extension: image extension, defualt is '.jpg'.
image_dir: directroy name containing the image, default name is split name.
csv_path: labels filename, default name is `<split>.csv`
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Yields Example instances from given CSV.
Args:
kwargs: Optional kwargs for further input data format customization.
Following inputs for kwargs are accepted:
split: name of the split.
extension: image extension, defualt is '.jpg'.
image_dir: directroy name containing the image, default name is split name.
csv_path: labels filename, default name is `<split>.csv`
Returns:
a tuple of datum id and a dict with key as feature name and values as feature values.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
extension = kwargs.get('extension', '.jpg')
sub_dir = kwargs.get('image_dir', split)
csv_path = kwargs.get('csv_path', split + '.csv')
data_path = os.path.join(self.path, sub_dir)
data: List[Dict] = []
with tf.io.gfile.GFile(os.path.join(self.path, csv_path)) as csv_f:
reader = csv.DictReader(csv_f)
for row in reader:
feature_dict = {}
for feature_name, feature_value in row.items():
if feature_name != 'filename':
feature_dict[feature_name] = literal_eval(feature_value)
else:
feature_value = os.path.join(data_path, feature_value + extension)
feature_dict['image'] = feature_value
data.append(feature_dict)
for idx, datum in enumerate(data):
yield idx, datum
class DetDatumGenerator(DatumGenerator):
"""Image object Detection problem data generator.
This generator expect image data to be stored in the Pascal VOC data format in the
input storage location.
For each input example image, corresponding labels should be stored in a xml file, if
labels loading is enabled.
Input data should be stored in the following format
+ data_dir
- JPEGImages (all images, any number of split, stored together)
- Annotations (All annotations for detection, .xml format)
- ImageSets (Splits file, txt files with split name, each line contain name of the
image to use use for that split
e.g. image1\n image2\n etc)
While the overall directory levels should be as shown in the format, sub-directory names can
be controlled by passing keyword argument to `__call__` method.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: name of the split.
extension: image extension.
set_dir: directory name where split files are stored.
image_dir: directory name where images are stored.
annotation_dir: directory name where xml annotation files are stored.
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Generator to iterate over data stored in the data folder.
Args:
kwargs: optional, keyword arguments can be used to control folder names and image extension.
Following kwargs are supported:
split: name of the split.
extension: image extension.
set_dir: directory name where split files are stored.
image_dir: directory name where images are stored.
annotation_dir: directory name where xml annotation files are stored.
Returns:
a tuple of datum id and a dict with key as feature name and values as feature values.
Raises:
ValueError: if inptut split name is not provided.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
extension = kwargs.get('extension', '.jpg')
set_dir = kwargs.get('set_dir', 'ImageSets')
image_dir = kwargs.get('image_dir', 'JPEGImages')
annon_dir = kwargs.get('annotation_dir', 'Annotations')
set_filepath = os.path.join(self.path, set_dir, split + '.txt')
with tf.io.gfile.GFile(set_filepath, "r") as f:
for line in f:
image_id = line.strip()
example = self._generate_example(self.path, image_dir, annon_dir, image_id, extension,
self.gen_config.has_test_annotations)
yield image_id, example
def _generate_example(self, data_path: str, image_dir: str, annon_dir: str, image_id: str,
extension: str, load_annotations: bool) -> Dict:
"""Generate a single example of the dataset.
Args:
data_path: input dataset storage path.
image_dir: directory name with input images.
annon_dir: directory name with input annotations xml files.
image_id: id of the image, here the image name without extension.
extension: image filename extension.
load_annotations: whether to load annotations. True for training and validation.
Returns:
a dict with keys as feature names and values as feature values.
"""
image_filepath = os.path.join(data_path, image_dir, image_id + extension)
annon_filepath = os.path.join(data_path, annon_dir, image_id + '.xml')
if load_annotations:
xmin, xmax, ymin, ymax, label, pose, is_truncated, is_difficult = self._get_example_objects(
annon_filepath)
else:
xmin = []
xmax = []
ymin = []
ymax = []
label = []
pose = []
is_truncated = []
is_difficult = []
return {
"image": image_filepath,
"xmin": xmin,
"xmax": xmax,
"ymin": ymin,
"ymax": ymax,
"pose": pose,
"labels": label,
"is_truncated": is_truncated,
"labels_difficult": is_difficult,
}
@no_type_check
def _get_example_objects(self, annon_filepath: str) -> Tuple:
"""Function to get all the objects from the annotation XML file."""
with tf.io.gfile.GFile(annon_filepath, "r") as f:
root = xml.etree.ElementTree.parse(f).getroot()
size = root.find("size")
width = float(size.find("width").text)
height = float(size.find("height").text)
xmin: List[float] = []
xmax: List[float] = []
ymin: List[float] = []
ymax: List[float] = []
label: List[int] = []
pose: List[str] = []
is_truncated: List[bool] = []
is_difficult: List[bool] = []
for obj in root.findall("object"):
class_id = obj.find("name").text.lower()
if isinstance(class_id, str):
label.append(self.gen_config.class_map[class_id])
else:
label.append(class_id)
pose.append(obj.find("pose").text.lower())
is_truncated.append((obj.find("truncated").text == "1"))
is_difficult.append((obj.find("difficult").text == "1"))
bndbox = obj.find("bndbox")
xmax.append(float(bndbox.find("xmax").text) / width)
xmin.append(float(bndbox.find("xmin").text) / width)
ymax.append(float(bndbox.find("ymax").text) / height)
ymin.append(float(bndbox.find("ymin").text) / height)
return xmin, xmax, ymin, ymax, label, pose, is_truncated, is_difficult
class SegDatumGenerator(DatumGenerator):
"""Generator for image Segmentation problem.
This generator expects input data in the Pascal VOC segmentation data format.
For each single image there should be a single segmentation map image with class id as
pixel values.
It expects a input data path with the following format:
+ data_dir:
- JPEGImages (all input images for all the splits.)
- SegmentationClass (all segmentation label map images.)
While the overall directory levels should be as shown in the format, sub-directory names can
be controlled by passing keyword argument to `__call__` method.
Following inputs for kwargs are accepted when calling the object:
Kwargs:
split: split name.
image_dir: name of the directory with input images.
label_dir: name of the directory with segmentation label map images.
image_extension: extension of the input images.
label_extension: extension of the label images.
"""
def generate_datum(self, **kwargs: Any) -> GeneratorReturnType:
"""Single example generator from data in the storage path.
Args:
kwargs: Optional, keyword arguments to control directory names and exensions.
Followings kwargs are supported:
split: split name.
image_dir: name of the directory with input images.
label_dir: name of the directory with segmentation label map images.
image_extension: extension of the input images.
label_extension: extension of the label images.
Returns:
a tuple containing an unique example id and a dict with keys as feature names and
values as feature values.
"""
split = kwargs.get('split')
if not split:
raise ValueError('Pass a valid split name to generate data.')
set_dir = kwargs.get('set_dir')
image_dir = kwargs.get('image_dir', 'JPEGImages')
label_dir = kwargs.get('label_dir', 'SegmentationClass')
image_extension = kwargs.get('image_extension', '.jpg')
label_extension = kwargs.get('label_extension', '.png')
set_filepath = os.path.join(self.path, split + '.txt')
if set_dir:
set_filepath = os.path.join(self.path, set_dir, split + '.txt')
with tf.io.gfile.GFile(set_filepath, "r") as f:
data = [line.strip() for line in f]
for image_id in data:
datum = {
'image': os.path.join(self.path, image_dir, image_id + image_extension),
'label': os.path.join(self.path, label_dir, image_id + label_extension),
}
yield image_id, datum
| en | 0.763121 | # Copyright 2020 The OpenAGI Datum Authors. # # 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. Image classification problem data generator. An object of this class can be used to iterate over data stored in a specified folder in the host device in a specified format. Typically this generator expect the input data to be stored in the following format: + data_path - train (folder with training images, named after split) - val (folder with validation images, named after split) - test (folder with test images, named after split) - train.csv (csv file with columns data as label with respect to filename (filename without extension) ) ``` filename, label_name1, label_name2, ...., label_nameN test_image1, 1, 2, ..., 1.1 test_image1, 1, 2, ..., 1.3 ``` - val.csv (csv file with columns data as label with respect to filename (filename without extension) ) - test.csv (csv file with columns data as label with respect to filename (filename without extension) ) It is not mandatory to have all the folders and csv files named after split name. You can control the folder name by passing it as input the `__call__` method. For a particular split, image folder name, labels csv fllename, data extension can be controlled by passing the following keyword arguments the `__call__` method. All sub directory path are relative to the root path. Following inputs for kwargs are accepted when calling the object: Kwargs: split: name of the split. extension: image extension, defualt is '.jpg'. image_dir: directroy name containing the image, default name is split name. csv_path: labels filename, default name is `<split>.csv` Yields Example instances from given CSV. Args: kwargs: Optional kwargs for further input data format customization. Following inputs for kwargs are accepted: split: name of the split. extension: image extension, defualt is '.jpg'. image_dir: directroy name containing the image, default name is split name. csv_path: labels filename, default name is `<split>.csv` Returns: a tuple of datum id and a dict with key as feature name and values as feature values. Image object Detection problem data generator. This generator expect image data to be stored in the Pascal VOC data format in the input storage location. For each input example image, corresponding labels should be stored in a xml file, if labels loading is enabled. Input data should be stored in the following format + data_dir - JPEGImages (all images, any number of split, stored together) - Annotations (All annotations for detection, .xml format) - ImageSets (Splits file, txt files with split name, each line contain name of the image to use use for that split e.g. image1\n image2\n etc) While the overall directory levels should be as shown in the format, sub-directory names can be controlled by passing keyword argument to `__call__` method. Following inputs for kwargs are accepted when calling the object: Kwargs: split: name of the split. extension: image extension. set_dir: directory name where split files are stored. image_dir: directory name where images are stored. annotation_dir: directory name where xml annotation files are stored. Generator to iterate over data stored in the data folder. Args: kwargs: optional, keyword arguments can be used to control folder names and image extension. Following kwargs are supported: split: name of the split. extension: image extension. set_dir: directory name where split files are stored. image_dir: directory name where images are stored. annotation_dir: directory name where xml annotation files are stored. Returns: a tuple of datum id and a dict with key as feature name and values as feature values. Raises: ValueError: if inptut split name is not provided. Generate a single example of the dataset. Args: data_path: input dataset storage path. image_dir: directory name with input images. annon_dir: directory name with input annotations xml files. image_id: id of the image, here the image name without extension. extension: image filename extension. load_annotations: whether to load annotations. True for training and validation. Returns: a dict with keys as feature names and values as feature values. Function to get all the objects from the annotation XML file. Generator for image Segmentation problem. This generator expects input data in the Pascal VOC segmentation data format. For each single image there should be a single segmentation map image with class id as pixel values. It expects a input data path with the following format: + data_dir: - JPEGImages (all input images for all the splits.) - SegmentationClass (all segmentation label map images.) While the overall directory levels should be as shown in the format, sub-directory names can be controlled by passing keyword argument to `__call__` method. Following inputs for kwargs are accepted when calling the object: Kwargs: split: split name. image_dir: name of the directory with input images. label_dir: name of the directory with segmentation label map images. image_extension: extension of the input images. label_extension: extension of the label images. Single example generator from data in the storage path. Args: kwargs: Optional, keyword arguments to control directory names and exensions. Followings kwargs are supported: split: split name. image_dir: name of the directory with input images. label_dir: name of the directory with segmentation label map images. image_extension: extension of the input images. label_extension: extension of the label images. Returns: a tuple containing an unique example id and a dict with keys as feature names and values as feature values. | 2.779881 | 3 |
src/data_common/provision/gs_buckets.py | hamshif/data-common | 0 | 6620394 | <filename>src/data_common/provision/gs_buckets.py<gh_stars>0
#!/usr/bin/env python
"""
author: gbar
A module for working with google cloud storage buckets
"""
from google.cloud import storage
from data_common.config.configurer import get_conf
from data_common.dictionary import dictionary as d
def s_confirm_bucket(**kwargs):
if 'kwargs' in kwargs:
kwargs = kwargs['kwargs']
bucket_name = kwargs[d.BUCKET_NAME]
project_id = kwargs[d.PROJECT]
location = kwargs[d.LOCATION]
if location is 'default':
location = None
confirm_bucket(
bucket_name=bucket_name,
project_id=project_id,
location=location
)
def confirm_bucket(bucket_name, project_id, location=None):
"""
The function affirms existence or provisions a namespace bucket
:param bucket_name:
:param project_id:
:param location: eg 'eu'
:return:
"""
client = storage.Client(project=project_id)
bucket = storage.Bucket(client, name=bucket_name)
if location is not None and location is not '':
bucket.location = location
if not bucket.exists(client):
bucket.create()
return bucket
def rename_blob(bucket_name, blob_name, new_name):
"""
:param bucket_name:
:param blob_name:
:param new_name:
:return:
"""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print(f'Blob {blob.name} has been renamed to {new_blob.name}')
if __name__ == "__main__":
_conf = get_conf()
_project_id = _conf.cloud.gcp.project
namespaces = _conf.namespaces
for _namespace, v in namespaces.items():
_bucket = confirm_bucket(
bucket_name=_namespace,
project_id=_project_id
)
| <filename>src/data_common/provision/gs_buckets.py<gh_stars>0
#!/usr/bin/env python
"""
author: gbar
A module for working with google cloud storage buckets
"""
from google.cloud import storage
from data_common.config.configurer import get_conf
from data_common.dictionary import dictionary as d
def s_confirm_bucket(**kwargs):
if 'kwargs' in kwargs:
kwargs = kwargs['kwargs']
bucket_name = kwargs[d.BUCKET_NAME]
project_id = kwargs[d.PROJECT]
location = kwargs[d.LOCATION]
if location is 'default':
location = None
confirm_bucket(
bucket_name=bucket_name,
project_id=project_id,
location=location
)
def confirm_bucket(bucket_name, project_id, location=None):
"""
The function affirms existence or provisions a namespace bucket
:param bucket_name:
:param project_id:
:param location: eg 'eu'
:return:
"""
client = storage.Client(project=project_id)
bucket = storage.Bucket(client, name=bucket_name)
if location is not None and location is not '':
bucket.location = location
if not bucket.exists(client):
bucket.create()
return bucket
def rename_blob(bucket_name, blob_name, new_name):
"""
:param bucket_name:
:param blob_name:
:param new_name:
:return:
"""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
new_blob = bucket.rename_blob(blob, new_name)
print(f'Blob {blob.name} has been renamed to {new_blob.name}')
if __name__ == "__main__":
_conf = get_conf()
_project_id = _conf.cloud.gcp.project
namespaces = _conf.namespaces
for _namespace, v in namespaces.items():
_bucket = confirm_bucket(
bucket_name=_namespace,
project_id=_project_id
)
| en | 0.606506 | #!/usr/bin/env python author: gbar A module for working with google cloud storage buckets The function affirms existence or provisions a namespace bucket :param bucket_name: :param project_id: :param location: eg 'eu' :return: :param bucket_name: :param blob_name: :param new_name: :return: | 2.857996 | 3 |
apps/booking/migrations/0001_initial.py | aadrm/breakoutwagtail | 0 | 6620395 | # Generated by Django 3.1.4 on 2021-03-06 09:20
import apps.booking.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.SmallIntegerField(default=0, verbose_name='status')),
('items_before_checkout', models.SmallIntegerField(blank=True, null=True, verbose_name='items before purchase')),
],
options={
'verbose_name': 'Cart',
'verbose_name_plural': 'Carts',
},
),
migrations.CreateModel(
name='CartCoupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('discount', models.DecimalField(decimal_places=2, default=0, max_digits=8, verbose_name='Discount')),
('cart', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cart_coupons', to='booking.cart', verbose_name='Cart')),
],
options={
'verbose_name': 'CartCoupon',
'verbose_name_plural': 'CartCoupons',
'ordering': ['-coupon__is_upgrade', 'coupon__is_percent', 'coupon__is_apply_to_basket'],
},
),
migrations.CreateModel(
name='Invoice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=32, verbose_name='Name')),
('phone', models.CharField(max_length=32, verbose_name='Phone')),
('email', models.EmailField(max_length=128, verbose_name='Email')),
('street', models.CharField(blank=True, max_length=128, null=True, verbose_name='Street')),
('post', models.CharField(blank=True, max_length=8, null=True, verbose_name='Post code')),
('city', models.CharField(blank=True, max_length=32, null=True, verbose_name='City')),
('company', models.CharField(blank=True, max_length=64, null=True, verbose_name='Company name')),
('is_terms', models.BooleanField(default=False, verbose_name='Accept terms')),
('is_privacy', models.BooleanField(default=False, verbose_name='Accept privacy')),
('order_date', models.DateTimeField(blank=True, editable=False, null=True, verbose_name='Order Placed')),
('order_int', models.SmallIntegerField(blank=True, editable=False, null=True, verbose_name='Order Number')),
('order_number', models.CharField(blank=True, editable=False, max_length=8, null=True, verbose_name='Order Number')),
],
options={
'verbose_name': 'Invoice',
'verbose_name_plural': 'Invoices',
},
),
migrations.CreateModel(
name='PaymentMethod',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='display name')),
('method', models.CharField(max_length=16, verbose_name='method')),
],
options={
'verbose_name': 'PaymentMethod',
'verbose_name_plural': 'PaymentMethods',
},
),
migrations.CreateModel(
name='ProductFamily',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Product Family')),
('is_coupon', models.BooleanField(default=False, verbose_name='Is coupon')),
('shipping_cost', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='Shipping cost')),
('payment_methods', models.ManyToManyField(to='booking.PaymentMethod')),
],
options={
'verbose_name': 'ProductFamily',
'verbose_name_plural': 'ProductFamilies',
},
),
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Name')),
('is_active', models.BooleanField(default=False, verbose_name='Active')),
('description', models.TextField(blank=True, null=True, verbose_name='Description')),
('photo', models.ImageField(blank=True, null=True, upload_to='uploads/rooms', verbose_name='Image')),
('red', models.SmallIntegerField(default=255, verbose_name='Red')),
('green', models.SmallIntegerField(default=255, verbose_name='Green')),
('blue', models.SmallIntegerField(default=255, verbose_name='Blue')),
],
),
migrations.CreateModel(
name='Schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_date', models.DateField(verbose_name='Start Date')),
('end_date', models.DateField(verbose_name='End Date')),
('dow', models.PositiveSmallIntegerField(verbose_name='Day of Week')),
('start_time', models.TimeField(verbose_name='Start Time')),
('interval', models.PositiveSmallIntegerField(default=30, verbose_name='Interval')),
('duration', models.PositiveSmallIntegerField(default=60, verbose_name='Duration')),
('instances', models.PositiveSmallIntegerField(verbose_name='Instances')),
('product_family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='booking.productfamily', verbose_name='ProductFamily')),
],
options={
'ordering': ['product_family__room', 'start_date', 'start_time'],
},
),
migrations.CreateModel(
name='Slot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.DateTimeField(verbose_name='Start')),
('duration', models.PositiveSmallIntegerField(default=60, verbose_name='Duration')),
('interval', models.PositiveSmallIntegerField(default=30, verbose_name='interval')),
('protect', models.BooleanField(null=True, verbose_name='protect')),
('product_family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='booking.productfamily', verbose_name='ProductFamily')),
('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='booking.room', verbose_name='room')),
('schedule', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='slots', to='booking.schedule', verbose_name='schedule')),
],
options={
'ordering': ['room', 'start'],
},
),
migrations.AddField(
model_name='productfamily',
name='room',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='booking.room', verbose_name='Room'),
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='Product')),
('price', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Price')),
('players', models.SmallIntegerField(blank=True, null=True, verbose_name='Players')),
('family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='products', to='booking.productfamily', verbose_name='Family')),
('upgrade', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='degrade', to='booking.product', verbose_name='upgrade')),
],
options={
'verbose_name': 'Product',
'verbose_name_plural': 'Products',
'ordering': ['price'],
},
),
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=2, max_digits=8)),
('invoice', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments', to='booking.invoice')),
],
),
migrations.AddField(
model_name='invoice',
name='payment',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='booking.paymentmethod', verbose_name='Payment Method'),
),
migrations.CreateModel(
name='Coupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=32, null=True, verbose_name='reference')),
('code', models.SlugField(blank=True, max_length=32, unique=True, verbose_name='code')),
('amount', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='discount amount')),
('is_percent', models.BooleanField(default=False, verbose_name='apply as percent')),
('is_apply_to_basket', models.BooleanField(default=False, verbose_name='apply to entire basket')),
('is_individual_use', models.BooleanField(default=True, verbose_name='cannot be used in conjunction with other coupons')),
('is_overrule_individual_use', models.BooleanField(default=False, verbose_name='can be used with individual use coupons')),
('is_upgrade', models.BooleanField(default=False, verbose_name='Upgrades the item')),
('used_times', models.IntegerField(default=0, verbose_name='Used times')),
('use_limit', models.IntegerField(default=1, verbose_name='Usage limit')),
('created', models.DateTimeField(auto_now=True, verbose_name='Created')),
('expiry', models.DateField(blank=True, default=apps.booking.models.Coupon.now_plus_time, null=True, verbose_name='Expiration date')),
('minimum_spend', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='Minimum spend')),
('dow_valid', models.PositiveSmallIntegerField(default=127, verbose_name='Days Valid')),
('product_excluded', models.ManyToManyField(blank=True, related_name='product_exclude', to='booking.Product', verbose_name='exclude product')),
('product_families_excluded', models.ManyToManyField(blank=True, related_name='product_family_exclude', to='booking.ProductFamily', verbose_name=' exclude families')),
('product_families_included', models.ManyToManyField(blank=True, related_name='product_family_include', to='booking.ProductFamily', verbose_name=' include families')),
('product_included', models.ManyToManyField(blank=True, related_name='product_include', to='booking.Product', verbose_name='include product')),
],
options={
'verbose_name': 'Coupon',
'verbose_name_plural': 'Coupons',
},
),
migrations.CreateModel(
name='CartItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.SmallIntegerField(default=0, verbose_name='status')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
('price', models.DecimalField(decimal_places=2, default=0, max_digits=8, verbose_name='Price')),
('marked_shipped', models.DateTimeField(blank=True, null=True, verbose_name='Shipped')),
('cart', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cart_items', to='booking.cart', verbose_name='Cart')),
('cart_coupons', models.ManyToManyField(blank=True, related_name='cart_items', to='booking.CartCoupon', verbose_name='coupons')),
('coupon', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='booking', to='booking.coupon')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='booking.product')),
('slot', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='booking', to='booking.slot', verbose_name='slot')),
],
),
migrations.AddField(
model_name='cartcoupon',
name='coupon',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='booking.coupon', verbose_name='Cart Coupon'),
),
migrations.AddField(
model_name='cart',
name='invoice',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='booking.invoice', verbose_name='Invoice'),
),
]
| # Generated by Django 3.1.4 on 2021-03-06 09:20
import apps.booking.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.SmallIntegerField(default=0, verbose_name='status')),
('items_before_checkout', models.SmallIntegerField(blank=True, null=True, verbose_name='items before purchase')),
],
options={
'verbose_name': 'Cart',
'verbose_name_plural': 'Carts',
},
),
migrations.CreateModel(
name='CartCoupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('discount', models.DecimalField(decimal_places=2, default=0, max_digits=8, verbose_name='Discount')),
('cart', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cart_coupons', to='booking.cart', verbose_name='Cart')),
],
options={
'verbose_name': 'CartCoupon',
'verbose_name_plural': 'CartCoupons',
'ordering': ['-coupon__is_upgrade', 'coupon__is_percent', 'coupon__is_apply_to_basket'],
},
),
migrations.CreateModel(
name='Invoice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=32, verbose_name='Name')),
('phone', models.CharField(max_length=32, verbose_name='Phone')),
('email', models.EmailField(max_length=128, verbose_name='Email')),
('street', models.CharField(blank=True, max_length=128, null=True, verbose_name='Street')),
('post', models.CharField(blank=True, max_length=8, null=True, verbose_name='Post code')),
('city', models.CharField(blank=True, max_length=32, null=True, verbose_name='City')),
('company', models.CharField(blank=True, max_length=64, null=True, verbose_name='Company name')),
('is_terms', models.BooleanField(default=False, verbose_name='Accept terms')),
('is_privacy', models.BooleanField(default=False, verbose_name='Accept privacy')),
('order_date', models.DateTimeField(blank=True, editable=False, null=True, verbose_name='Order Placed')),
('order_int', models.SmallIntegerField(blank=True, editable=False, null=True, verbose_name='Order Number')),
('order_number', models.CharField(blank=True, editable=False, max_length=8, null=True, verbose_name='Order Number')),
],
options={
'verbose_name': 'Invoice',
'verbose_name_plural': 'Invoices',
},
),
migrations.CreateModel(
name='PaymentMethod',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='display name')),
('method', models.CharField(max_length=16, verbose_name='method')),
],
options={
'verbose_name': 'PaymentMethod',
'verbose_name_plural': 'PaymentMethods',
},
),
migrations.CreateModel(
name='ProductFamily',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Product Family')),
('is_coupon', models.BooleanField(default=False, verbose_name='Is coupon')),
('shipping_cost', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='Shipping cost')),
('payment_methods', models.ManyToManyField(to='booking.PaymentMethod')),
],
options={
'verbose_name': 'ProductFamily',
'verbose_name_plural': 'ProductFamilies',
},
),
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Name')),
('is_active', models.BooleanField(default=False, verbose_name='Active')),
('description', models.TextField(blank=True, null=True, verbose_name='Description')),
('photo', models.ImageField(blank=True, null=True, upload_to='uploads/rooms', verbose_name='Image')),
('red', models.SmallIntegerField(default=255, verbose_name='Red')),
('green', models.SmallIntegerField(default=255, verbose_name='Green')),
('blue', models.SmallIntegerField(default=255, verbose_name='Blue')),
],
),
migrations.CreateModel(
name='Schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_date', models.DateField(verbose_name='Start Date')),
('end_date', models.DateField(verbose_name='End Date')),
('dow', models.PositiveSmallIntegerField(verbose_name='Day of Week')),
('start_time', models.TimeField(verbose_name='Start Time')),
('interval', models.PositiveSmallIntegerField(default=30, verbose_name='Interval')),
('duration', models.PositiveSmallIntegerField(default=60, verbose_name='Duration')),
('instances', models.PositiveSmallIntegerField(verbose_name='Instances')),
('product_family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='booking.productfamily', verbose_name='ProductFamily')),
],
options={
'ordering': ['product_family__room', 'start_date', 'start_time'],
},
),
migrations.CreateModel(
name='Slot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.DateTimeField(verbose_name='Start')),
('duration', models.PositiveSmallIntegerField(default=60, verbose_name='Duration')),
('interval', models.PositiveSmallIntegerField(default=30, verbose_name='interval')),
('protect', models.BooleanField(null=True, verbose_name='protect')),
('product_family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='booking.productfamily', verbose_name='ProductFamily')),
('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='booking.room', verbose_name='room')),
('schedule', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='slots', to='booking.schedule', verbose_name='schedule')),
],
options={
'ordering': ['room', 'start'],
},
),
migrations.AddField(
model_name='productfamily',
name='room',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='booking.room', verbose_name='Room'),
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='Product')),
('price', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Price')),
('players', models.SmallIntegerField(blank=True, null=True, verbose_name='Players')),
('family', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='products', to='booking.productfamily', verbose_name='Family')),
('upgrade', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='degrade', to='booking.product', verbose_name='upgrade')),
],
options={
'verbose_name': 'Product',
'verbose_name_plural': 'Products',
'ordering': ['price'],
},
),
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=2, max_digits=8)),
('invoice', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='payments', to='booking.invoice')),
],
),
migrations.AddField(
model_name='invoice',
name='payment',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='booking.paymentmethod', verbose_name='Payment Method'),
),
migrations.CreateModel(
name='Coupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=32, null=True, verbose_name='reference')),
('code', models.SlugField(blank=True, max_length=32, unique=True, verbose_name='code')),
('amount', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='discount amount')),
('is_percent', models.BooleanField(default=False, verbose_name='apply as percent')),
('is_apply_to_basket', models.BooleanField(default=False, verbose_name='apply to entire basket')),
('is_individual_use', models.BooleanField(default=True, verbose_name='cannot be used in conjunction with other coupons')),
('is_overrule_individual_use', models.BooleanField(default=False, verbose_name='can be used with individual use coupons')),
('is_upgrade', models.BooleanField(default=False, verbose_name='Upgrades the item')),
('used_times', models.IntegerField(default=0, verbose_name='Used times')),
('use_limit', models.IntegerField(default=1, verbose_name='Usage limit')),
('created', models.DateTimeField(auto_now=True, verbose_name='Created')),
('expiry', models.DateField(blank=True, default=apps.booking.models.Coupon.now_plus_time, null=True, verbose_name='Expiration date')),
('minimum_spend', models.DecimalField(decimal_places=2, default=0, max_digits=5, verbose_name='Minimum spend')),
('dow_valid', models.PositiveSmallIntegerField(default=127, verbose_name='Days Valid')),
('product_excluded', models.ManyToManyField(blank=True, related_name='product_exclude', to='booking.Product', verbose_name='exclude product')),
('product_families_excluded', models.ManyToManyField(blank=True, related_name='product_family_exclude', to='booking.ProductFamily', verbose_name=' exclude families')),
('product_families_included', models.ManyToManyField(blank=True, related_name='product_family_include', to='booking.ProductFamily', verbose_name=' include families')),
('product_included', models.ManyToManyField(blank=True, related_name='product_include', to='booking.Product', verbose_name='include product')),
],
options={
'verbose_name': 'Coupon',
'verbose_name_plural': 'Coupons',
},
),
migrations.CreateModel(
name='CartItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.SmallIntegerField(default=0, verbose_name='status')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
('price', models.DecimalField(decimal_places=2, default=0, max_digits=8, verbose_name='Price')),
('marked_shipped', models.DateTimeField(blank=True, null=True, verbose_name='Shipped')),
('cart', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cart_items', to='booking.cart', verbose_name='Cart')),
('cart_coupons', models.ManyToManyField(blank=True, related_name='cart_items', to='booking.CartCoupon', verbose_name='coupons')),
('coupon', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='booking', to='booking.coupon')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='booking.product')),
('slot', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='booking', to='booking.slot', verbose_name='slot')),
],
),
migrations.AddField(
model_name='cartcoupon',
name='coupon',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='booking.coupon', verbose_name='Cart Coupon'),
),
migrations.AddField(
model_name='cart',
name='invoice',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='booking.invoice', verbose_name='Invoice'),
),
]
| en | 0.818189 | # Generated by Django 3.1.4 on 2021-03-06 09:20 | 1.773559 | 2 |
leetCode/algorithms/medium/search_a_2d_matrix_2.py | ferhatelmas/algo | 25 | 6620396 | <gh_stars>10-100
class Solution:
def searchMatrix(self, matrix, target):
m, n = len(matrix), len(matrix[0])
x, y = 0, n - 1
while x < m and y >= 0:
e = matrix[x][y]
if target == e:
return True
elif target > e:
x += 1
else:
y -= 1
return False
| class Solution:
def searchMatrix(self, matrix, target):
m, n = len(matrix), len(matrix[0])
x, y = 0, n - 1
while x < m and y >= 0:
e = matrix[x][y]
if target == e:
return True
elif target > e:
x += 1
else:
y -= 1
return False | none | 1 | 3.444315 | 3 | |
venv/Lib/site-packages/psychopy/app/_psychopyApp.py | mintzer/pupillometry-rf-back | 0 | 6620397 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, division, print_function
from builtins import str
from builtins import object
from pathlib import Path
from psychopy.app.colorpicker import PsychoColorPicker
profiling = False # turning on will save profile files in currDir
import sys
import argparse
import psychopy
from psychopy import prefs
from pkg_resources import parse_version
from psychopy.constants import PY3
from . import urls
from . import frametracker
from . import themes
from . import console
import io
if not hasattr(sys, 'frozen'):
try:
import wxversion
haveWxVersion = True
except ImportError:
haveWxVersion = False # if wxversion doesn't exist hope for the best
if haveWxVersion:
wxversion.ensureMinimal('2.8') # because this version has agw
import wx
try:
from agw import advancedsplash as AS
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.advancedsplash as AS
# from .plugin_manager import saveStartUpPluginsConfig
from psychopy.localization import _translate
# NB keep imports to a minimum here because splash screen has not yet shown
# e.g. coder and builder are imported during app.__init__ because they
# take a while
# needed by splash screen for the path to resources/psychopySplash.png
import ctypes
from psychopy import logging, __version__
from psychopy import projects
from . import connections
from .utils import FileDropTarget
import os
import weakref
# knowing if the user has admin priv is generally a good idea for security.
# not actually needed; psychopy should never need anything except normal user
# see older versions for code to detect admin (e.g., v 1.80.00)
if not PY3 and sys.platform == 'darwin':
blockTips = True
else:
blockTips = False
# Enable high-dpi support if on Windows. This fixes blurry text rendering.
if sys.platform == 'win32':
# get the preference for high DPI
if 'highDPI' in psychopy.prefs.app.keys(): # check if we have the option
enableHighDPI = psychopy.prefs.app['highDPI']
# check if we have OS support for it
if enableHighDPI:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(enableHighDPI)
except OSError:
logging.warn(
"High DPI support is not appear to be supported by this version"
" of Windows. Disabling in preferences.")
psychopy.prefs.app['highDPI'] = False
psychopy.prefs.saveUserPrefs()
class MenuFrame(wx.Frame, themes.ThemeMixin):
"""A simple empty frame with a menubar, should be last frame closed on mac
"""
def __init__(self, parent=None, ID=-1, app=None, title="PsychoPy"):
wx.Frame.__init__(self, parent, ID, title, size=(1, 1))
self.app = app
self.menuBar = wx.MenuBar()
self.viewMenu = wx.Menu()
self.menuBar.Append(self.viewMenu, _translate('&View'))
mtxt = _translate("&Open Builder view\t%s")
self.app.IDs.openBuilderView = self.viewMenu.Append(wx.ID_ANY,
mtxt,
_translate("Open a new Builder view")).GetId()
self.Bind(wx.EVT_MENU, self.app.showBuilder,
id=self.app.IDs.openBuilderView)
mtxt = _translate("&Open Coder view\t%s")
self.app.IDs.openCoderView = self.viewMenu.Append(wx.ID_ANY,
mtxt,
_translate("Open a new Coder view")).GetId()
self.Bind(wx.EVT_MENU, self.app.showCoder,
id=self.app.IDs.openCoderView)
mtxt = _translate("&Quit\t%s")
item = self.viewMenu.Append(wx.ID_EXIT, mtxt % self.app.keys['quit'],
_translate("Terminate the program"))
self.Bind(wx.EVT_MENU, self.app.quit, id=item.GetId())
self.SetMenuBar(self.menuBar)
self.Show()
class IDStore(dict):
"""A simpe class that works like a dict but you can access attributes
like standard python attrs. Useful to replace the previous pre-made
app.IDs (wx.NewID() is no longer recommended or safe)
"""
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
class _Showgui_Hack(object):
"""Class with side-effect of restoring wx window switching under wx-3.0
- might only be needed on some platforms (Mac 10.9.4 needs it for me);
- needs to be launched as an external script
- needs to be separate: seg-faults as method of PsychoPyApp or in-lined
- unlear why it works or what the deeper issue is, blah
- called at end of PsychoPyApp.onInit()
"""
def __init__(self):
super(_Showgui_Hack, self).__init__()
from psychopy import core
import os
# should be writable:
noopPath = os.path.join(psychopy.prefs.paths['userPrefsDir'],
'showgui_hack.py')
# code to open & immediately close a gui (= invisibly):
if not os.path.isfile(noopPath):
code = """from psychopy import gui
dlg = gui.Dlg().Show() # non-blocking
try:
dlg.Destroy() # might as well
except Exception:
pass"""
with open(noopPath, 'wb') as fd:
fd.write(bytes(code))
# append 'w' for pythonw seems not needed
core.shellCall([sys.executable, noopPath])
class PsychoPyApp(wx.App, themes.ThemeMixin):
_called_from_test = False # pytest needs to change this
def __init__(self, arg=0, testMode=False, **kwargs):
"""With a wx.App some things get done here, before App.__init__
then some further code is launched in OnInit() which occurs after
"""
if profiling:
import cProfile, time
profile = cProfile.Profile()
profile.enable()
t0 = time.time()
self._appLoaded = False # set to true when all frames are created
self.coder = None
self.runner = None
self.version = psychopy.__version__
# set default paths and prefs
self.prefs = psychopy.prefs
self._currentThemeSpec = None
self.keys = self.prefs.keys
self.prefs.pageCurrent = 0 # track last-viewed page, can return there
self.IDs = IDStore()
self.urls = urls.urls
self.quitting = False
# check compatibility with last run version (before opening windows)
self.firstRun = False
self.testMode = testMode
self._stdout = sys.stdout
self._stderr = sys.stderr
self._stdoutFrame = None
self.iconCache = themes.IconCache()
if not self.testMode:
self._lastRunLog = open(os.path.join(
self.prefs.paths['userPrefsDir'], 'last_app_load.log'),
'w')
sys.stderr = sys.stdout = lastLoadErrs = self._lastRunLog
logging.console.setLevel(logging.DEBUG)
# indicates whether we're running for testing purposes
self.osfSession = None
self.pavloviaSession = None
self.copiedRoutine = None
self.copiedCompon = None
self._allFrames = frametracker.openFrames # ordered; order updated with self.onNewTopWindow
wx.App.__init__(self, arg)
# import localization after wx:
from psychopy import localization # needed by splash screen
self.localization = localization
self.locale = localization.setLocaleWX()
self.locale.AddCatalog(self.GetAppName())
logging.flush()
self.onInit(testMode=testMode, **kwargs)
if profiling:
profile.disable()
print("time to load app = {:.2f}".format(time.time()-t0))
profile.dump_stats('profileLaunchApp.profile')
logging.flush()
# set the exception hook to present unhandled errors in a dialog
if not PsychoPyApp._called_from_test: #NB class variable not self
from psychopy.app.errorDlg import exceptionCallback
sys.excepthook = exceptionCallback
def onInit(self, showSplash=True, testMode=False):
"""This is launched immediately *after* the app initialises with wx
:Parameters:
testMode: bool
"""
self.SetAppName('PsychoPy3')
if showSplash: #showSplash:
# show splash screen
splashFile = os.path.join(
self.prefs.paths['resources'], 'psychopySplash.png')
splashImage = wx.Image(name=splashFile)
splashImage.ConvertAlphaToMask()
splash = AS.AdvancedSplash(None, bitmap=splashImage.ConvertToBitmap(),
timeout=3000,
agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN,
) # transparency?
w, h = splashImage.GetSize()
splash.SetTextPosition((int(340), h-30))
splash.SetText(_translate("Copyright (C) 2021 OpenScienceTools.org"))
else:
splash = None
# SLOW IMPORTS - these need to be imported after splash screen starts
# but then that they end up being local so keep track in self
from psychopy.compatibility import checkCompatibility
# import coder and builder here but only use them later
from psychopy.app import coder, builder, runner, dialogs
if '--firstrun' in sys.argv:
del sys.argv[sys.argv.index('--firstrun')]
self.firstRun = True
if 'lastVersion' not in self.prefs.appData:
# must be before 1.74.00
last = self.prefs.appData['lastVersion'] = '1.73.04'
self.firstRun = True
else:
last = self.prefs.appData['lastVersion']
if self.firstRun and not self.testMode:
pass
# setup links for URLs
# on a mac, don't exit when the last frame is deleted, just show menu
if sys.platform == 'darwin':
self.menuFrame = MenuFrame(parent=None, app=self)
# fetch prev files if that's the preference
if self.prefs.coder['reloadPrevFiles']:
scripts = self.prefs.appData['coder']['prevFiles']
else:
scripts = []
appKeys = list(self.prefs.appData['builder'].keys())
if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys):
exps = self.prefs.appData['builder']['prevFiles']
else:
exps = []
runlist = []
self.dpi = int(wx.GetDisplaySize()[0] /
float(wx.GetDisplaySizeMM()[0]) * 25.4)
# detect retina displays
self.isRetina = self.dpi>80 and wx.Platform == '__WXMAC__'
if self.isRetina:
fontScale = 1.2 # fonts are looking tiny on macos (only retina?) right now
else:
fontScale = 1
# adjust dpi to something reasonable
if not (50 < self.dpi < 120):
self.dpi = 80 # dpi was unreasonable, make one up
# Manage fonts
if sys.platform == 'win32':
# wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32
self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
else:
self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
# rescale for tiny retina fonts
if hasattr(wx.Font, "AddPrivateFont") and sys.platform != "darwin":
# Load packaged fonts if possible
for fontFile in (Path(__file__).parent / "Resources" / "fonts").glob("*"):
if fontFile.suffix in ['.ttf', '.truetype']:
wx.Font.AddPrivateFont(str(fontFile))
# Set fonts as those loaded
self._codeFont = wx.Font(wx.FontInfo(self._mainFont.GetPointSize()).FaceName("JetBrains Mono"))
else:
# Get system defaults if can't load fonts
try:
self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
except wx._core.wxAssertionError:
# if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN
self._codeFont = wx.Font(self._mainFont.GetPointSize(),
wx.FONTFAMILY_TELETYPE,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
if self.isRetina:
self._codeFont.SetPointSize(int(self._codeFont.GetPointSize()*fontScale))
self._mainFont.SetPointSize(int(self._mainFont.GetPointSize()*fontScale))
# that gets most of the properties of _codeFont but the FaceName
# FaceName is set in the setting of the theme:
self.theme = self.prefs.app['theme']
# removed Aug 2017: on newer versions of wx (at least on mac)
# this looks too big
# if hasattr(self._mainFont, 'Larger'):
# # Font.Larger is available since wyPython version 2.9.1
# # PsychoPy still supports 2.8 (see ensureMinimal above)
# self._mainFont = self._mainFont.Larger()
# self._codeFont.SetPointSize(
# self._mainFont.GetPointSize()) # unify font size
# create both frame for coder/builder as necess
if splash:
splash.SetText(_translate(" Creating frames..."))
# Parse incoming call
parser = argparse.ArgumentParser(prog=self)
parser.add_argument('--builder', dest='builder', action="store_true")
parser.add_argument('-b', dest='builder', action="store_true")
parser.add_argument('--coder', dest='coder', action="store_true")
parser.add_argument('-c', dest='coder', action="store_true")
parser.add_argument('--runner', dest='runner', action="store_true")
parser.add_argument('-r', dest='runner', action="store_true")
parser.add_argument('-x', dest='direct', action='store_true')
view, args = parser.parse_known_args(sys.argv)
# Check from filetype if any windows need to be open
if any(arg.endswith('.psyexp') for arg in args):
view.builder = True
exps = [file for file in args if file.endswith('.psyexp')]
if any(arg.endswith('.psyrun') for arg in args):
view.runner = True
runlist = [file for file in args if file.endswith('.psyrun')]
# If still no window specified, use default from prefs
if not any(getattr(view, key) for key in ['builder', 'coder', 'runner']):
if self.prefs.app['defaultView'] in view:
setattr(view, self.prefs.app['defaultView'], True)
elif self.prefs.app['defaultView'] == 'all':
view.builder = True
view.coder = True
view.runner = True
# set the dispatcher for standard output
self.stdStreamDispatcher = console.StdStreamDispatcher(self)
self.stdStreamDispatcher.redirect()
# Create windows
if view.runner:
self.showRunner(fileList=runlist)
if view.coder:
self.showCoder(fileList=scripts)
if view.builder:
self.showBuilder(fileList=exps)
if view.direct:
self.showRunner()
for exp in [file for file in args if file.endswith('.psyexp') or file.endswith('.py')]:
self.runner.panel.runFile(exp)
# send anonymous info to www.psychopy.org/usage.php
# please don't disable this, it's important for PsychoPy's development
self._latestAvailableVersion = None
self.updater = None
self.news = None
self.tasks = None
prefsConn = self.prefs.connections
ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True)
# tell the user what has changed
if not ok and not self.firstRun and not self.testMode:
title = _translate("Compatibility information")
dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info',
title=title)
dlg.ShowModal()
if (self.prefs.app['showStartupTips']
and not self.testMode and not blockTips):
tipFile = os.path.join(
self.prefs.paths['resources'], _translate("tips.txt"))
tipIndex = self.prefs.appData['tipIndex']
if parse_version(wx.__version__) >= parse_version('4.0.0a1'):
tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex)
showTip = wx.adv.ShowTip(None, tp)
else:
tp = wx.CreateFileTipProvider(tipFile, tipIndex)
showTip = wx.ShowTip(None, tp)
self.prefs.appData['tipIndex'] = tp.GetCurrentTip()
self.prefs.saveAppData()
self.prefs.app['showStartupTips'] = showTip
self.prefs.saveUserPrefs()
self.Bind(wx.EVT_IDLE, self.onIdle)
# doing this once subsequently enables the app to open & switch among
# wx-windows on some platforms (Mac 10.9.4) with wx-3.0:
v = parse_version
if sys.platform == 'darwin':
if v('3.0') <= v(wx.version()) < v('4.0'):
_Showgui_Hack() # returns ~immediately, no display
# focus stays in never-land, so bring back to the app:
if prefs.app['defaultView'] in ['all', 'builder', 'coder', 'runner']:
self.showBuilder()
else:
self.showCoder()
# after all windows are created (so errors flushed) create output
self._appLoaded = True
if self.coder:
self.coder.setOutputWindow() # takes control of sys.stdout
# flush any errors to the last run log file
logging.flush()
sys.stdout.flush()
# we wanted debug mode while loading but safe to go back to info mode
if not self.prefs.app['debugMode']:
logging.console.setLevel(logging.INFO)
return True
@property
def appLoaded(self):
"""`True` if the app has been fully loaded (`bool`)."""
return self._appLoaded
def _wizard(self, selector, arg=''):
from psychopy import core
wizard = os.path.join(
self.prefs.paths['psychopy'], 'tools', 'wizard.py')
so, se = core.shellCall(
[sys.executable, wizard, selector, arg], stderr=True)
if se and self.prefs.app['debugMode']:
print(se) # stderr contents; sometimes meaningless
def firstrunWizard(self):
self._wizard('--config', '--firstrun')
# wizard typically creates html report file but user can manually skip
reportPath = os.path.join(
self.prefs.paths['userPrefsDir'], 'firstrunReport.html')
if os.path.exists(reportPath):
with io.open(reportPath, 'r', encoding='utf-8-sig') as f:
report = f.read()
if 'Configuration problem' in report:
# fatal error was encountered (currently only if bad drivers)
# ensure wizard will be triggered again:
del self.prefs.appData['lastVersion']
self.prefs.saveAppData()
def benchmarkWizard(self, evt=None):
self._wizard('--benchmark')
def csvFromPsydat(self, evt=None):
from psychopy import gui
from psychopy.tools.filetools import fromFile
prompt = _translate("Select .psydat file(s) to extract")
names = gui.fileOpenDlg(allowed='*.psydat', prompt=prompt)
for name in names or []:
filePsydat = os.path.abspath(name)
print("psydat: {0}".format(filePsydat))
exp = fromFile(filePsydat)
if filePsydat.endswith('.psydat'):
fileCsv = filePsydat[:-7]
else:
fileCsv = filePsydat
fileCsv += '.csv'
exp.saveAsWideText(fileCsv)
print(' -->: {0}'.format(os.path.abspath(fileCsv)))
def checkUpdates(self, evt):
# if we have internet and haven't yet checked for updates then do so
# we have a network connection but not yet tried an update
if self._latestAvailableVersion not in [-1, None]:
# change IDLE routine so we won't come back here
self.Unbind(wx.EVT_IDLE) # unbind all EVT_IDLE methods from app
self.Bind(wx.EVT_IDLE, self.onIdle)
# create updater (which will create dialogs as needed)
self.updater = connections.Updater(app=self)
self.updater.latest = self._latestAvailableVersion
self.updater.suggestUpdate(confirmationDlg=False)
evt.Skip()
def getPrimaryDisplaySize(self):
"""Get the size of the primary display (whose coords start (0,0))
"""
return list(wx.Display(0).GetGeometry())[2:]
def makeAccelTable(self):
"""Makes a standard accelorator table and returns it. This then needs
to be set for the Frame using self.SetAccelerator(table)
"""
def parseStr(inStr):
accel = 0
if 'ctrl' in inStr.lower():
accel += wx.ACCEL_CTRL
if 'shift' in inStr.lower():
accel += wx.ACCEL_SHIFT
if 'alt' in inStr.lower():
accel += wx.ACCEL_ALT
return accel, ord(inStr[-1])
# create a list to link IDs to key strings
keyCodesDict = {}
keyCodesDict[self.keys['copy']] = wx.ID_COPY
keyCodesDict[self.keys['cut']] = wx.ID_CUT
keyCodesDict[self.keys['paste']] = wx.ID_PASTE
keyCodesDict[self.keys['undo']] = wx.ID_UNDO
keyCodesDict[self.keys['redo']] = wx.ID_REDO
keyCodesDict[self.keys['save']] = wx.ID_SAVE
keyCodesDict[self.keys['saveAs']] = wx.ID_SAVEAS
keyCodesDict[self.keys['close']] = wx.ID_CLOSE
keyCodesDict[self.keys['redo']] = wx.ID_REDO
keyCodesDict[self.keys['quit']] = wx.ID_EXIT
# parse the key strings and convert to accelerator entries
entries = []
for keyStr, code in list(keyCodesDict.items()):
mods, key = parseStr(keyStr)
entry = wx.AcceleratorEntry(mods, key, code)
entries.append(entry)
table = wx.AcceleratorTable(entries)
return table
def updateWindowMenu(self):
"""Update items within Window menu to reflect open windows"""
# Update checks on menus in all frames
for frame in self.getAllFrames():
if hasattr(frame, "windowMenu"):
frame.windowMenu.updateFrames()
def showCoder(self, event=None, fileList=None):
# have to reimport because it is only local to __init__ so far
from . import coder
if self.coder is None:
title = "PsychoPy Coder (IDE) (v%s)"
wx.BeginBusyCursor()
self.coder = coder.CoderFrame(None, -1,
title=title % self.version,
files=fileList, app=self)
self.updateWindowMenu()
wx.EndBusyCursor()
else:
# Set output window and standard streams
self.coder.setOutputWindow(True)
self.coder.Show(True)
self.SetTopWindow(self.coder)
self.coder.Raise()
def newBuilderFrame(self, event=None, fileName=None):
# have to reimport because it is ony local to __init__ so far
wx.BeginBusyCursor()
from .builder.builder import BuilderFrame
title = "PsychoPy Builder (v%s)"
self.builder = BuilderFrame(None, -1,
title=title % self.version,
fileName=fileName, app=self)
self.builder.Show(True)
self.builder.Raise()
self.SetTopWindow(self.builder)
self.updateWindowMenu()
wx.EndBusyCursor()
return self.builder
def showBuilder(self, event=None, fileList=()):
# have to reimport because it is only local to __init__ so far
from psychopy.app import builder
for fileName in fileList:
if os.path.isfile(fileName):
self.newBuilderFrame(fileName=fileName)
# create an empty Builder view if needed
if len(self.getAllFrames(frameType="builder")) == 0:
self.newBuilderFrame()
# loop through all frames, from the back bringing each forward
for thisFrame in self.getAllFrames(frameType='builder'):
thisFrame.Show(True)
thisFrame.Raise()
self.SetTopWindow(thisFrame)
def showRunner(self, event=None, fileList=[]):
if not self.runner:
self.runner = self.newRunnerFrame()
if not self.testMode:
self.runner.Show()
self.runner.Raise()
self.SetTopWindow(self.runner)
# Runner captures standard streams until program closed
if self.runner and not self.testMode:
sys.stderr = sys.stdout = self.stdStreamDispatcher
def newRunnerFrame(self, event=None):
# have to reimport because it is only local to __init__ so far
from .runner.runner import RunnerFrame
title = "PsychoPy Runner (v{})".format(self.version)
wx.BeginBusyCursor()
self.runner = RunnerFrame(parent=None,
id=-1,
title=title,
app=self)
self.updateWindowMenu()
wx.EndBusyCursor()
return self.runner
def OnDrop(self, x, y, files):
"""Not clear this method ever gets called!"""
logging.info("Got Files")
def MacOpenFile(self, fileName):
if fileName.endswith('psychopyApp.py'):
# in wx4 on mac this is called erroneously by App.__init__
# if called like `python psychopyApp.py`
return
logging.debug('PsychoPyApp: Received Mac file dropped event')
if fileName.endswith('.py'):
if self.coder is None:
self.showCoder()
self.coder.setCurrentDoc(fileName)
elif fileName.endswith('.psyexp'):
self.newBuilderFrame(fileName=fileName)
def MacReopenApp(self):
"""Called when the doc icon is clicked, and ???"""
self.GetTopWindow().Raise()
def openIPythonNotebook(self, event=None):
"""Note that right now this is bad because it ceases all activity in
the main wx loop and the app has to be quit. We need it to run from
a separate process? The necessary depends (zmq and tornado) were
included from v1.78 onwards in the standalone
"""
import IPython.frontend.html.notebook.notebookapp as nb
instance = nb.launch_new_instance()
def openUpdater(self, event=None):
from psychopy.app import connections
dlg = connections.InstallUpdateDialog(parent=None, ID=-1, app=self)
def colorPicker(self, event=None):
"""Open color-picker, sets clip-board to string [r,g,b].
Note: units are psychopy -1..+1 rgb units to three decimal places,
preserving 24-bit color.
"""
if self.coder is None:
return
document = self.coder.currentDoc
dlg = PsychoColorPicker(document) # doesn't need a parent
dlg.ShowModal()
dlg.Destroy()
if event is not None:
event.Skip()
def openMonitorCenter(self, event):
from psychopy.monitors import MonitorCenter
self.monCenter = MonitorCenter.MainFrame(
None, 'PsychoPy Monitor Center')
self.monCenter.Show(True)
def terminateHubProcess(self):
"""
Send a UDP message to iohub informing it to exit.
Use this when force quitting the experiment script process so iohub
knows to exit as well.
If message is not sent within 1 second, or the iohub server
address in incorrect,the issue is logged.
"""
sock = None
try:
logging.debug('PsychoPyApp: terminateHubProcess called.')
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1.0)
iohubAddress = '127.0.0.1', 9034
import msgpack
txData = msgpack.Packer().pack(('STOP_IOHUB_SERVER',))
return sock.sendto(txData, iohubAddress)
except socket.error as e:
msg = 'PsychoPyApp: terminateHubProcess socket.error: %s'
logging.debug(msg % str(e))
except socket.herror as e:
msg = 'PsychoPyApp: terminateHubProcess socket.herror: %s'
logging.debug(msg % str(e))
except socket.gaierror as e:
msg = 'PsychoPyApp: terminateHubProcess socket.gaierror: %s'
logging.debug(msg % str(e))
except socket.timeout as e:
msg = 'PsychoPyApp: terminateHubProcess socket.timeout: %s'
logging.debug(msg % str(e))
except Exception as e:
msg = 'PsychoPyApp: terminateHubProcess exception: %s'
logging.debug(msg % str(e))
finally:
if sock:
sock.close()
logging.debug('PsychoPyApp: terminateHubProcess completed.')
def quit(self, event=None):
logging.debug('PsychoPyApp: Quitting...')
self.quitting = True
# garbage collect the projects before sys.exit
projects.pavlovia.knownUsers = None
projects.pavlovia.knownProjects = None
# see whether any files need saving
for frame in self.getAllFrames():
try: # will fail if the frame has been shut somehow elsewhere
ok = frame.checkSave()
except Exception:
ok = False
logging.debug("PsychopyApp: exception when saving")
if not ok:
logging.debug('PsychoPyApp: User cancelled shutdown')
return # user cancelled quit
# save info about current frames for next run
if self.coder and len(self.getAllFrames("builder")) == 0:
self.prefs.appData['lastFrame'] = 'coder'
elif self.coder is None:
self.prefs.appData['lastFrame'] = 'builder'
else:
self.prefs.appData['lastFrame'] = 'both'
self.prefs.appData['lastVersion'] = self.version
# update app data while closing each frame
# start with an empty list to be appended by each frame
self.prefs.appData['builder']['prevFiles'] = []
self.prefs.appData['coder']['prevFiles'] = []
# write plugins config if changed during the session
# saveStartUpPluginsConfig()
for frame in self.getAllFrames():
try:
frame.closeFrame(event=event, checkSave=False)
# must do this before destroying the frame?
self.prefs.saveAppData()
except Exception:
pass # we don't care if this fails - we're quitting anyway
#self.Destroy()
# Reset streams back to default
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if not self.testMode:
sys.exit()
def showPrefs(self, event):
from psychopy.app.preferencesDlg import PreferencesDlg
logging.debug('PsychoPyApp: Showing prefs dlg')
prefsDlg = PreferencesDlg(app=self)
prefsDlg.ShowModal()
prefsDlg.Destroy()
def showAbout(self, event):
logging.debug('PsychoPyApp: Showing about dlg')
with io.open(os.path.join(self.prefs.paths['psychopy'], 'LICENSE.txt'),
'r', encoding='utf-8-sig') as f:
license = f.read()
msg = _translate(
"For stimulus generation and experimental control in Python.\n"
"PsychoPy depends on your feedback. If something doesn't work\n"
"then let us know at <EMAIL>")
if parse_version(wx.__version__) >= parse_version('4.0a1'):
info = wx.adv.AboutDialogInfo()
showAbout = wx.adv.AboutBox
else:
info = wx.AboutDialogInfo()
showAbout = wx.AboutBox
if wx.version() >= '3.':
icon = os.path.join(self.prefs.paths['resources'], 'psychopy.png')
info.SetIcon(wx.Icon(icon, wx.BITMAP_TYPE_PNG, 128, 128))
info.SetName('PsychoPy')
info.SetVersion('v' + psychopy.__version__)
info.SetDescription(msg)
info.SetCopyright('(C) 2002-2021 <NAME>')
info.SetWebSite('https://www.psychopy.org')
info.SetLicence(license)
# developers
devNames = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
u'<NAME>\xF8v',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
u'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<EMAIL>]',
'<EMAIL>drjen <EMAIL>]'
]
docNames = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>'
]
devNames.sort()
intNames = [
'Hiroyuki Sogo'
]
intNames.sort()
for name in devNames:
info.AddDeveloper(name)
for name in docNames:
info.AddDocWriter(name)
for name in intNames:
info.AddTranslator(name)
if not self.testMode:
showAbout(info)
def showNews(self, event=None):
connections.showNews(self, checkPrev=False)
def showSystemInfo(self, event=None):
"""Show system information."""
from psychopy.app.sysInfoDlg import SystemInfoDialog
dlg = SystemInfoDialog(None)
dlg.Show()
def followLink(self, event=None, url=None):
"""Follow either an event id (= a key to an url defined in urls.py)
or follow a complete url (a string beginning "http://")
"""
if event is not None:
wx.LaunchDefaultBrowser(self.urls[event.GetId()])
elif url is not None:
wx.LaunchDefaultBrowser(url)
def getAllFrames(self, frameType=None):
"""Get a list of frames, optionally filtered by a particular kind
(which can be "builder", "coder", "project")
"""
frames = []
for frameRef in self._allFrames:
frame = frameRef()
if (not frame):
self._allFrames.remove(frameRef) # has been deleted
continue
elif frameType and frame.frameType != frameType:
continue
frames.append(frame)
return frames
def trackFrame(self, frame):
"""Keep track of an open frame (stores a weak reference to the frame
which will probably have a regular reference to the app)
"""
self._allFrames.append(weakref.ref(frame))
def forgetFrame(self, frame):
"""Keep track of an open frame (stores a weak reference to the frame
which will probably have a regular reference to the app)
"""
for entry in self._allFrames:
if entry() == frame: # is a weakref
self._allFrames.remove(entry)
def onIdle(self, evt):
from . import idle
idle.doIdleTasks(app=self)
evt.Skip()
def onThemeChange(self, event):
"""Handles a theme change event (from a window with a themesMenu)"""
win = event.EventObject.Window
newTheme = win.themesMenu.FindItemById(event.GetId()).ItemLabel
prefs.app['theme'] = newTheme
prefs.saveUserPrefs()
self.theme = newTheme
@property
def theme(self):
"""The theme to be used through the application"""
return prefs.app['theme']
@theme.setter
def theme(self, value):
"""The theme to be used through the application"""
themes.ThemeMixin.loadThemeSpec(self, themeName=value)
prefs.app['theme'] = value
self._currentThemeSpec = themes.ThemeMixin.spec
codeFont = themes.ThemeMixin.codeColors['base']['font']
# On OSX 10.15 Catalina at least calling SetFaceName with 'AppleSystemUIFont' fails.
# So this fix checks to see if changing the font name invalidates the font.
# if so rollback to the font before attempted change.
# Note that wx.Font uses referencing and copy-on-write so we need to force creation of a copy
# witht he wx.Font() call. Otherwise you just get reference to the font that gets borked by SetFaceName()
# -<NAME>
beforesetface = wx.Font(self._codeFont)
success = self._codeFont.SetFaceName(codeFont)
if not (success):
self._codeFont = beforesetface
# Apply theme
self._applyAppTheme()
def _applyAppTheme(self):
"""Overrides ThemeMixin for this class"""
self.iconCache.setTheme(themes.ThemeMixin)
for frameRef in self._allFrames:
frame = frameRef()
if hasattr(frame, '_applyAppTheme'):
frame._applyAppTheme()
if __name__ == '__main__':
# never run; stopped earlier at cannot do relative import in a non-package
sys.exit("Do not launch the app from this script -"
"use python psychopyApp.py instead")
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, division, print_function
from builtins import str
from builtins import object
from pathlib import Path
from psychopy.app.colorpicker import PsychoColorPicker
profiling = False # turning on will save profile files in currDir
import sys
import argparse
import psychopy
from psychopy import prefs
from pkg_resources import parse_version
from psychopy.constants import PY3
from . import urls
from . import frametracker
from . import themes
from . import console
import io
if not hasattr(sys, 'frozen'):
try:
import wxversion
haveWxVersion = True
except ImportError:
haveWxVersion = False # if wxversion doesn't exist hope for the best
if haveWxVersion:
wxversion.ensureMinimal('2.8') # because this version has agw
import wx
try:
from agw import advancedsplash as AS
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.advancedsplash as AS
# from .plugin_manager import saveStartUpPluginsConfig
from psychopy.localization import _translate
# NB keep imports to a minimum here because splash screen has not yet shown
# e.g. coder and builder are imported during app.__init__ because they
# take a while
# needed by splash screen for the path to resources/psychopySplash.png
import ctypes
from psychopy import logging, __version__
from psychopy import projects
from . import connections
from .utils import FileDropTarget
import os
import weakref
# knowing if the user has admin priv is generally a good idea for security.
# not actually needed; psychopy should never need anything except normal user
# see older versions for code to detect admin (e.g., v 1.80.00)
if not PY3 and sys.platform == 'darwin':
blockTips = True
else:
blockTips = False
# Enable high-dpi support if on Windows. This fixes blurry text rendering.
if sys.platform == 'win32':
# get the preference for high DPI
if 'highDPI' in psychopy.prefs.app.keys(): # check if we have the option
enableHighDPI = psychopy.prefs.app['highDPI']
# check if we have OS support for it
if enableHighDPI:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(enableHighDPI)
except OSError:
logging.warn(
"High DPI support is not appear to be supported by this version"
" of Windows. Disabling in preferences.")
psychopy.prefs.app['highDPI'] = False
psychopy.prefs.saveUserPrefs()
class MenuFrame(wx.Frame, themes.ThemeMixin):
"""A simple empty frame with a menubar, should be last frame closed on mac
"""
def __init__(self, parent=None, ID=-1, app=None, title="PsychoPy"):
wx.Frame.__init__(self, parent, ID, title, size=(1, 1))
self.app = app
self.menuBar = wx.MenuBar()
self.viewMenu = wx.Menu()
self.menuBar.Append(self.viewMenu, _translate('&View'))
mtxt = _translate("&Open Builder view\t%s")
self.app.IDs.openBuilderView = self.viewMenu.Append(wx.ID_ANY,
mtxt,
_translate("Open a new Builder view")).GetId()
self.Bind(wx.EVT_MENU, self.app.showBuilder,
id=self.app.IDs.openBuilderView)
mtxt = _translate("&Open Coder view\t%s")
self.app.IDs.openCoderView = self.viewMenu.Append(wx.ID_ANY,
mtxt,
_translate("Open a new Coder view")).GetId()
self.Bind(wx.EVT_MENU, self.app.showCoder,
id=self.app.IDs.openCoderView)
mtxt = _translate("&Quit\t%s")
item = self.viewMenu.Append(wx.ID_EXIT, mtxt % self.app.keys['quit'],
_translate("Terminate the program"))
self.Bind(wx.EVT_MENU, self.app.quit, id=item.GetId())
self.SetMenuBar(self.menuBar)
self.Show()
class IDStore(dict):
"""A simpe class that works like a dict but you can access attributes
like standard python attrs. Useful to replace the previous pre-made
app.IDs (wx.NewID() is no longer recommended or safe)
"""
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
class _Showgui_Hack(object):
"""Class with side-effect of restoring wx window switching under wx-3.0
- might only be needed on some platforms (Mac 10.9.4 needs it for me);
- needs to be launched as an external script
- needs to be separate: seg-faults as method of PsychoPyApp or in-lined
- unlear why it works or what the deeper issue is, blah
- called at end of PsychoPyApp.onInit()
"""
def __init__(self):
super(_Showgui_Hack, self).__init__()
from psychopy import core
import os
# should be writable:
noopPath = os.path.join(psychopy.prefs.paths['userPrefsDir'],
'showgui_hack.py')
# code to open & immediately close a gui (= invisibly):
if not os.path.isfile(noopPath):
code = """from psychopy import gui
dlg = gui.Dlg().Show() # non-blocking
try:
dlg.Destroy() # might as well
except Exception:
pass"""
with open(noopPath, 'wb') as fd:
fd.write(bytes(code))
# append 'w' for pythonw seems not needed
core.shellCall([sys.executable, noopPath])
class PsychoPyApp(wx.App, themes.ThemeMixin):
_called_from_test = False # pytest needs to change this
def __init__(self, arg=0, testMode=False, **kwargs):
"""With a wx.App some things get done here, before App.__init__
then some further code is launched in OnInit() which occurs after
"""
if profiling:
import cProfile, time
profile = cProfile.Profile()
profile.enable()
t0 = time.time()
self._appLoaded = False # set to true when all frames are created
self.coder = None
self.runner = None
self.version = psychopy.__version__
# set default paths and prefs
self.prefs = psychopy.prefs
self._currentThemeSpec = None
self.keys = self.prefs.keys
self.prefs.pageCurrent = 0 # track last-viewed page, can return there
self.IDs = IDStore()
self.urls = urls.urls
self.quitting = False
# check compatibility with last run version (before opening windows)
self.firstRun = False
self.testMode = testMode
self._stdout = sys.stdout
self._stderr = sys.stderr
self._stdoutFrame = None
self.iconCache = themes.IconCache()
if not self.testMode:
self._lastRunLog = open(os.path.join(
self.prefs.paths['userPrefsDir'], 'last_app_load.log'),
'w')
sys.stderr = sys.stdout = lastLoadErrs = self._lastRunLog
logging.console.setLevel(logging.DEBUG)
# indicates whether we're running for testing purposes
self.osfSession = None
self.pavloviaSession = None
self.copiedRoutine = None
self.copiedCompon = None
self._allFrames = frametracker.openFrames # ordered; order updated with self.onNewTopWindow
wx.App.__init__(self, arg)
# import localization after wx:
from psychopy import localization # needed by splash screen
self.localization = localization
self.locale = localization.setLocaleWX()
self.locale.AddCatalog(self.GetAppName())
logging.flush()
self.onInit(testMode=testMode, **kwargs)
if profiling:
profile.disable()
print("time to load app = {:.2f}".format(time.time()-t0))
profile.dump_stats('profileLaunchApp.profile')
logging.flush()
# set the exception hook to present unhandled errors in a dialog
if not PsychoPyApp._called_from_test: #NB class variable not self
from psychopy.app.errorDlg import exceptionCallback
sys.excepthook = exceptionCallback
def onInit(self, showSplash=True, testMode=False):
"""This is launched immediately *after* the app initialises with wx
:Parameters:
testMode: bool
"""
self.SetAppName('PsychoPy3')
if showSplash: #showSplash:
# show splash screen
splashFile = os.path.join(
self.prefs.paths['resources'], 'psychopySplash.png')
splashImage = wx.Image(name=splashFile)
splashImage.ConvertAlphaToMask()
splash = AS.AdvancedSplash(None, bitmap=splashImage.ConvertToBitmap(),
timeout=3000,
agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN,
) # transparency?
w, h = splashImage.GetSize()
splash.SetTextPosition((int(340), h-30))
splash.SetText(_translate("Copyright (C) 2021 OpenScienceTools.org"))
else:
splash = None
# SLOW IMPORTS - these need to be imported after splash screen starts
# but then that they end up being local so keep track in self
from psychopy.compatibility import checkCompatibility
# import coder and builder here but only use them later
from psychopy.app import coder, builder, runner, dialogs
if '--firstrun' in sys.argv:
del sys.argv[sys.argv.index('--firstrun')]
self.firstRun = True
if 'lastVersion' not in self.prefs.appData:
# must be before 1.74.00
last = self.prefs.appData['lastVersion'] = '1.73.04'
self.firstRun = True
else:
last = self.prefs.appData['lastVersion']
if self.firstRun and not self.testMode:
pass
# setup links for URLs
# on a mac, don't exit when the last frame is deleted, just show menu
if sys.platform == 'darwin':
self.menuFrame = MenuFrame(parent=None, app=self)
# fetch prev files if that's the preference
if self.prefs.coder['reloadPrevFiles']:
scripts = self.prefs.appData['coder']['prevFiles']
else:
scripts = []
appKeys = list(self.prefs.appData['builder'].keys())
if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys):
exps = self.prefs.appData['builder']['prevFiles']
else:
exps = []
runlist = []
self.dpi = int(wx.GetDisplaySize()[0] /
float(wx.GetDisplaySizeMM()[0]) * 25.4)
# detect retina displays
self.isRetina = self.dpi>80 and wx.Platform == '__WXMAC__'
if self.isRetina:
fontScale = 1.2 # fonts are looking tiny on macos (only retina?) right now
else:
fontScale = 1
# adjust dpi to something reasonable
if not (50 < self.dpi < 120):
self.dpi = 80 # dpi was unreasonable, make one up
# Manage fonts
if sys.platform == 'win32':
# wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32
self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
else:
self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
# rescale for tiny retina fonts
if hasattr(wx.Font, "AddPrivateFont") and sys.platform != "darwin":
# Load packaged fonts if possible
for fontFile in (Path(__file__).parent / "Resources" / "fonts").glob("*"):
if fontFile.suffix in ['.ttf', '.truetype']:
wx.Font.AddPrivateFont(str(fontFile))
# Set fonts as those loaded
self._codeFont = wx.Font(wx.FontInfo(self._mainFont.GetPointSize()).FaceName("JetBrains Mono"))
else:
# Get system defaults if can't load fonts
try:
self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
except wx._core.wxAssertionError:
# if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN
self._codeFont = wx.Font(self._mainFont.GetPointSize(),
wx.FONTFAMILY_TELETYPE,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
if self.isRetina:
self._codeFont.SetPointSize(int(self._codeFont.GetPointSize()*fontScale))
self._mainFont.SetPointSize(int(self._mainFont.GetPointSize()*fontScale))
# that gets most of the properties of _codeFont but the FaceName
# FaceName is set in the setting of the theme:
self.theme = self.prefs.app['theme']
# removed Aug 2017: on newer versions of wx (at least on mac)
# this looks too big
# if hasattr(self._mainFont, 'Larger'):
# # Font.Larger is available since wyPython version 2.9.1
# # PsychoPy still supports 2.8 (see ensureMinimal above)
# self._mainFont = self._mainFont.Larger()
# self._codeFont.SetPointSize(
# self._mainFont.GetPointSize()) # unify font size
# create both frame for coder/builder as necess
if splash:
splash.SetText(_translate(" Creating frames..."))
# Parse incoming call
parser = argparse.ArgumentParser(prog=self)
parser.add_argument('--builder', dest='builder', action="store_true")
parser.add_argument('-b', dest='builder', action="store_true")
parser.add_argument('--coder', dest='coder', action="store_true")
parser.add_argument('-c', dest='coder', action="store_true")
parser.add_argument('--runner', dest='runner', action="store_true")
parser.add_argument('-r', dest='runner', action="store_true")
parser.add_argument('-x', dest='direct', action='store_true')
view, args = parser.parse_known_args(sys.argv)
# Check from filetype if any windows need to be open
if any(arg.endswith('.psyexp') for arg in args):
view.builder = True
exps = [file for file in args if file.endswith('.psyexp')]
if any(arg.endswith('.psyrun') for arg in args):
view.runner = True
runlist = [file for file in args if file.endswith('.psyrun')]
# If still no window specified, use default from prefs
if not any(getattr(view, key) for key in ['builder', 'coder', 'runner']):
if self.prefs.app['defaultView'] in view:
setattr(view, self.prefs.app['defaultView'], True)
elif self.prefs.app['defaultView'] == 'all':
view.builder = True
view.coder = True
view.runner = True
# set the dispatcher for standard output
self.stdStreamDispatcher = console.StdStreamDispatcher(self)
self.stdStreamDispatcher.redirect()
# Create windows
if view.runner:
self.showRunner(fileList=runlist)
if view.coder:
self.showCoder(fileList=scripts)
if view.builder:
self.showBuilder(fileList=exps)
if view.direct:
self.showRunner()
for exp in [file for file in args if file.endswith('.psyexp') or file.endswith('.py')]:
self.runner.panel.runFile(exp)
# send anonymous info to www.psychopy.org/usage.php
# please don't disable this, it's important for PsychoPy's development
self._latestAvailableVersion = None
self.updater = None
self.news = None
self.tasks = None
prefsConn = self.prefs.connections
ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True)
# tell the user what has changed
if not ok and not self.firstRun and not self.testMode:
title = _translate("Compatibility information")
dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info',
title=title)
dlg.ShowModal()
if (self.prefs.app['showStartupTips']
and not self.testMode and not blockTips):
tipFile = os.path.join(
self.prefs.paths['resources'], _translate("tips.txt"))
tipIndex = self.prefs.appData['tipIndex']
if parse_version(wx.__version__) >= parse_version('4.0.0a1'):
tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex)
showTip = wx.adv.ShowTip(None, tp)
else:
tp = wx.CreateFileTipProvider(tipFile, tipIndex)
showTip = wx.ShowTip(None, tp)
self.prefs.appData['tipIndex'] = tp.GetCurrentTip()
self.prefs.saveAppData()
self.prefs.app['showStartupTips'] = showTip
self.prefs.saveUserPrefs()
self.Bind(wx.EVT_IDLE, self.onIdle)
# doing this once subsequently enables the app to open & switch among
# wx-windows on some platforms (Mac 10.9.4) with wx-3.0:
v = parse_version
if sys.platform == 'darwin':
if v('3.0') <= v(wx.version()) < v('4.0'):
_Showgui_Hack() # returns ~immediately, no display
# focus stays in never-land, so bring back to the app:
if prefs.app['defaultView'] in ['all', 'builder', 'coder', 'runner']:
self.showBuilder()
else:
self.showCoder()
# after all windows are created (so errors flushed) create output
self._appLoaded = True
if self.coder:
self.coder.setOutputWindow() # takes control of sys.stdout
# flush any errors to the last run log file
logging.flush()
sys.stdout.flush()
# we wanted debug mode while loading but safe to go back to info mode
if not self.prefs.app['debugMode']:
logging.console.setLevel(logging.INFO)
return True
@property
def appLoaded(self):
"""`True` if the app has been fully loaded (`bool`)."""
return self._appLoaded
def _wizard(self, selector, arg=''):
from psychopy import core
wizard = os.path.join(
self.prefs.paths['psychopy'], 'tools', 'wizard.py')
so, se = core.shellCall(
[sys.executable, wizard, selector, arg], stderr=True)
if se and self.prefs.app['debugMode']:
print(se) # stderr contents; sometimes meaningless
def firstrunWizard(self):
self._wizard('--config', '--firstrun')
# wizard typically creates html report file but user can manually skip
reportPath = os.path.join(
self.prefs.paths['userPrefsDir'], 'firstrunReport.html')
if os.path.exists(reportPath):
with io.open(reportPath, 'r', encoding='utf-8-sig') as f:
report = f.read()
if 'Configuration problem' in report:
# fatal error was encountered (currently only if bad drivers)
# ensure wizard will be triggered again:
del self.prefs.appData['lastVersion']
self.prefs.saveAppData()
def benchmarkWizard(self, evt=None):
self._wizard('--benchmark')
def csvFromPsydat(self, evt=None):
from psychopy import gui
from psychopy.tools.filetools import fromFile
prompt = _translate("Select .psydat file(s) to extract")
names = gui.fileOpenDlg(allowed='*.psydat', prompt=prompt)
for name in names or []:
filePsydat = os.path.abspath(name)
print("psydat: {0}".format(filePsydat))
exp = fromFile(filePsydat)
if filePsydat.endswith('.psydat'):
fileCsv = filePsydat[:-7]
else:
fileCsv = filePsydat
fileCsv += '.csv'
exp.saveAsWideText(fileCsv)
print(' -->: {0}'.format(os.path.abspath(fileCsv)))
def checkUpdates(self, evt):
# if we have internet and haven't yet checked for updates then do so
# we have a network connection but not yet tried an update
if self._latestAvailableVersion not in [-1, None]:
# change IDLE routine so we won't come back here
self.Unbind(wx.EVT_IDLE) # unbind all EVT_IDLE methods from app
self.Bind(wx.EVT_IDLE, self.onIdle)
# create updater (which will create dialogs as needed)
self.updater = connections.Updater(app=self)
self.updater.latest = self._latestAvailableVersion
self.updater.suggestUpdate(confirmationDlg=False)
evt.Skip()
def getPrimaryDisplaySize(self):
"""Get the size of the primary display (whose coords start (0,0))
"""
return list(wx.Display(0).GetGeometry())[2:]
def makeAccelTable(self):
"""Makes a standard accelorator table and returns it. This then needs
to be set for the Frame using self.SetAccelerator(table)
"""
def parseStr(inStr):
accel = 0
if 'ctrl' in inStr.lower():
accel += wx.ACCEL_CTRL
if 'shift' in inStr.lower():
accel += wx.ACCEL_SHIFT
if 'alt' in inStr.lower():
accel += wx.ACCEL_ALT
return accel, ord(inStr[-1])
# create a list to link IDs to key strings
keyCodesDict = {}
keyCodesDict[self.keys['copy']] = wx.ID_COPY
keyCodesDict[self.keys['cut']] = wx.ID_CUT
keyCodesDict[self.keys['paste']] = wx.ID_PASTE
keyCodesDict[self.keys['undo']] = wx.ID_UNDO
keyCodesDict[self.keys['redo']] = wx.ID_REDO
keyCodesDict[self.keys['save']] = wx.ID_SAVE
keyCodesDict[self.keys['saveAs']] = wx.ID_SAVEAS
keyCodesDict[self.keys['close']] = wx.ID_CLOSE
keyCodesDict[self.keys['redo']] = wx.ID_REDO
keyCodesDict[self.keys['quit']] = wx.ID_EXIT
# parse the key strings and convert to accelerator entries
entries = []
for keyStr, code in list(keyCodesDict.items()):
mods, key = parseStr(keyStr)
entry = wx.AcceleratorEntry(mods, key, code)
entries.append(entry)
table = wx.AcceleratorTable(entries)
return table
def updateWindowMenu(self):
"""Update items within Window menu to reflect open windows"""
# Update checks on menus in all frames
for frame in self.getAllFrames():
if hasattr(frame, "windowMenu"):
frame.windowMenu.updateFrames()
def showCoder(self, event=None, fileList=None):
# have to reimport because it is only local to __init__ so far
from . import coder
if self.coder is None:
title = "PsychoPy Coder (IDE) (v%s)"
wx.BeginBusyCursor()
self.coder = coder.CoderFrame(None, -1,
title=title % self.version,
files=fileList, app=self)
self.updateWindowMenu()
wx.EndBusyCursor()
else:
# Set output window and standard streams
self.coder.setOutputWindow(True)
self.coder.Show(True)
self.SetTopWindow(self.coder)
self.coder.Raise()
def newBuilderFrame(self, event=None, fileName=None):
# have to reimport because it is ony local to __init__ so far
wx.BeginBusyCursor()
from .builder.builder import BuilderFrame
title = "PsychoPy Builder (v%s)"
self.builder = BuilderFrame(None, -1,
title=title % self.version,
fileName=fileName, app=self)
self.builder.Show(True)
self.builder.Raise()
self.SetTopWindow(self.builder)
self.updateWindowMenu()
wx.EndBusyCursor()
return self.builder
def showBuilder(self, event=None, fileList=()):
# have to reimport because it is only local to __init__ so far
from psychopy.app import builder
for fileName in fileList:
if os.path.isfile(fileName):
self.newBuilderFrame(fileName=fileName)
# create an empty Builder view if needed
if len(self.getAllFrames(frameType="builder")) == 0:
self.newBuilderFrame()
# loop through all frames, from the back bringing each forward
for thisFrame in self.getAllFrames(frameType='builder'):
thisFrame.Show(True)
thisFrame.Raise()
self.SetTopWindow(thisFrame)
def showRunner(self, event=None, fileList=[]):
if not self.runner:
self.runner = self.newRunnerFrame()
if not self.testMode:
self.runner.Show()
self.runner.Raise()
self.SetTopWindow(self.runner)
# Runner captures standard streams until program closed
if self.runner and not self.testMode:
sys.stderr = sys.stdout = self.stdStreamDispatcher
def newRunnerFrame(self, event=None):
# have to reimport because it is only local to __init__ so far
from .runner.runner import RunnerFrame
title = "PsychoPy Runner (v{})".format(self.version)
wx.BeginBusyCursor()
self.runner = RunnerFrame(parent=None,
id=-1,
title=title,
app=self)
self.updateWindowMenu()
wx.EndBusyCursor()
return self.runner
def OnDrop(self, x, y, files):
"""Not clear this method ever gets called!"""
logging.info("Got Files")
def MacOpenFile(self, fileName):
if fileName.endswith('psychopyApp.py'):
# in wx4 on mac this is called erroneously by App.__init__
# if called like `python psychopyApp.py`
return
logging.debug('PsychoPyApp: Received Mac file dropped event')
if fileName.endswith('.py'):
if self.coder is None:
self.showCoder()
self.coder.setCurrentDoc(fileName)
elif fileName.endswith('.psyexp'):
self.newBuilderFrame(fileName=fileName)
def MacReopenApp(self):
"""Called when the doc icon is clicked, and ???"""
self.GetTopWindow().Raise()
def openIPythonNotebook(self, event=None):
"""Note that right now this is bad because it ceases all activity in
the main wx loop and the app has to be quit. We need it to run from
a separate process? The necessary depends (zmq and tornado) were
included from v1.78 onwards in the standalone
"""
import IPython.frontend.html.notebook.notebookapp as nb
instance = nb.launch_new_instance()
def openUpdater(self, event=None):
from psychopy.app import connections
dlg = connections.InstallUpdateDialog(parent=None, ID=-1, app=self)
def colorPicker(self, event=None):
"""Open color-picker, sets clip-board to string [r,g,b].
Note: units are psychopy -1..+1 rgb units to three decimal places,
preserving 24-bit color.
"""
if self.coder is None:
return
document = self.coder.currentDoc
dlg = PsychoColorPicker(document) # doesn't need a parent
dlg.ShowModal()
dlg.Destroy()
if event is not None:
event.Skip()
def openMonitorCenter(self, event):
from psychopy.monitors import MonitorCenter
self.monCenter = MonitorCenter.MainFrame(
None, 'PsychoPy Monitor Center')
self.monCenter.Show(True)
def terminateHubProcess(self):
"""
Send a UDP message to iohub informing it to exit.
Use this when force quitting the experiment script process so iohub
knows to exit as well.
If message is not sent within 1 second, or the iohub server
address in incorrect,the issue is logged.
"""
sock = None
try:
logging.debug('PsychoPyApp: terminateHubProcess called.')
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1.0)
iohubAddress = '127.0.0.1', 9034
import msgpack
txData = msgpack.Packer().pack(('STOP_IOHUB_SERVER',))
return sock.sendto(txData, iohubAddress)
except socket.error as e:
msg = 'PsychoPyApp: terminateHubProcess socket.error: %s'
logging.debug(msg % str(e))
except socket.herror as e:
msg = 'PsychoPyApp: terminateHubProcess socket.herror: %s'
logging.debug(msg % str(e))
except socket.gaierror as e:
msg = 'PsychoPyApp: terminateHubProcess socket.gaierror: %s'
logging.debug(msg % str(e))
except socket.timeout as e:
msg = 'PsychoPyApp: terminateHubProcess socket.timeout: %s'
logging.debug(msg % str(e))
except Exception as e:
msg = 'PsychoPyApp: terminateHubProcess exception: %s'
logging.debug(msg % str(e))
finally:
if sock:
sock.close()
logging.debug('PsychoPyApp: terminateHubProcess completed.')
def quit(self, event=None):
logging.debug('PsychoPyApp: Quitting...')
self.quitting = True
# garbage collect the projects before sys.exit
projects.pavlovia.knownUsers = None
projects.pavlovia.knownProjects = None
# see whether any files need saving
for frame in self.getAllFrames():
try: # will fail if the frame has been shut somehow elsewhere
ok = frame.checkSave()
except Exception:
ok = False
logging.debug("PsychopyApp: exception when saving")
if not ok:
logging.debug('PsychoPyApp: User cancelled shutdown')
return # user cancelled quit
# save info about current frames for next run
if self.coder and len(self.getAllFrames("builder")) == 0:
self.prefs.appData['lastFrame'] = 'coder'
elif self.coder is None:
self.prefs.appData['lastFrame'] = 'builder'
else:
self.prefs.appData['lastFrame'] = 'both'
self.prefs.appData['lastVersion'] = self.version
# update app data while closing each frame
# start with an empty list to be appended by each frame
self.prefs.appData['builder']['prevFiles'] = []
self.prefs.appData['coder']['prevFiles'] = []
# write plugins config if changed during the session
# saveStartUpPluginsConfig()
for frame in self.getAllFrames():
try:
frame.closeFrame(event=event, checkSave=False)
# must do this before destroying the frame?
self.prefs.saveAppData()
except Exception:
pass # we don't care if this fails - we're quitting anyway
#self.Destroy()
# Reset streams back to default
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if not self.testMode:
sys.exit()
def showPrefs(self, event):
from psychopy.app.preferencesDlg import PreferencesDlg
logging.debug('PsychoPyApp: Showing prefs dlg')
prefsDlg = PreferencesDlg(app=self)
prefsDlg.ShowModal()
prefsDlg.Destroy()
def showAbout(self, event):
logging.debug('PsychoPyApp: Showing about dlg')
with io.open(os.path.join(self.prefs.paths['psychopy'], 'LICENSE.txt'),
'r', encoding='utf-8-sig') as f:
license = f.read()
msg = _translate(
"For stimulus generation and experimental control in Python.\n"
"PsychoPy depends on your feedback. If something doesn't work\n"
"then let us know at <EMAIL>")
if parse_version(wx.__version__) >= parse_version('4.0a1'):
info = wx.adv.AboutDialogInfo()
showAbout = wx.adv.AboutBox
else:
info = wx.AboutDialogInfo()
showAbout = wx.AboutBox
if wx.version() >= '3.':
icon = os.path.join(self.prefs.paths['resources'], 'psychopy.png')
info.SetIcon(wx.Icon(icon, wx.BITMAP_TYPE_PNG, 128, 128))
info.SetName('PsychoPy')
info.SetVersion('v' + psychopy.__version__)
info.SetDescription(msg)
info.SetCopyright('(C) 2002-2021 <NAME>')
info.SetWebSite('https://www.psychopy.org')
info.SetLicence(license)
# developers
devNames = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
u'<NAME>\xF8v',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
u'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<EMAIL>]',
'<EMAIL>drjen <EMAIL>]'
]
docNames = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>'
]
devNames.sort()
intNames = [
'Hiroyuki Sogo'
]
intNames.sort()
for name in devNames:
info.AddDeveloper(name)
for name in docNames:
info.AddDocWriter(name)
for name in intNames:
info.AddTranslator(name)
if not self.testMode:
showAbout(info)
def showNews(self, event=None):
connections.showNews(self, checkPrev=False)
def showSystemInfo(self, event=None):
"""Show system information."""
from psychopy.app.sysInfoDlg import SystemInfoDialog
dlg = SystemInfoDialog(None)
dlg.Show()
def followLink(self, event=None, url=None):
"""Follow either an event id (= a key to an url defined in urls.py)
or follow a complete url (a string beginning "http://")
"""
if event is not None:
wx.LaunchDefaultBrowser(self.urls[event.GetId()])
elif url is not None:
wx.LaunchDefaultBrowser(url)
def getAllFrames(self, frameType=None):
"""Get a list of frames, optionally filtered by a particular kind
(which can be "builder", "coder", "project")
"""
frames = []
for frameRef in self._allFrames:
frame = frameRef()
if (not frame):
self._allFrames.remove(frameRef) # has been deleted
continue
elif frameType and frame.frameType != frameType:
continue
frames.append(frame)
return frames
def trackFrame(self, frame):
"""Keep track of an open frame (stores a weak reference to the frame
which will probably have a regular reference to the app)
"""
self._allFrames.append(weakref.ref(frame))
def forgetFrame(self, frame):
"""Keep track of an open frame (stores a weak reference to the frame
which will probably have a regular reference to the app)
"""
for entry in self._allFrames:
if entry() == frame: # is a weakref
self._allFrames.remove(entry)
def onIdle(self, evt):
from . import idle
idle.doIdleTasks(app=self)
evt.Skip()
def onThemeChange(self, event):
"""Handles a theme change event (from a window with a themesMenu)"""
win = event.EventObject.Window
newTheme = win.themesMenu.FindItemById(event.GetId()).ItemLabel
prefs.app['theme'] = newTheme
prefs.saveUserPrefs()
self.theme = newTheme
@property
def theme(self):
"""The theme to be used through the application"""
return prefs.app['theme']
@theme.setter
def theme(self, value):
"""The theme to be used through the application"""
themes.ThemeMixin.loadThemeSpec(self, themeName=value)
prefs.app['theme'] = value
self._currentThemeSpec = themes.ThemeMixin.spec
codeFont = themes.ThemeMixin.codeColors['base']['font']
# On OSX 10.15 Catalina at least calling SetFaceName with 'AppleSystemUIFont' fails.
# So this fix checks to see if changing the font name invalidates the font.
# if so rollback to the font before attempted change.
# Note that wx.Font uses referencing and copy-on-write so we need to force creation of a copy
# witht he wx.Font() call. Otherwise you just get reference to the font that gets borked by SetFaceName()
# -<NAME>
beforesetface = wx.Font(self._codeFont)
success = self._codeFont.SetFaceName(codeFont)
if not (success):
self._codeFont = beforesetface
# Apply theme
self._applyAppTheme()
def _applyAppTheme(self):
"""Overrides ThemeMixin for this class"""
self.iconCache.setTheme(themes.ThemeMixin)
for frameRef in self._allFrames:
frame = frameRef()
if hasattr(frame, '_applyAppTheme'):
frame._applyAppTheme()
if __name__ == '__main__':
# never run; stopped earlier at cannot do relative import in a non-package
sys.exit("Do not launch the app from this script -"
"use python psychopyApp.py instead")
| en | 0.85474 | #!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # turning on will save profile files in currDir # if wxversion doesn't exist hope for the best # because this version has agw # if it's not there locally, try the wxPython lib. # from .plugin_manager import saveStartUpPluginsConfig # NB keep imports to a minimum here because splash screen has not yet shown # e.g. coder and builder are imported during app.__init__ because they # take a while # needed by splash screen for the path to resources/psychopySplash.png # knowing if the user has admin priv is generally a good idea for security. # not actually needed; psychopy should never need anything except normal user # see older versions for code to detect admin (e.g., v 1.80.00) # Enable high-dpi support if on Windows. This fixes blurry text rendering. # get the preference for high DPI # check if we have the option # check if we have OS support for it A simple empty frame with a menubar, should be last frame closed on mac A simpe class that works like a dict but you can access attributes like standard python attrs. Useful to replace the previous pre-made app.IDs (wx.NewID() is no longer recommended or safe) Class with side-effect of restoring wx window switching under wx-3.0 - might only be needed on some platforms (Mac 10.9.4 needs it for me); - needs to be launched as an external script - needs to be separate: seg-faults as method of PsychoPyApp or in-lined - unlear why it works or what the deeper issue is, blah - called at end of PsychoPyApp.onInit() # should be writable: # code to open & immediately close a gui (= invisibly): from psychopy import gui dlg = gui.Dlg().Show() # non-blocking try: dlg.Destroy() # might as well except Exception: pass # append 'w' for pythonw seems not needed # pytest needs to change this With a wx.App some things get done here, before App.__init__ then some further code is launched in OnInit() which occurs after # set to true when all frames are created # set default paths and prefs # track last-viewed page, can return there # check compatibility with last run version (before opening windows) # indicates whether we're running for testing purposes # ordered; order updated with self.onNewTopWindow # import localization after wx: # needed by splash screen # set the exception hook to present unhandled errors in a dialog #NB class variable not self This is launched immediately *after* the app initialises with wx :Parameters: testMode: bool #showSplash: # show splash screen # transparency? # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self # import coder and builder here but only use them later # must be before 1.74.00 # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu # fetch prev files if that's the preference # detect retina displays # fonts are looking tiny on macos (only retina?) right now # adjust dpi to something reasonable # dpi was unreasonable, make one up # Manage fonts # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 # rescale for tiny retina fonts # Load packaged fonts if possible # Set fonts as those loaded # Get system defaults if can't load fonts # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN # that gets most of the properties of _codeFont but the FaceName # FaceName is set in the setting of the theme: # removed Aug 2017: on newer versions of wx (at least on mac) # this looks too big # if hasattr(self._mainFont, 'Larger'): # # Font.Larger is available since wyPython version 2.9.1 # # PsychoPy still supports 2.8 (see ensureMinimal above) # self._mainFont = self._mainFont.Larger() # self._codeFont.SetPointSize( # self._mainFont.GetPointSize()) # unify font size # create both frame for coder/builder as necess # Parse incoming call # Check from filetype if any windows need to be open # If still no window specified, use default from prefs # set the dispatcher for standard output # Create windows # send anonymous info to www.psychopy.org/usage.php # please don't disable this, it's important for PsychoPy's development # tell the user what has changed # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: # returns ~immediately, no display # focus stays in never-land, so bring back to the app: # after all windows are created (so errors flushed) create output # takes control of sys.stdout # flush any errors to the last run log file # we wanted debug mode while loading but safe to go back to info mode `True` if the app has been fully loaded (`bool`). # stderr contents; sometimes meaningless # wizard typically creates html report file but user can manually skip # fatal error was encountered (currently only if bad drivers) # ensure wizard will be triggered again: # if we have internet and haven't yet checked for updates then do so # we have a network connection but not yet tried an update # change IDLE routine so we won't come back here # unbind all EVT_IDLE methods from app # create updater (which will create dialogs as needed) Get the size of the primary display (whose coords start (0,0)) Makes a standard accelorator table and returns it. This then needs to be set for the Frame using self.SetAccelerator(table) # create a list to link IDs to key strings # parse the key strings and convert to accelerator entries Update items within Window menu to reflect open windows # Update checks on menus in all frames # have to reimport because it is only local to __init__ so far # Set output window and standard streams # have to reimport because it is ony local to __init__ so far # have to reimport because it is only local to __init__ so far # create an empty Builder view if needed # loop through all frames, from the back bringing each forward # Runner captures standard streams until program closed # have to reimport because it is only local to __init__ so far Not clear this method ever gets called! # in wx4 on mac this is called erroneously by App.__init__ # if called like `python psychopyApp.py` Called when the doc icon is clicked, and ??? Note that right now this is bad because it ceases all activity in the main wx loop and the app has to be quit. We need it to run from a separate process? The necessary depends (zmq and tornado) were included from v1.78 onwards in the standalone Open color-picker, sets clip-board to string [r,g,b]. Note: units are psychopy -1..+1 rgb units to three decimal places, preserving 24-bit color. # doesn't need a parent Send a UDP message to iohub informing it to exit. Use this when force quitting the experiment script process so iohub knows to exit as well. If message is not sent within 1 second, or the iohub server address in incorrect,the issue is logged. # garbage collect the projects before sys.exit # see whether any files need saving # will fail if the frame has been shut somehow elsewhere # user cancelled quit # save info about current frames for next run # update app data while closing each frame # start with an empty list to be appended by each frame # write plugins config if changed during the session # saveStartUpPluginsConfig() # must do this before destroying the frame? # we don't care if this fails - we're quitting anyway #self.Destroy() # Reset streams back to default # developers Show system information. Follow either an event id (= a key to an url defined in urls.py) or follow a complete url (a string beginning "http://") Get a list of frames, optionally filtered by a particular kind (which can be "builder", "coder", "project") # has been deleted Keep track of an open frame (stores a weak reference to the frame which will probably have a regular reference to the app) Keep track of an open frame (stores a weak reference to the frame which will probably have a regular reference to the app) # is a weakref Handles a theme change event (from a window with a themesMenu) The theme to be used through the application The theme to be used through the application # On OSX 10.15 Catalina at least calling SetFaceName with 'AppleSystemUIFont' fails. # So this fix checks to see if changing the font name invalidates the font. # if so rollback to the font before attempted change. # Note that wx.Font uses referencing and copy-on-write so we need to force creation of a copy # witht he wx.Font() call. Otherwise you just get reference to the font that gets borked by SetFaceName() # -<NAME> # Apply theme Overrides ThemeMixin for this class # never run; stopped earlier at cannot do relative import in a non-package | 1.734712 | 2 |
central-with-statistics.py | MichaelJBaumli/608-mod2 | 0 | 6620398 | #Program Name: central-with-statistics.py
#Assignment Module 2
#Class 44680 Block 44599 Section 01
#<NAME>
#Date: 20210517
import statistics
statistics.mean
statistics.mode
statistics.median
#Variable
grades = [85,93,45,89,85]
#Count Finder
count = len(grades)
print("The count of the grades for the class is: ", count)
#Sum Finder
sumgrade = sum(grades)
print("The sum of the grades for the class is: ",sumgrade)
classgrade = statistics.mean(grades)
print("The mean grade for the class is:", classgrade)
mediangrade = statistics.mode(grades)
print("The median grade is: ", mediangrade)
modegrade = statistics.mode(grades)
print("The mode grade is: ",modegrade) | #Program Name: central-with-statistics.py
#Assignment Module 2
#Class 44680 Block 44599 Section 01
#<NAME>
#Date: 20210517
import statistics
statistics.mean
statistics.mode
statistics.median
#Variable
grades = [85,93,45,89,85]
#Count Finder
count = len(grades)
print("The count of the grades for the class is: ", count)
#Sum Finder
sumgrade = sum(grades)
print("The sum of the grades for the class is: ",sumgrade)
classgrade = statistics.mean(grades)
print("The mean grade for the class is:", classgrade)
mediangrade = statistics.mode(grades)
print("The median grade is: ", mediangrade)
modegrade = statistics.mode(grades)
print("The mode grade is: ",modegrade) | en | 0.694969 | #Program Name: central-with-statistics.py #Assignment Module 2 #Class 44680 Block 44599 Section 01 #<NAME> #Date: 20210517 #Variable #Count Finder #Sum Finder | 3.513319 | 4 |
costar_task_plan/scripts/keras/keras_autoencoder.py | cpaxton/costar_plan | 66 | 6620399 | <gh_stars>10-100
#!/usr/bin/env python
'''
Learning about Keras and autoencoders
From this tutorial: https://blog.keras.io/building-autoencoders-in-keras.html
'''
import keras
import keras.backend as K
from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, UpSampling2D
from keras.models import Model
'''
This block adapts between Tensorflow ordering and Theano ordering.
'''
if K.image_data_format() == "channels_last":
mnist_shape = (28, 28, 1)
else:
mnist_shape = (1, 28, 28)
input_img = Input(shape=mnist_shape)
x = Convolution2D(16, (3, 3), activation='selu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
# at this point the representation is (8, 4, 4) i.e. 128-dimensional
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, (3, 3), activation='selu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.summary()
'''
IMPORT DATA AND CONFIGURE TRAINING
'''
print "Importing dataset..."
from keras.datasets import mnist
print "done."
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train),) + mnist_shape)
x_test = np.reshape(x_test, (len(x_test),) + mnist_shape)
'''
TRAIN ON DATA
'''
from keras.backend import backend
if not backend() == u'theano':
from keras.callbacks import TensorBoard
autoencoder.fit(x_train, x_train,
nb_epoch=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test),
callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])
else:
autoencoder.fit(x_train, x_train,
nb_epoch=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test))
'''
VISUALIZE RESULTS
'''
decoded_imgs = autoencoder.predict(x_test)
try:
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
except ImportError, e:
print e
| #!/usr/bin/env python
'''
Learning about Keras and autoencoders
From this tutorial: https://blog.keras.io/building-autoencoders-in-keras.html
'''
import keras
import keras.backend as K
from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, UpSampling2D
from keras.models import Model
'''
This block adapts between Tensorflow ordering and Theano ordering.
'''
if K.image_data_format() == "channels_last":
mnist_shape = (28, 28, 1)
else:
mnist_shape = (1, 28, 28)
input_img = Input(shape=mnist_shape)
x = Convolution2D(16, (3, 3), activation='selu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
# at this point the representation is (8, 4, 4) i.e. 128-dimensional
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, (3, 3), activation='selu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, (3, 3), activation='selu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.summary()
'''
IMPORT DATA AND CONFIGURE TRAINING
'''
print "Importing dataset..."
from keras.datasets import mnist
print "done."
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train),) + mnist_shape)
x_test = np.reshape(x_test, (len(x_test),) + mnist_shape)
'''
TRAIN ON DATA
'''
from keras.backend import backend
if not backend() == u'theano':
from keras.callbacks import TensorBoard
autoencoder.fit(x_train, x_train,
nb_epoch=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test),
callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])
else:
autoencoder.fit(x_train, x_train,
nb_epoch=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test))
'''
VISUALIZE RESULTS
'''
decoded_imgs = autoencoder.predict(x_test)
try:
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
except ImportError, e:
print e | en | 0.626237 | #!/usr/bin/env python Learning about Keras and autoencoders From this tutorial: https://blog.keras.io/building-autoencoders-in-keras.html This block adapts between Tensorflow ordering and Theano ordering. # at this point the representation is (8, 4, 4) i.e. 128-dimensional IMPORT DATA AND CONFIGURE TRAINING TRAIN ON DATA VISUALIZE RESULTS # display original # display reconstruction | 3.655091 | 4 |
python/localconstants.py | nichuguen/led-matrix-rpi | 0 | 6620400 | <reponame>nichuguen/led-matrix-rpi<gh_stars>0
pathprog = "/home/pi/LED-Project/led-matrix-rpi/c"
clear = pathprog + "/test-clear.run"
ledmatrix = pathprog + "/led-matrix.run"
| pathprog = "/home/pi/LED-Project/led-matrix-rpi/c"
clear = pathprog + "/test-clear.run"
ledmatrix = pathprog + "/led-matrix.run" | none | 1 | 1.096352 | 1 | |
sample.py | himalaya-singh-sheoran/kairon | 0 | 6620401 | <filename>sample.py
import os
from rasa.shared.constants import DEFAULT_MODELS_PATH
from glob import glob
output = os.path.join(DEFAULT_MODELS_PATH, "tests")
new_model = "models/tests/20211116-144823.tar.gz"
if os.path.isdir(output):
new_path = os.path.join(output, "old_model")
if not os.path.exists(new_path):
os.mkdir(new_path)
for cleanUp in glob(os.path.join(output, '*.tar.gz')):
print(cleanUp) | <filename>sample.py
import os
from rasa.shared.constants import DEFAULT_MODELS_PATH
from glob import glob
output = os.path.join(DEFAULT_MODELS_PATH, "tests")
new_model = "models/tests/20211116-144823.tar.gz"
if os.path.isdir(output):
new_path = os.path.join(output, "old_model")
if not os.path.exists(new_path):
os.mkdir(new_path)
for cleanUp in glob(os.path.join(output, '*.tar.gz')):
print(cleanUp) | none | 1 | 2.217122 | 2 | |
python_toolbox/wx_tools/widgets/cute_window/bind_savvy_evt_handler/bind_savvy_evt_handler_type.py | hboshnak/python_toolbox | 119 | 6620402 | <filename>python_toolbox/wx_tools/widgets/cute_window/bind_savvy_evt_handler/bind_savvy_evt_handler_type.py
# Copyright 2009-2011 <NAME>.
# This program is distributed under the LGPL2.1 license.
import wx
from python_toolbox import caching
from python_toolbox import dict_tools
from .event_handler_grokker import EventHandlerGrokker
class BindSavvyEvtHandlerType(type(wx.EvtHandler)):
'''
Metaclass for the `BindSavvyEvtHandler` class.
See documentation of `BindSavvyEvtHandler` for more information.
'''
event_modules = []
'''
Modules in which events of the form `EVT_WHATEVER` will be searched.
You may override this with either a module or a list of modules, and they
will be searched when encountering an event handler function with a
corresponding name. (e.g. `_on_whatever`.)
'''
@property
@caching.cache()
def _BindSavvyEvtHandlerType__event_handler_grokkers(cls):
'''
The `EventHandlerGrokker` objects for this window.
Each grokker corresponds to an event handler function and its
responsibilty is to figure out the correct event to handle based on the
function's name. See documentation of `EventHandlerGrokker` for more
information.
'''
names_to_event_handlers = dict_tools.filter_items(
vars(cls),
lambda name, value:
cls._BindSavvyEvtHandlerType__name_parser.match(name,
cls.__name__) and
callable(value) and
getattr(value, '_BindSavvyEvtHandlerType__dont_bind_automatically',
None) is not True,
force_dict_type=dict
)
'''Dict mapping names to event handling functions.'''
return [EventHandlerGrokker(name, value, cls) for (name, value) in
names_to_event_handlers.items()]
@staticmethod
def dont_bind_automatically(function):
'''
Decorate a method to not be bound automatically as an event handler.
'''
function._BindSavvyEvtHandlerType__dont_bind_automatically = True
return function | <filename>python_toolbox/wx_tools/widgets/cute_window/bind_savvy_evt_handler/bind_savvy_evt_handler_type.py
# Copyright 2009-2011 <NAME>.
# This program is distributed under the LGPL2.1 license.
import wx
from python_toolbox import caching
from python_toolbox import dict_tools
from .event_handler_grokker import EventHandlerGrokker
class BindSavvyEvtHandlerType(type(wx.EvtHandler)):
'''
Metaclass for the `BindSavvyEvtHandler` class.
See documentation of `BindSavvyEvtHandler` for more information.
'''
event_modules = []
'''
Modules in which events of the form `EVT_WHATEVER` will be searched.
You may override this with either a module or a list of modules, and they
will be searched when encountering an event handler function with a
corresponding name. (e.g. `_on_whatever`.)
'''
@property
@caching.cache()
def _BindSavvyEvtHandlerType__event_handler_grokkers(cls):
'''
The `EventHandlerGrokker` objects for this window.
Each grokker corresponds to an event handler function and its
responsibilty is to figure out the correct event to handle based on the
function's name. See documentation of `EventHandlerGrokker` for more
information.
'''
names_to_event_handlers = dict_tools.filter_items(
vars(cls),
lambda name, value:
cls._BindSavvyEvtHandlerType__name_parser.match(name,
cls.__name__) and
callable(value) and
getattr(value, '_BindSavvyEvtHandlerType__dont_bind_automatically',
None) is not True,
force_dict_type=dict
)
'''Dict mapping names to event handling functions.'''
return [EventHandlerGrokker(name, value, cls) for (name, value) in
names_to_event_handlers.items()]
@staticmethod
def dont_bind_automatically(function):
'''
Decorate a method to not be bound automatically as an event handler.
'''
function._BindSavvyEvtHandlerType__dont_bind_automatically = True
return function | en | 0.780163 | # Copyright 2009-2011 <NAME>. # This program is distributed under the LGPL2.1 license. Metaclass for the `BindSavvyEvtHandler` class. See documentation of `BindSavvyEvtHandler` for more information. Modules in which events of the form `EVT_WHATEVER` will be searched. You may override this with either a module or a list of modules, and they will be searched when encountering an event handler function with a corresponding name. (e.g. `_on_whatever`.) The `EventHandlerGrokker` objects for this window. Each grokker corresponds to an event handler function and its responsibilty is to figure out the correct event to handle based on the function's name. See documentation of `EventHandlerGrokker` for more information. Dict mapping names to event handling functions. Decorate a method to not be bound automatically as an event handler. | 2.106059 | 2 |
doc/demos/python/interactive_segmentation.py | basileMarchand/smil | 4 | 6620403 | from smilPython import *
im1 = Image("https://smil.cmm.minesparis.psl.eu/images/tools.png")
im2 = Image(im1)
im3 = Image(im1)
im4 = Image(im1)
imOverl = Image(im1)
gradient(im1, im2)
im1.show()
im3.show()
im4.showLabel()
v = im1.getViewer()
class slot(EventSlot):
def run(self, event=None):
v.getOverlay(imOverl)
watershed(im2, imOverl, im3, im4)
s = slot()
v.onOverlayModified.connect(s)
v.onOverlayModified.trigger()
print("1) Right click on im1")
print("2) In the \"Tools\" menu select \"Draw\"")
print("3) Draw markers (with different colors) on im1 and view the resulting segmentation")
# Will crash if not in a "real" Qt loop
Gui.execLoop()
| from smilPython import *
im1 = Image("https://smil.cmm.minesparis.psl.eu/images/tools.png")
im2 = Image(im1)
im3 = Image(im1)
im4 = Image(im1)
imOverl = Image(im1)
gradient(im1, im2)
im1.show()
im3.show()
im4.showLabel()
v = im1.getViewer()
class slot(EventSlot):
def run(self, event=None):
v.getOverlay(imOverl)
watershed(im2, imOverl, im3, im4)
s = slot()
v.onOverlayModified.connect(s)
v.onOverlayModified.trigger()
print("1) Right click on im1")
print("2) In the \"Tools\" menu select \"Draw\"")
print("3) Draw markers (with different colors) on im1 and view the resulting segmentation")
# Will crash if not in a "real" Qt loop
Gui.execLoop()
| en | 0.529436 | # Will crash if not in a "real" Qt loop | 2.76969 | 3 |
minimalistic-maps.py | lorossi/minimalistic-maps | 0 | 6620404 | # Made by <NAME>
# www.lorenzoros.si
import json
import time
import logging
from math import sqrt
from pathlib import Path
from PIL import Image, ImageFont, ImageDraw
from OSMPythonTools.nominatim import Nominatim
from OSMPythonTools.overpass import overpassQueryBuilder, Overpass
# translate variables
def map(value, old_min, old_max, new_min, new_max):
old_width = old_max - old_min
new_width = new_max - new_min
value_scaled = float(value - old_min) / float(old_width)
return new_min + (value_scaled * new_width)
class MinimalMap:
def __init__(self, colors, width=1500, height=1500):
self.width = width
self.height = height
self.colors = colors
self.dist_factor = 1.75
# start up apis
self.nominatim = Nominatim()
self.overpass = Overpass()
def distance(self, point):
return sqrt((point["lon"] - self.center["x"]) ** 2 +
(point["lat"] - self.center["y"]) ** 2)
def loadFont(self, main_font_path, italic_font_path):
self.main_font_path = main_font_path
self.italic_font_path = italic_font_path
def setCity(self, city, timeout=300):
self.city = city
# select the city
query = self.nominatim.query(self.city, timeout=timeout)
self.area_id = query.areaId()
def query(self, primary, secondary, element_type, timeout=300):
# save the element type
self.element_type = element_type
# initialize list
self.json_data = []
# convert secondary to list
if type(secondary) is not list:
secondary = [secondary]
# we save this variable to generate the output image name
self.secondary_query = secondary
# load each selector
for s in secondary:
# effective query
selector = f'"{primary}"="{s}"'
query = overpassQueryBuilder(area=self.area_id,
elementType=self.element_type,
selector=selector, out='body',
includeGeometry=True)
while True:
try:
result = self.overpass.query(query, timeout=timeout)
break
except KeyboardInterrupt:
logging.info("Received KeyboardInterrupt while querying. "
"Stopping execution.")
quit()
except Exception as e:
logging.warning(f"Error while querying {self.city}, "
f" {selector}. Error {e}. \n"
"Trying again in a bit")
time.sleep(30)
if self.element_type == "node":
# convert to json and keep only the nodes
result_json = result.toJSON()["elements"]
self.json_data.extend(result_json) # keep only the elements
elif self.element_type == "way":
# this is going to be fun, it's a polygon!
result_json = result.toJSON()["elements"]
for way in result_json:
self.json_data.append(way["geometry"])
elif self.element_type == "relation":
# this is going to be even funnier!
result_json = result.toJSON()["elements"]
for relation in result_json:
for member in relation["members"]:
if "geometry" in member:
self.json_data.append(member["geometry"])
if self.element_type == "node":
lat = sorted([x["lat"] for x in self.json_data])
lon = sorted([x["lon"] for x in self.json_data])
elif self.element_type == "way" or self.element_type == "relation":
lat = []
lon = []
# i'm sure there's a list comprehension for this
for way in self.json_data:
for point in way:
lat.append(point["lat"])
lon.append(point["lon"])
lat = sorted(lat)
lon = sorted(lon)
# if there is only one item, we need to add a way to prevent a sure
# crash... here we go
if not lat or not len:
return False
# define the bounding box
self.bbox = {
"north": lat[0],
"south": lat[-1],
"east": lon[0],
"west": lon[-1],
"height": lat[-1] - lat[0],
"width": lon[-1] - lon[0]
}
# check if any point was found
if self.bbox["width"] == 0 or self.bbox["height"] == 0:
return False
# calculate center point
self.center = {
"x": (lon[0] + lon[-1]) / 2,
"y": (lat[0] + lat[-1]) / 2
}
return True
def createImage(self, fill="red", subtitle="", fill_type="fill", map_scl=.9):
if len(self.json_data) > 10000:
circles_radius = 2
elif len(self.json_data) > 1000:
circles_radius = 4
else:
circles_radius = 6
# calculate map image size
biggest = max(self.bbox["width"], self.bbox["height"])
scl = max(self.width, self.height) / biggest
# map width and height
map_width = int(self.bbox["width"] * scl)
map_height = int(self.bbox["height"] * scl)
# create the map image
map_im = Image.new('RGBA', (map_width, map_height),
color=self.colors["secondary"])
map_draw = ImageDraw.Draw(map_im)
# draw points
if self.element_type == "node":
for node in self.json_data:
# calculate each node position
x = map(node["lon"], self.bbox["east"],
self.bbox["west"], 0, map_im.width)
y = map(node["lat"], self.bbox["south"], self.bbox["north"],
0, map_im.height)
circle_box = [x - circles_radius, y - circles_radius,
x + circles_radius, y + circles_radius]
# finally draw circle
map_draw.ellipse(circle_box, fill=fill)
# draw shapes
elif self.element_type == "way" or self.element_type == "relation":
# iterate throught shapes
for way in self.json_data:
poly = []
# iterate throught points
for point in way:
# calculate each point position
x = map(point["lon"], self.bbox["east"],
self.bbox["west"], 0, map_im.width)
y = map(point["lat"], self.bbox["south"], self.bbox["north"],
0, map_im.height)
poly.append((x, y))
if fill_type == "fill":
# finally draw poly
map_draw.polygon(poly, fill=fill)
elif fill_type == "line":
map_draw.line(poly, fill=fill, width=10)
# scale the image
new_width = int(map_width * map_scl)
new_height = int(map_height * map_scl)
map_im = map_im.resize((new_width, new_height))
# calculate map image displacement
dx = int((self.width - map_im.width) / 2)
dy = int((self.height - map_im.height) / 2)
# create the text image
text_im = Image.new('RGBA', (self.width, self.height),
color=(0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_im)
# city name format
text = self.city
font_size = 300
# main text location
tx = font_size / 2
ty = self.height - font_size / 2
main_font = ImageFont.truetype(font=self.main_font_path,
size=font_size)
text_draw.text((tx, ty), text=text, anchor="ls",
fill=self.colors["text"], font=main_font,
align="left", stroke_fill=None)
# watermark
# city name format
text = "<NAME> - www.lorenzoros.si"
font_size = 100
italic_font = ImageFont.truetype(font=self.italic_font_path,
size=font_size)
# create a new image with just the right size
watermark_im = Image.new('RGBA', (self.width, font_size),
color=self.colors["secondary"])
watermark_draw = ImageDraw.Draw(watermark_im)
watermark_draw.text((watermark_im.width, watermark_im.height),
text=text, font=italic_font, anchor="rd",
fill=self.colors["watermark"], stroke_fill=None)
# rotate text
watermark_im = watermark_im.rotate(angle=90, expand=1)
# watermark location
tx = int(self.width - font_size * 1.5)
ty = int(font_size * 1.5)
# paste watermark into text
text_im.paste(watermark_im, (tx, ty))
# final image
self.dest_im = Image.new('RGBA', (self.width, self.height),
color=self.colors["secondary"])
# paste into final image
self.dest_im.paste(map_im, (dx, dy))
# paste with transparency
self.dest_im.paste(text_im, (0, 0), text_im)
def saveImage(self, path):
filename = f"{self.city}-{'-'.join(self.secondary_query)}.png"
full_path = f"{path}/{filename}"
self.dest_im.save(full_path)
return full_path.replace("//", "/")
def main():
logfile = __file__.replace(".py", ".log")
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.INFO, filename=logfile,
filemode="w+")
print(f"Logging into {logfile}")
logging.info("Script started")
with open("settings.json") as f:
settings = json.load(f)
# settings unpacking
image_width = settings["image"]["width"]
image_height = settings["image"]["height"]
output_folder = settings["image"]["output_path"]
cities = sorted(settings["cities"])
main_font = settings["image"]["main_font"]
italic_font = settings["image"]["italic_font"]
colors = settings["image"]["colors"]
logging.info("Settings loaded")
# create output folder
Path(output_folder).mkdir(parents=True, exist_ok=True)
# create city
m = MinimalMap(colors, width=image_width, height=image_height)
# load fonts
m.loadFont(main_font, italic_font)
logging.info("Basic setup completed")
# load queries
for city in cities:
output_path = f"{output_folder}/{city}/"
# make output city folder
Path(output_path).mkdir(parents=True, exist_ok=True)
m.setCity(city)
for query in sorted(settings["queries"], key=lambda x: x["subtitle"]):
if type(query['secondary_query']) is list:
logging.info(f"Starting {' '.join(query['secondary_query'])} "
f"for city {city}")
else:
logging.info(f"Starting {query['secondary_query']} "
f"for city {city}")
result = m.query(query["primary_query"], query["secondary_query"],
query["type"])
if result:
if "fill_type" in query:
# we specified a fill type inside the settings
m.createImage(fill=query["fill"], subtitle=query["subtitle"],
fill_type=query["fill_type"])
else:
# there is not a fill type, just go default
m.createImage(fill=query["fill"], subtitle=query["subtitle"])
full_path = m.saveImage(output_path)
logging.info(f"Completed. Filepath: {full_path}")
else:
logging.info("Not enough points. Aborted.")
logging.info(f"{city} completed")
print("Done")
logging.info("Everything done!")
if __name__ == "__main__":
main()
| # Made by <NAME>
# www.lorenzoros.si
import json
import time
import logging
from math import sqrt
from pathlib import Path
from PIL import Image, ImageFont, ImageDraw
from OSMPythonTools.nominatim import Nominatim
from OSMPythonTools.overpass import overpassQueryBuilder, Overpass
# translate variables
def map(value, old_min, old_max, new_min, new_max):
old_width = old_max - old_min
new_width = new_max - new_min
value_scaled = float(value - old_min) / float(old_width)
return new_min + (value_scaled * new_width)
class MinimalMap:
def __init__(self, colors, width=1500, height=1500):
self.width = width
self.height = height
self.colors = colors
self.dist_factor = 1.75
# start up apis
self.nominatim = Nominatim()
self.overpass = Overpass()
def distance(self, point):
return sqrt((point["lon"] - self.center["x"]) ** 2 +
(point["lat"] - self.center["y"]) ** 2)
def loadFont(self, main_font_path, italic_font_path):
self.main_font_path = main_font_path
self.italic_font_path = italic_font_path
def setCity(self, city, timeout=300):
self.city = city
# select the city
query = self.nominatim.query(self.city, timeout=timeout)
self.area_id = query.areaId()
def query(self, primary, secondary, element_type, timeout=300):
# save the element type
self.element_type = element_type
# initialize list
self.json_data = []
# convert secondary to list
if type(secondary) is not list:
secondary = [secondary]
# we save this variable to generate the output image name
self.secondary_query = secondary
# load each selector
for s in secondary:
# effective query
selector = f'"{primary}"="{s}"'
query = overpassQueryBuilder(area=self.area_id,
elementType=self.element_type,
selector=selector, out='body',
includeGeometry=True)
while True:
try:
result = self.overpass.query(query, timeout=timeout)
break
except KeyboardInterrupt:
logging.info("Received KeyboardInterrupt while querying. "
"Stopping execution.")
quit()
except Exception as e:
logging.warning(f"Error while querying {self.city}, "
f" {selector}. Error {e}. \n"
"Trying again in a bit")
time.sleep(30)
if self.element_type == "node":
# convert to json and keep only the nodes
result_json = result.toJSON()["elements"]
self.json_data.extend(result_json) # keep only the elements
elif self.element_type == "way":
# this is going to be fun, it's a polygon!
result_json = result.toJSON()["elements"]
for way in result_json:
self.json_data.append(way["geometry"])
elif self.element_type == "relation":
# this is going to be even funnier!
result_json = result.toJSON()["elements"]
for relation in result_json:
for member in relation["members"]:
if "geometry" in member:
self.json_data.append(member["geometry"])
if self.element_type == "node":
lat = sorted([x["lat"] for x in self.json_data])
lon = sorted([x["lon"] for x in self.json_data])
elif self.element_type == "way" or self.element_type == "relation":
lat = []
lon = []
# i'm sure there's a list comprehension for this
for way in self.json_data:
for point in way:
lat.append(point["lat"])
lon.append(point["lon"])
lat = sorted(lat)
lon = sorted(lon)
# if there is only one item, we need to add a way to prevent a sure
# crash... here we go
if not lat or not len:
return False
# define the bounding box
self.bbox = {
"north": lat[0],
"south": lat[-1],
"east": lon[0],
"west": lon[-1],
"height": lat[-1] - lat[0],
"width": lon[-1] - lon[0]
}
# check if any point was found
if self.bbox["width"] == 0 or self.bbox["height"] == 0:
return False
# calculate center point
self.center = {
"x": (lon[0] + lon[-1]) / 2,
"y": (lat[0] + lat[-1]) / 2
}
return True
def createImage(self, fill="red", subtitle="", fill_type="fill", map_scl=.9):
if len(self.json_data) > 10000:
circles_radius = 2
elif len(self.json_data) > 1000:
circles_radius = 4
else:
circles_radius = 6
# calculate map image size
biggest = max(self.bbox["width"], self.bbox["height"])
scl = max(self.width, self.height) / biggest
# map width and height
map_width = int(self.bbox["width"] * scl)
map_height = int(self.bbox["height"] * scl)
# create the map image
map_im = Image.new('RGBA', (map_width, map_height),
color=self.colors["secondary"])
map_draw = ImageDraw.Draw(map_im)
# draw points
if self.element_type == "node":
for node in self.json_data:
# calculate each node position
x = map(node["lon"], self.bbox["east"],
self.bbox["west"], 0, map_im.width)
y = map(node["lat"], self.bbox["south"], self.bbox["north"],
0, map_im.height)
circle_box = [x - circles_radius, y - circles_radius,
x + circles_radius, y + circles_radius]
# finally draw circle
map_draw.ellipse(circle_box, fill=fill)
# draw shapes
elif self.element_type == "way" or self.element_type == "relation":
# iterate throught shapes
for way in self.json_data:
poly = []
# iterate throught points
for point in way:
# calculate each point position
x = map(point["lon"], self.bbox["east"],
self.bbox["west"], 0, map_im.width)
y = map(point["lat"], self.bbox["south"], self.bbox["north"],
0, map_im.height)
poly.append((x, y))
if fill_type == "fill":
# finally draw poly
map_draw.polygon(poly, fill=fill)
elif fill_type == "line":
map_draw.line(poly, fill=fill, width=10)
# scale the image
new_width = int(map_width * map_scl)
new_height = int(map_height * map_scl)
map_im = map_im.resize((new_width, new_height))
# calculate map image displacement
dx = int((self.width - map_im.width) / 2)
dy = int((self.height - map_im.height) / 2)
# create the text image
text_im = Image.new('RGBA', (self.width, self.height),
color=(0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_im)
# city name format
text = self.city
font_size = 300
# main text location
tx = font_size / 2
ty = self.height - font_size / 2
main_font = ImageFont.truetype(font=self.main_font_path,
size=font_size)
text_draw.text((tx, ty), text=text, anchor="ls",
fill=self.colors["text"], font=main_font,
align="left", stroke_fill=None)
# watermark
# city name format
text = "<NAME> - www.lorenzoros.si"
font_size = 100
italic_font = ImageFont.truetype(font=self.italic_font_path,
size=font_size)
# create a new image with just the right size
watermark_im = Image.new('RGBA', (self.width, font_size),
color=self.colors["secondary"])
watermark_draw = ImageDraw.Draw(watermark_im)
watermark_draw.text((watermark_im.width, watermark_im.height),
text=text, font=italic_font, anchor="rd",
fill=self.colors["watermark"], stroke_fill=None)
# rotate text
watermark_im = watermark_im.rotate(angle=90, expand=1)
# watermark location
tx = int(self.width - font_size * 1.5)
ty = int(font_size * 1.5)
# paste watermark into text
text_im.paste(watermark_im, (tx, ty))
# final image
self.dest_im = Image.new('RGBA', (self.width, self.height),
color=self.colors["secondary"])
# paste into final image
self.dest_im.paste(map_im, (dx, dy))
# paste with transparency
self.dest_im.paste(text_im, (0, 0), text_im)
def saveImage(self, path):
filename = f"{self.city}-{'-'.join(self.secondary_query)}.png"
full_path = f"{path}/{filename}"
self.dest_im.save(full_path)
return full_path.replace("//", "/")
def main():
logfile = __file__.replace(".py", ".log")
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.INFO, filename=logfile,
filemode="w+")
print(f"Logging into {logfile}")
logging.info("Script started")
with open("settings.json") as f:
settings = json.load(f)
# settings unpacking
image_width = settings["image"]["width"]
image_height = settings["image"]["height"]
output_folder = settings["image"]["output_path"]
cities = sorted(settings["cities"])
main_font = settings["image"]["main_font"]
italic_font = settings["image"]["italic_font"]
colors = settings["image"]["colors"]
logging.info("Settings loaded")
# create output folder
Path(output_folder).mkdir(parents=True, exist_ok=True)
# create city
m = MinimalMap(colors, width=image_width, height=image_height)
# load fonts
m.loadFont(main_font, italic_font)
logging.info("Basic setup completed")
# load queries
for city in cities:
output_path = f"{output_folder}/{city}/"
# make output city folder
Path(output_path).mkdir(parents=True, exist_ok=True)
m.setCity(city)
for query in sorted(settings["queries"], key=lambda x: x["subtitle"]):
if type(query['secondary_query']) is list:
logging.info(f"Starting {' '.join(query['secondary_query'])} "
f"for city {city}")
else:
logging.info(f"Starting {query['secondary_query']} "
f"for city {city}")
result = m.query(query["primary_query"], query["secondary_query"],
query["type"])
if result:
if "fill_type" in query:
# we specified a fill type inside the settings
m.createImage(fill=query["fill"], subtitle=query["subtitle"],
fill_type=query["fill_type"])
else:
# there is not a fill type, just go default
m.createImage(fill=query["fill"], subtitle=query["subtitle"])
full_path = m.saveImage(output_path)
logging.info(f"Completed. Filepath: {full_path}")
else:
logging.info("Not enough points. Aborted.")
logging.info(f"{city} completed")
print("Done")
logging.info("Everything done!")
if __name__ == "__main__":
main()
| en | 0.73411 | # Made by <NAME> # www.lorenzoros.si # translate variables # start up apis # select the city # save the element type # initialize list # convert secondary to list # we save this variable to generate the output image name # load each selector # effective query # convert to json and keep only the nodes # keep only the elements # this is going to be fun, it's a polygon! # this is going to be even funnier! # i'm sure there's a list comprehension for this # if there is only one item, we need to add a way to prevent a sure # crash... here we go # define the bounding box # check if any point was found # calculate center point # calculate map image size # map width and height # create the map image # draw points # calculate each node position # finally draw circle # draw shapes # iterate throught shapes # iterate throught points # calculate each point position # finally draw poly # scale the image # calculate map image displacement # create the text image # city name format # main text location # watermark # city name format # create a new image with just the right size # rotate text # watermark location # paste watermark into text # final image # paste into final image # paste with transparency # settings unpacking # create output folder # create city # load fonts # load queries # make output city folder # we specified a fill type inside the settings # there is not a fill type, just go default | 2.846952 | 3 |
view/create_fplot.py | GPCRmd/GPCRmd | 3 | 6620405 | from dynadb.models import DyndbFiles, DyndbFilesDynamics, DyndbModelComponents, DyndbCompound, DyndbDynamicsComponents,DyndbDynamics, DyndbModel, DyndbProtein,DyndbProteinSequence, DyndbModeledResidues
from view.assign_generic_numbers_from_DB import obtain_gen_numbering
from view.traj2flare_modified_wn import * #[!] Now it's the wn version (new version that uses MDtraj wernet_nilsson function)
from view.views import findGPCRclass, obtain_all_chains, obtain_DyndbProtein_id_list, obtain_seq_pos_info
from dynadb.pipe4_6_0 import *
from view.data import *
import re
import json
from Bio.PDB import *
from Bio import PDB
import itertools
import mdtraj as md
import numpy as np
import copy
import csv
def obtain_fplot_input(result,numbers,chain_name,current_class):
resi_to_group = {}
resi_to_name = {}
cluster_dict={}
#chain_index=str(chain_name_li.index(chain_name))
pos_gnum = numbers[current_class]
for pos in result:
if pos[0] != "-": #Consider only num in the pdb
db_pos=pos[1][1]
pdb_pos=pos[0][1]
#gnum_or_nth=""
this_gnum = pos_gnum[db_pos][1]
this_segm = pos_gnum[db_pos][2]
resi_to_group[(pdb_pos,chain_name)]=str(this_segm)
if this_gnum:#If exist GPCR num for this position
this_gnum=this_gnum[:this_gnum.find(".")]+this_gnum[this_gnum.find("x"):]
cluster_dict[this_gnum]=[chain_name+"."+pdb_pos,""]
resi_to_name[(pdb_pos,chain_name)]=str(this_gnum)
return(resi_to_group,resi_to_name,cluster_dict)
def create_fplot(self,dyn_id,newpath,pdbpath=None,trajpath=None,traj_id=None,stride=1):# Not sure what will happen in pdbs with more than 1 gpcr . Use traj 14 or 15 for dyn 1
"""Generates the json files necessary to visualize flare plots."""
gpcr_mode=True
if (trajpath==None and traj_id):
trajpath=DyndbFiles.objects.get(id=traj_id)
if (pdbpath==None):
pdbpath=DyndbFiles.objects.filter(dyndbfilesdynamics__id_dynamics=dyn_id, id_file_types__extension="pdb")[0].filepath
chain_name_li=obtain_all_chains(pdbpath)
if (len(chain_name_li)==0):
error="Protein chains not found."
self.stdout.write(self.style.NOTICE(error))
return
prot_li_gpcr, dprot_li_all,dprot_li_all_info,pdbid=obtain_DyndbProtein_id_list(dyn_id)
dprot_chains={}
chains_taken=set()
prot_seq_pos={}
seq_pos_n=1
for prot_id, prot_name, prot_is_gpcr, prot_seq in dprot_li_all_info: #To classify chains by protein (dprot_chains is a dict:for each protein, has a list of each chain with its matchpdbfa results + the protein seq_pos)
seq_pos=[]
dprot_chains[prot_id]=[[],[]]
for chain_name in chain_name_li:
checkpdb_res=checkpdb_ngl(pdbpath, segid="",start=-1,stop=9999999999999999999, chain=chain_name)
if isinstance(checkpdb_res, tuple):
tablepdb,pdb_sequence,hexflag=checkpdb_res
result=matchpdbfa_ngl(prot_seq,pdb_sequence, tablepdb, hexflag)
type(result)
if isinstance(result, list):
#chain_results[chain_name]=result
if chain_name not in chains_taken:
chains_taken.add(chain_name)
dprot_chains[prot_id][0].append((chain_name,result))
(seq_pos,seq_pos_n)=obtain_seq_pos_info(result,seq_pos,seq_pos_n,chain_name,True)
dprot_chains[prot_id][1]=seq_pos
prot_seq_pos[prot_id]=(prot_name,seq_pos)
keys_to_rm=set()
for key, val in dprot_chains.items():
if val==([],[]):
keys_to_rm.add(key)
for key in keys_to_rm:
del dprot_chains[key]
if chains_taken: # To check if some result have been obtained
for gpcr_DprotGprot in prot_li_gpcr:
gpcr_Dprot=gpcr_DprotGprot[0]
gpcr_Gprot=gpcr_DprotGprot[1]
dprot_id=gpcr_Dprot.id
dprot_name=gpcr_Dprot.name
gen_num_res=obtain_gen_numbering(dyn_id, gpcr_Dprot,gpcr_Gprot)
if len(gen_num_res) > 2:
(numbers, num_scheme, db_seq, current_class) = gen_num_res
current_class=findGPCRclass(num_scheme)
gpcr_n_ex=""
for pos_gnum in numbers[current_class].values():
if pos_gnum[1]: #We take the 1st instance of gpcr num as example, and check in which format it is (n.nnxnn or nxnn)
gpcr_n_ex=pos_gnum[1]
break
if not "." in gpcr_n_ex: #For the moment we only accept n.nnxnn format
error="Error obtaining GPCR generic numbering."
self.stdout.write(self.style.NOTICE(error))
return
(dprot_chain_li, dprot_seq) = dprot_chains[dprot_id]
for chain_name, result in dprot_chain_li:
(resi_to_group,resi_to_name,cluster_dict)=obtain_fplot_input(result,numbers,chain_name,current_class)
model_res=DyndbModeledResidues.objects.filter(id_model__dyndbdynamics__id=dyn_id)
seg_to_chain={mr.segid : mr.chain for mr in model_res}
if gpcr_mode:
for (pos, gnum) in resi_to_name.items():
if gnum != "None":
chain=gnum.split("x",1)[0]
resi_to_name[pos]=chain+"."+gnum
create_json(self,True,trajpath,pdbpath,resi_to_group,resi_to_name,newpath,stride,seg_to_chain)
else:
create_json(self,False,trajpath,pdbpath,resi_to_group,resi_to_name,newpath,stride,seg_to_chain)
out_file = re.search("(\w*)(\.\w*)$" , newpath).group()
self.stdout.write(self.style.SUCCESS('JSON file '+out_file+' successfully created'))
else:
error="Error obtaining GPCR generic numbering."
self.stdout.write(self.style.NOTICE(error))
return
else:
error="Error assigning the GPCR generic numbering to the PDB"
self.stdout.write(self.style.NOTICE(error))
return
| from dynadb.models import DyndbFiles, DyndbFilesDynamics, DyndbModelComponents, DyndbCompound, DyndbDynamicsComponents,DyndbDynamics, DyndbModel, DyndbProtein,DyndbProteinSequence, DyndbModeledResidues
from view.assign_generic_numbers_from_DB import obtain_gen_numbering
from view.traj2flare_modified_wn import * #[!] Now it's the wn version (new version that uses MDtraj wernet_nilsson function)
from view.views import findGPCRclass, obtain_all_chains, obtain_DyndbProtein_id_list, obtain_seq_pos_info
from dynadb.pipe4_6_0 import *
from view.data import *
import re
import json
from Bio.PDB import *
from Bio import PDB
import itertools
import mdtraj as md
import numpy as np
import copy
import csv
def obtain_fplot_input(result,numbers,chain_name,current_class):
resi_to_group = {}
resi_to_name = {}
cluster_dict={}
#chain_index=str(chain_name_li.index(chain_name))
pos_gnum = numbers[current_class]
for pos in result:
if pos[0] != "-": #Consider only num in the pdb
db_pos=pos[1][1]
pdb_pos=pos[0][1]
#gnum_or_nth=""
this_gnum = pos_gnum[db_pos][1]
this_segm = pos_gnum[db_pos][2]
resi_to_group[(pdb_pos,chain_name)]=str(this_segm)
if this_gnum:#If exist GPCR num for this position
this_gnum=this_gnum[:this_gnum.find(".")]+this_gnum[this_gnum.find("x"):]
cluster_dict[this_gnum]=[chain_name+"."+pdb_pos,""]
resi_to_name[(pdb_pos,chain_name)]=str(this_gnum)
return(resi_to_group,resi_to_name,cluster_dict)
def create_fplot(self,dyn_id,newpath,pdbpath=None,trajpath=None,traj_id=None,stride=1):# Not sure what will happen in pdbs with more than 1 gpcr . Use traj 14 or 15 for dyn 1
"""Generates the json files necessary to visualize flare plots."""
gpcr_mode=True
if (trajpath==None and traj_id):
trajpath=DyndbFiles.objects.get(id=traj_id)
if (pdbpath==None):
pdbpath=DyndbFiles.objects.filter(dyndbfilesdynamics__id_dynamics=dyn_id, id_file_types__extension="pdb")[0].filepath
chain_name_li=obtain_all_chains(pdbpath)
if (len(chain_name_li)==0):
error="Protein chains not found."
self.stdout.write(self.style.NOTICE(error))
return
prot_li_gpcr, dprot_li_all,dprot_li_all_info,pdbid=obtain_DyndbProtein_id_list(dyn_id)
dprot_chains={}
chains_taken=set()
prot_seq_pos={}
seq_pos_n=1
for prot_id, prot_name, prot_is_gpcr, prot_seq in dprot_li_all_info: #To classify chains by protein (dprot_chains is a dict:for each protein, has a list of each chain with its matchpdbfa results + the protein seq_pos)
seq_pos=[]
dprot_chains[prot_id]=[[],[]]
for chain_name in chain_name_li:
checkpdb_res=checkpdb_ngl(pdbpath, segid="",start=-1,stop=9999999999999999999, chain=chain_name)
if isinstance(checkpdb_res, tuple):
tablepdb,pdb_sequence,hexflag=checkpdb_res
result=matchpdbfa_ngl(prot_seq,pdb_sequence, tablepdb, hexflag)
type(result)
if isinstance(result, list):
#chain_results[chain_name]=result
if chain_name not in chains_taken:
chains_taken.add(chain_name)
dprot_chains[prot_id][0].append((chain_name,result))
(seq_pos,seq_pos_n)=obtain_seq_pos_info(result,seq_pos,seq_pos_n,chain_name,True)
dprot_chains[prot_id][1]=seq_pos
prot_seq_pos[prot_id]=(prot_name,seq_pos)
keys_to_rm=set()
for key, val in dprot_chains.items():
if val==([],[]):
keys_to_rm.add(key)
for key in keys_to_rm:
del dprot_chains[key]
if chains_taken: # To check if some result have been obtained
for gpcr_DprotGprot in prot_li_gpcr:
gpcr_Dprot=gpcr_DprotGprot[0]
gpcr_Gprot=gpcr_DprotGprot[1]
dprot_id=gpcr_Dprot.id
dprot_name=gpcr_Dprot.name
gen_num_res=obtain_gen_numbering(dyn_id, gpcr_Dprot,gpcr_Gprot)
if len(gen_num_res) > 2:
(numbers, num_scheme, db_seq, current_class) = gen_num_res
current_class=findGPCRclass(num_scheme)
gpcr_n_ex=""
for pos_gnum in numbers[current_class].values():
if pos_gnum[1]: #We take the 1st instance of gpcr num as example, and check in which format it is (n.nnxnn or nxnn)
gpcr_n_ex=pos_gnum[1]
break
if not "." in gpcr_n_ex: #For the moment we only accept n.nnxnn format
error="Error obtaining GPCR generic numbering."
self.stdout.write(self.style.NOTICE(error))
return
(dprot_chain_li, dprot_seq) = dprot_chains[dprot_id]
for chain_name, result in dprot_chain_li:
(resi_to_group,resi_to_name,cluster_dict)=obtain_fplot_input(result,numbers,chain_name,current_class)
model_res=DyndbModeledResidues.objects.filter(id_model__dyndbdynamics__id=dyn_id)
seg_to_chain={mr.segid : mr.chain for mr in model_res}
if gpcr_mode:
for (pos, gnum) in resi_to_name.items():
if gnum != "None":
chain=gnum.split("x",1)[0]
resi_to_name[pos]=chain+"."+gnum
create_json(self,True,trajpath,pdbpath,resi_to_group,resi_to_name,newpath,stride,seg_to_chain)
else:
create_json(self,False,trajpath,pdbpath,resi_to_group,resi_to_name,newpath,stride,seg_to_chain)
out_file = re.search("(\w*)(\.\w*)$" , newpath).group()
self.stdout.write(self.style.SUCCESS('JSON file '+out_file+' successfully created'))
else:
error="Error obtaining GPCR generic numbering."
self.stdout.write(self.style.NOTICE(error))
return
else:
error="Error assigning the GPCR generic numbering to the PDB"
self.stdout.write(self.style.NOTICE(error))
return
| en | 0.789269 | #[!] Now it's the wn version (new version that uses MDtraj wernet_nilsson function) #chain_index=str(chain_name_li.index(chain_name)) #Consider only num in the pdb #gnum_or_nth="" #If exist GPCR num for this position # Not sure what will happen in pdbs with more than 1 gpcr . Use traj 14 or 15 for dyn 1 Generates the json files necessary to visualize flare plots. #To classify chains by protein (dprot_chains is a dict:for each protein, has a list of each chain with its matchpdbfa results + the protein seq_pos) #chain_results[chain_name]=result # To check if some result have been obtained #We take the 1st instance of gpcr num as example, and check in which format it is (n.nnxnn or nxnn) #For the moment we only accept n.nnxnn format | 2.329616 | 2 |
autogalaxy/profiles/light_profiles/light_profiles_linear.py | caoxiaoyue/PyAutoGalaxy | 0 | 6620406 | import numpy as np
from typing import Tuple
import autoarray as aa
from autogalaxy.profiles.light_profiles import light_profiles as lp
class LightProfileLinear(lp.LightProfile, aa.LinearObj):
def mapping_matrix_from(self, grid: aa.type.Grid2DLike) -> np.ndarray:
return self.image_2d_from(grid=grid).slim
class EllSersic(lp.AbstractEllSersic, LightProfileLinear):
def __init__(
self,
centre: Tuple[float, float] = (0.0, 0.0),
elliptical_comps: Tuple[float, float] = (0.0, 0.0),
effective_radius: float = 0.6,
sersic_index: float = 4.0,
):
"""
The elliptical Sersic light profile.
See `autogalaxy.profiles.light_profiles.light_profiles.LightProfile` for a description of light profile objects.
Parameters
----------
centre
The (y,x) arc-second coordinates of the profile centre.
elliptical_comps
The first and second ellipticity components of the elliptical coordinate system, (see the module
`autogalaxy -> convert.py` for the convention).
effective_radius
The circular radius containing half the light of this profile.
sersic_index
Controls the concentration of the profile (lower -> less concentrated, higher -> more concentrated).
"""
super().__init__(
centre=centre,
elliptical_comps=elliptical_comps,
intensity=1.0,
effective_radius=effective_radius,
sersic_index=sersic_index,
)
| import numpy as np
from typing import Tuple
import autoarray as aa
from autogalaxy.profiles.light_profiles import light_profiles as lp
class LightProfileLinear(lp.LightProfile, aa.LinearObj):
def mapping_matrix_from(self, grid: aa.type.Grid2DLike) -> np.ndarray:
return self.image_2d_from(grid=grid).slim
class EllSersic(lp.AbstractEllSersic, LightProfileLinear):
def __init__(
self,
centre: Tuple[float, float] = (0.0, 0.0),
elliptical_comps: Tuple[float, float] = (0.0, 0.0),
effective_radius: float = 0.6,
sersic_index: float = 4.0,
):
"""
The elliptical Sersic light profile.
See `autogalaxy.profiles.light_profiles.light_profiles.LightProfile` for a description of light profile objects.
Parameters
----------
centre
The (y,x) arc-second coordinates of the profile centre.
elliptical_comps
The first and second ellipticity components of the elliptical coordinate system, (see the module
`autogalaxy -> convert.py` for the convention).
effective_radius
The circular radius containing half the light of this profile.
sersic_index
Controls the concentration of the profile (lower -> less concentrated, higher -> more concentrated).
"""
super().__init__(
centre=centre,
elliptical_comps=elliptical_comps,
intensity=1.0,
effective_radius=effective_radius,
sersic_index=sersic_index,
)
| en | 0.630024 | The elliptical Sersic light profile.
See `autogalaxy.profiles.light_profiles.light_profiles.LightProfile` for a description of light profile objects.
Parameters
----------
centre
The (y,x) arc-second coordinates of the profile centre.
elliptical_comps
The first and second ellipticity components of the elliptical coordinate system, (see the module
`autogalaxy -> convert.py` for the convention).
effective_radius
The circular radius containing half the light of this profile.
sersic_index
Controls the concentration of the profile (lower -> less concentrated, higher -> more concentrated). | 2.663876 | 3 |
browser_calls/migrations/0001_initial.py | friendm/browser-calls-django | 0 | 6620407 | <reponame>friendm/browser-calls-django
# Generated by Django 3.0.8 on 2020-11-01 20:20
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SupportTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('phone_number', phonenumber_field.modelfields.PhoneNumberField(help_text='Must include international prefix - e.g. +1 555 555 55555', max_length=128, region=None)),
('description', models.TextField(help_text='A description of your problem')),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
]
| # Generated by Django 3.0.8 on 2020-11-01 20:20
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SupportTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('phone_number', phonenumber_field.modelfields.PhoneNumberField(help_text='Must include international prefix - e.g. +1 555 555 55555', max_length=128, region=None)),
('description', models.TextField(help_text='A description of your problem')),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
] | en | 0.856889 | # Generated by Django 3.0.8 on 2020-11-01 20:20 | 1.944349 | 2 |
Backend/events/migrations/0001_initial.py | afrlv1/TestWorkEvents | 0 | 6620408 | <filename>Backend/events/migrations/0001_initial.py
# Generated by Django 3.0.7 on 2020-06-30 05:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField(help_text='Day of the event', verbose_name='Day of the event')),
('title', models.CharField(blank=True, help_text='Title', max_length=255, null=True, verbose_name='Title')),
('body', models.TextField(blank=True, help_text='Textual Event', null=True, verbose_name='Textual Event')),
],
options={
'verbose_name': 'Scheduling',
'verbose_name_plural': 'Scheduling',
},
),
]
| <filename>Backend/events/migrations/0001_initial.py
# Generated by Django 3.0.7 on 2020-06-30 05:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.DateField(help_text='Day of the event', verbose_name='Day of the event')),
('title', models.CharField(blank=True, help_text='Title', max_length=255, null=True, verbose_name='Title')),
('body', models.TextField(blank=True, help_text='Textual Event', null=True, verbose_name='Textual Event')),
],
options={
'verbose_name': 'Scheduling',
'verbose_name_plural': 'Scheduling',
},
),
]
| en | 0.794839 | # Generated by Django 3.0.7 on 2020-06-30 05:54 | 1.713916 | 2 |
perception/Old/CVChess-master/src/corner_ml.py | gabrieledamone/DE3-ROB1-CHESS | 25 | 6620409 | <reponame>gabrieledamone/DE3-ROB1-CHESS
import os
import pickle
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
# from CVAnalysis import GetCornerFeatures
def is_sift (f):
return f[0] == 's'
def is_coords (f):
return f[0] == 'i'
if __name__ == "__main__":
data_dir = './corner_data'
#=====[ Step 1: change to correct directory ]=====
os.chdir (data_dir)
#=====[ Step 2: load features ]=====
# features_pos = pickle.load (open('features.mat', 'r'))
features_pos = pickle.load (open('specialized_corners.mat', 'r'))
features_neg = pickle.load (open('features_neg.mat', 'r'))
# fp_train, fp_test = features_pos[:300], features_pos[300:]
# fn_train, fn_test = features_neg[:-300], features_neg[-300:]
# yp_train, yp_test = np.ones ((fp_train.shape[0],)), np.ones ((fp_test.shape[0],))
# yn_train, yn_test = np.zeros ((fn_train.shape[0],)), np.zeros ((fn_test.shape[0],))
# X_train = np.concatenate ([fp_train, fn_train], 0)
# y_train = np.concatenate ([yp_train, yn_train])
# X_test = np.concatenate ([fp_test, fn_test])
# y_test = np.concatenate ([yp_test, yn_test])
X_train = np.concatenate ([features_pos, features_neg])
y_train = np.concatenate ([np.ones ((features_pos.shape[0],)), np.zeros((features_neg.shape[0],))])
#=====[ Step 3: create/fit/score raw models ]=====
lr = LogisticRegression ().fit (X_train, y_train)
dt = DecisionTreeClassifier ().fit (X_train, y_train)
rf = RandomForestClassifier ().fit (X_train, y_train)
svm = SVC().fit (X_train, y_train)
# print "=====[ RAW SCORES ]====="
# print "LogisticRegression: ", lr.score (X_test, y_test)
# print "DecisionTree: ", dt.score (X_test, y_test)
# print "RandomForest: ", rf.score (X_test, y_test)
# print "SVM: ", svm.score (X_test, y_test)
| import os
import pickle
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
# from CVAnalysis import GetCornerFeatures
def is_sift (f):
return f[0] == 's'
def is_coords (f):
return f[0] == 'i'
if __name__ == "__main__":
data_dir = './corner_data'
#=====[ Step 1: change to correct directory ]=====
os.chdir (data_dir)
#=====[ Step 2: load features ]=====
# features_pos = pickle.load (open('features.mat', 'r'))
features_pos = pickle.load (open('specialized_corners.mat', 'r'))
features_neg = pickle.load (open('features_neg.mat', 'r'))
# fp_train, fp_test = features_pos[:300], features_pos[300:]
# fn_train, fn_test = features_neg[:-300], features_neg[-300:]
# yp_train, yp_test = np.ones ((fp_train.shape[0],)), np.ones ((fp_test.shape[0],))
# yn_train, yn_test = np.zeros ((fn_train.shape[0],)), np.zeros ((fn_test.shape[0],))
# X_train = np.concatenate ([fp_train, fn_train], 0)
# y_train = np.concatenate ([yp_train, yn_train])
# X_test = np.concatenate ([fp_test, fn_test])
# y_test = np.concatenate ([yp_test, yn_test])
X_train = np.concatenate ([features_pos, features_neg])
y_train = np.concatenate ([np.ones ((features_pos.shape[0],)), np.zeros((features_neg.shape[0],))])
#=====[ Step 3: create/fit/score raw models ]=====
lr = LogisticRegression ().fit (X_train, y_train)
dt = DecisionTreeClassifier ().fit (X_train, y_train)
rf = RandomForestClassifier ().fit (X_train, y_train)
svm = SVC().fit (X_train, y_train)
# print "=====[ RAW SCORES ]====="
# print "LogisticRegression: ", lr.score (X_test, y_test)
# print "DecisionTree: ", dt.score (X_test, y_test)
# print "RandomForest: ", rf.score (X_test, y_test)
# print "SVM: ", svm.score (X_test, y_test) | en | 0.553517 | # from CVAnalysis import GetCornerFeatures #=====[ Step 1: change to correct directory ]===== #=====[ Step 2: load features ]===== # features_pos = pickle.load (open('features.mat', 'r')) # fp_train, fp_test = features_pos[:300], features_pos[300:] # fn_train, fn_test = features_neg[:-300], features_neg[-300:] # yp_train, yp_test = np.ones ((fp_train.shape[0],)), np.ones ((fp_test.shape[0],)) # yn_train, yn_test = np.zeros ((fn_train.shape[0],)), np.zeros ((fn_test.shape[0],)) # X_train = np.concatenate ([fp_train, fn_train], 0) # y_train = np.concatenate ([yp_train, yn_train]) # X_test = np.concatenate ([fp_test, fn_test]) # y_test = np.concatenate ([yp_test, yn_test]) #=====[ Step 3: create/fit/score raw models ]===== # print "=====[ RAW SCORES ]=====" # print "LogisticRegression: ", lr.score (X_test, y_test) # print "DecisionTree: ", dt.score (X_test, y_test) # print "RandomForest: ", rf.score (X_test, y_test) # print "SVM: ", svm.score (X_test, y_test) | 2.373669 | 2 |
accuracy/accuracy_plot.py | tpudlik/sbf | 4 | 6620410 | <filename>accuracy/accuracy_plot.py
"""Create accuracy plots for the given algorithm.
Usage: python accuracy_plot.py sbf algo
"""
import sys
from os import path
from itertools import izip
import numpy as np
from matplotlib import pyplot as plt
# Path hack
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from reference.config import (INNER_RADIUS, OUTER_RADIUS, RADIAL_POINTS,
ANGULAR_POINTS, MAX_ORDER)
REFERENCE_DIR = path.join(path.dirname(path.dirname(path.abspath(__file__))),
"reference")
def accuracy_plot(f, sbf, atol, rtol):
"""Generates plots illustrating the accuracy of f in approximating the
named sbf.
White is good, black is bad, red indicates NaN (likely underflow or
overflow). The quantity plotted is,
(|f - reference| - atol)/(|reference|*rtol)
If this is less than 1, then f is within tolerance of the reference value.
Parameters
----------
f : function
The function to be tested. It should take two arguments, the order n
and the argument z.
sbf : string
The spherical Bessel function that f should approximate. One of "jn",
"yn", "h1n", "h2n", "i1n", "i2n", or "kn".
atol : float
Absolute tolerance
Returns
-------
Nothing, but creates ANGULAR_POINTS pngs.
"""
if sbf not in ("jn", "yn", "h1n", "h2n", "i1n", "i2n", "kn"):
raise ValueError("Unrecorgnized sbf value {}".format(sbf))
real_points = np.load(path.join(REFERENCE_DIR,
"reference_points_real.npy"))
complex_points = np.split(np.load(path.join(REFERENCE_DIR,
"reference_points_complex.npy")),
ANGULAR_POINTS)
real_ref_values, complex_ref_values = get_ref_values(sbf)
real_values = f(real_points['n'], real_points['z'])
complex_values = [f(x['n'], x['z']) for x in complex_points]
make_accuracy_plot(real_points, real_values, real_ref_values,
atol, rtol, "{}_real.png".format(sbf),
"real line")
for point, value, ref_value, idx in izip(complex_points, complex_values,
complex_ref_values,
xrange(ANGULAR_POINTS)):
make_accuracy_plot(point, value, ref_value, atol, rtol,
"{}_complex_{}.png".format(sbf, idx),
r"$\exp(2\pi\imath*{}/{})$ line".format(idx + 1, ANGULAR_POINTS + 1))
def make_accuracy_plot(point, value, reference, atol, rtol, filename,
title=None):
z = np.reshape(point['z'], (RADIAL_POINTS, MAX_ORDER + 1))
n = np.reshape(point['n'], (RADIAL_POINTS, MAX_ORDER + 1))
error_1D = compute_error(value, reference, atol, rtol)
error = np.reshape(error_1D,
(RADIAL_POINTS, MAX_ORDER + 1))
imdata = np.ma.masked_invalid(error)
cmap = plt.cm.Greys
cmap.set_bad('r', 1)
fig, ax = plt.subplots()
im = ax.pcolormesh(np.log10(np.abs(z.transpose())), n.transpose(),
imdata.transpose(),
cmap=cmap, vmin=1, vmax=5)
plt.colorbar(im)
ax.set_xlim((INNER_RADIUS, OUTER_RADIUS))
ax.set_ylim((0, imdata.shape[1]))
ax.set_xlabel(r"$\log_{10}(|z|)$")
ax.set_ylabel("order")
if title:
ax.set_title(title)
plt.savefig(filename)
plt.close(fig)
def compute_error(value, reference, atol, rtol):
out = np.empty(np.shape(reference))
denominator = np.abs(reference)*rtol
idx = (denominator == 0)
out[idx] = (np.abs(value[idx])-atol)/rtol
idx = (denominator != 0)
out[idx] = (np.abs(value[idx] - reference[idx]) - atol)/denominator[idx]
# Covers np.inf
idx = (value == reference)
out[idx] = np.zeros(out.shape)[idx]
# Covers complex infinity
idx = np.logical_and(np.logical_and(np.iscomplex(value),
np.isinf(value)),
np.logical_and(np.iscomplex(reference),
np.isinf(reference)))
out[idx] = np.zeros(out.shape)[idx]
return np.log10(np.clip(out, 10**(-300), np.inf))
def get_ref_values(sbf):
"""Return arrays of reference values for sbf at real and complex args."""
filename = path.join(REFERENCE_DIR, "{}.npy".format(sbf))
values = np.split(np.load(filename), ANGULAR_POINTS + 1)
return values[0], values[1:]
if __name__ == '__main__':
import argparse, importlib
parser = argparse.ArgumentParser()
parser.add_argument("sbf",
help="The spherical Bessel function to create plots for.",
choices=["jn", "yn", "h1n", "h2n", "i1n", "i2n", "kn"])
parser.add_argument("algo",
help="The algorithm to create plots for.",
choices=["default", "bessel", "a_recur", "cai",
"power_series", "d_recur_miller",
"candidate"])
args = parser.parse_args()
m = importlib.import_module("algos.{}".format(args.algo))
f = getattr(m, "sph_{}".format(args.sbf))
accuracy_plot(f, args.sbf, 10**(-100), 10**(-14))
| <filename>accuracy/accuracy_plot.py
"""Create accuracy plots for the given algorithm.
Usage: python accuracy_plot.py sbf algo
"""
import sys
from os import path
from itertools import izip
import numpy as np
from matplotlib import pyplot as plt
# Path hack
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from reference.config import (INNER_RADIUS, OUTER_RADIUS, RADIAL_POINTS,
ANGULAR_POINTS, MAX_ORDER)
REFERENCE_DIR = path.join(path.dirname(path.dirname(path.abspath(__file__))),
"reference")
def accuracy_plot(f, sbf, atol, rtol):
"""Generates plots illustrating the accuracy of f in approximating the
named sbf.
White is good, black is bad, red indicates NaN (likely underflow or
overflow). The quantity plotted is,
(|f - reference| - atol)/(|reference|*rtol)
If this is less than 1, then f is within tolerance of the reference value.
Parameters
----------
f : function
The function to be tested. It should take two arguments, the order n
and the argument z.
sbf : string
The spherical Bessel function that f should approximate. One of "jn",
"yn", "h1n", "h2n", "i1n", "i2n", or "kn".
atol : float
Absolute tolerance
Returns
-------
Nothing, but creates ANGULAR_POINTS pngs.
"""
if sbf not in ("jn", "yn", "h1n", "h2n", "i1n", "i2n", "kn"):
raise ValueError("Unrecorgnized sbf value {}".format(sbf))
real_points = np.load(path.join(REFERENCE_DIR,
"reference_points_real.npy"))
complex_points = np.split(np.load(path.join(REFERENCE_DIR,
"reference_points_complex.npy")),
ANGULAR_POINTS)
real_ref_values, complex_ref_values = get_ref_values(sbf)
real_values = f(real_points['n'], real_points['z'])
complex_values = [f(x['n'], x['z']) for x in complex_points]
make_accuracy_plot(real_points, real_values, real_ref_values,
atol, rtol, "{}_real.png".format(sbf),
"real line")
for point, value, ref_value, idx in izip(complex_points, complex_values,
complex_ref_values,
xrange(ANGULAR_POINTS)):
make_accuracy_plot(point, value, ref_value, atol, rtol,
"{}_complex_{}.png".format(sbf, idx),
r"$\exp(2\pi\imath*{}/{})$ line".format(idx + 1, ANGULAR_POINTS + 1))
def make_accuracy_plot(point, value, reference, atol, rtol, filename,
title=None):
z = np.reshape(point['z'], (RADIAL_POINTS, MAX_ORDER + 1))
n = np.reshape(point['n'], (RADIAL_POINTS, MAX_ORDER + 1))
error_1D = compute_error(value, reference, atol, rtol)
error = np.reshape(error_1D,
(RADIAL_POINTS, MAX_ORDER + 1))
imdata = np.ma.masked_invalid(error)
cmap = plt.cm.Greys
cmap.set_bad('r', 1)
fig, ax = plt.subplots()
im = ax.pcolormesh(np.log10(np.abs(z.transpose())), n.transpose(),
imdata.transpose(),
cmap=cmap, vmin=1, vmax=5)
plt.colorbar(im)
ax.set_xlim((INNER_RADIUS, OUTER_RADIUS))
ax.set_ylim((0, imdata.shape[1]))
ax.set_xlabel(r"$\log_{10}(|z|)$")
ax.set_ylabel("order")
if title:
ax.set_title(title)
plt.savefig(filename)
plt.close(fig)
def compute_error(value, reference, atol, rtol):
out = np.empty(np.shape(reference))
denominator = np.abs(reference)*rtol
idx = (denominator == 0)
out[idx] = (np.abs(value[idx])-atol)/rtol
idx = (denominator != 0)
out[idx] = (np.abs(value[idx] - reference[idx]) - atol)/denominator[idx]
# Covers np.inf
idx = (value == reference)
out[idx] = np.zeros(out.shape)[idx]
# Covers complex infinity
idx = np.logical_and(np.logical_and(np.iscomplex(value),
np.isinf(value)),
np.logical_and(np.iscomplex(reference),
np.isinf(reference)))
out[idx] = np.zeros(out.shape)[idx]
return np.log10(np.clip(out, 10**(-300), np.inf))
def get_ref_values(sbf):
"""Return arrays of reference values for sbf at real and complex args."""
filename = path.join(REFERENCE_DIR, "{}.npy".format(sbf))
values = np.split(np.load(filename), ANGULAR_POINTS + 1)
return values[0], values[1:]
if __name__ == '__main__':
import argparse, importlib
parser = argparse.ArgumentParser()
parser.add_argument("sbf",
help="The spherical Bessel function to create plots for.",
choices=["jn", "yn", "h1n", "h2n", "i1n", "i2n", "kn"])
parser.add_argument("algo",
help="The algorithm to create plots for.",
choices=["default", "bessel", "a_recur", "cai",
"power_series", "d_recur_miller",
"candidate"])
args = parser.parse_args()
m = importlib.import_module("algos.{}".format(args.algo))
f = getattr(m, "sph_{}".format(args.sbf))
accuracy_plot(f, args.sbf, 10**(-100), 10**(-14))
| en | 0.651768 | Create accuracy plots for the given algorithm. Usage: python accuracy_plot.py sbf algo # Path hack Generates plots illustrating the accuracy of f in approximating the named sbf. White is good, black is bad, red indicates NaN (likely underflow or overflow). The quantity plotted is, (|f - reference| - atol)/(|reference|*rtol) If this is less than 1, then f is within tolerance of the reference value. Parameters ---------- f : function The function to be tested. It should take two arguments, the order n and the argument z. sbf : string The spherical Bessel function that f should approximate. One of "jn", "yn", "h1n", "h2n", "i1n", "i2n", or "kn". atol : float Absolute tolerance Returns ------- Nothing, but creates ANGULAR_POINTS pngs. # Covers np.inf # Covers complex infinity Return arrays of reference values for sbf at real and complex args. | 3.265264 | 3 |
alipay/aop/api/domain/AlipayIserviceCliveVisitorOfflineModel.py | antopen/alipay-sdk-python-all | 213 | 6620411 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayIserviceCliveVisitorOfflineModel(object):
def __init__(self):
self._visitor_id = None
self._visitor_token = None
@property
def visitor_id(self):
return self._visitor_id
@visitor_id.setter
def visitor_id(self, value):
self._visitor_id = value
@property
def visitor_token(self):
return self._visitor_token
@visitor_token.setter
def visitor_token(self, value):
self._visitor_token = value
def to_alipay_dict(self):
params = dict()
if self.visitor_id:
if hasattr(self.visitor_id, 'to_alipay_dict'):
params['visitor_id'] = self.visitor_id.to_alipay_dict()
else:
params['visitor_id'] = self.visitor_id
if self.visitor_token:
if hasattr(self.visitor_token, 'to_alipay_dict'):
params['visitor_token'] = self.visitor_token.to_alipay_dict()
else:
params['visitor_token'] = self.visitor_token
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayIserviceCliveVisitorOfflineModel()
if 'visitor_id' in d:
o.visitor_id = d['visitor_id']
if 'visitor_token' in d:
o.visitor_token = d['visitor_token']
return o
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayIserviceCliveVisitorOfflineModel(object):
def __init__(self):
self._visitor_id = None
self._visitor_token = None
@property
def visitor_id(self):
return self._visitor_id
@visitor_id.setter
def visitor_id(self, value):
self._visitor_id = value
@property
def visitor_token(self):
return self._visitor_token
@visitor_token.setter
def visitor_token(self, value):
self._visitor_token = value
def to_alipay_dict(self):
params = dict()
if self.visitor_id:
if hasattr(self.visitor_id, 'to_alipay_dict'):
params['visitor_id'] = self.visitor_id.to_alipay_dict()
else:
params['visitor_id'] = self.visitor_id
if self.visitor_token:
if hasattr(self.visitor_token, 'to_alipay_dict'):
params['visitor_token'] = self.visitor_token.to_alipay_dict()
else:
params['visitor_token'] = self.visitor_token
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayIserviceCliveVisitorOfflineModel()
if 'visitor_id' in d:
o.visitor_id = d['visitor_id']
if 'visitor_token' in d:
o.visitor_token = d['visitor_token']
return o
| en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 2.046131 | 2 |
pridesport_work/sportgoods/migrations/0006_auto_20201123_1850.py | Trifon87/pridesport_work | 0 | 6620412 | <filename>pridesport_work/sportgoods/migrations/0006_auto_20201123_1850.py
# Generated by Django 3.1.3 on 2020-11-23 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sportgoods', '0005_comment'),
]
operations = [
migrations.AlterField(
model_name='gear',
name='image_url',
field=models.ImageField(upload_to='gear'),
),
]
| <filename>pridesport_work/sportgoods/migrations/0006_auto_20201123_1850.py
# Generated by Django 3.1.3 on 2020-11-23 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sportgoods', '0005_comment'),
]
operations = [
migrations.AlterField(
model_name='gear',
name='image_url',
field=models.ImageField(upload_to='gear'),
),
]
| en | 0.825671 | # Generated by Django 3.1.3 on 2020-11-23 16:50 | 1.232414 | 1 |
notebooks/78.0-BDP-try-draw-gt-hierarchy.py | zeou1/maggot_models | 0 | 6620413 | # import graph_tool as gt
from graph_tool.collection import data
from graph_tool import inference
from graph_tool import draw
from graph_tool.draw import draw_hierarchy
g = data["celegansneural"]
state = inference.minimize_nested_blockmodel_dl(g, deg_corr=True)
draw_hierarchy(state, output="celegansneural_nested_mdl.pdf")
| # import graph_tool as gt
from graph_tool.collection import data
from graph_tool import inference
from graph_tool import draw
from graph_tool.draw import draw_hierarchy
g = data["celegansneural"]
state = inference.minimize_nested_blockmodel_dl(g, deg_corr=True)
draw_hierarchy(state, output="celegansneural_nested_mdl.pdf")
| en | 0.886018 | # import graph_tool as gt | 1.866713 | 2 |
code/setup/setup.exe.py | Samthebest999/AI-Friend | 0 | 6620414 | <reponame>Samthebest999/AI-Friend
import os
import wget
import shutil
working_dir = os.getcwd()
os.makedirs("python")
wget.download("https://raw.githubusercontent.com/Samthebest999/AI-Friend/main/code/setup/python.zip", "python/")
shutil.unpack_archive("python/python.zip", "python/", "zip")
os.remove("python/python.zip")
os.system(working_dir + "\\python\\python.exe python\\get-pip.py")
os.system(working_dir + "\\python\\python.exe -m pip install pip wheel setuptools wget")
os.system(working_dir + "\\python\\python.exe -m pip install --upgrade pip wheel setuptools")
wget.download("https://raw.githubusercontent.com/Samthebest999/AI-Friend/main/code/setup.py")
os.system(working_dir + "\\python\\python.exe setup.py")
| import os
import wget
import shutil
working_dir = os.getcwd()
os.makedirs("python")
wget.download("https://raw.githubusercontent.com/Samthebest999/AI-Friend/main/code/setup/python.zip", "python/")
shutil.unpack_archive("python/python.zip", "python/", "zip")
os.remove("python/python.zip")
os.system(working_dir + "\\python\\python.exe python\\get-pip.py")
os.system(working_dir + "\\python\\python.exe -m pip install pip wheel setuptools wget")
os.system(working_dir + "\\python\\python.exe -m pip install --upgrade pip wheel setuptools")
wget.download("https://raw.githubusercontent.com/Samthebest999/AI-Friend/main/code/setup.py")
os.system(working_dir + "\\python\\python.exe setup.py") | none | 1 | 1.943389 | 2 | |
tests/test_5stdlib.py | cmarkello/miniwdl | 0 | 6620415 | <gh_stars>0
import unittest
import logging
import tempfile
from .context import WDL
class TestStdLib(unittest.TestCase):
def setUp(self):
logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
self._dir = tempfile.mkdtemp(prefix="miniwdl_test_stdlib_")
def _test_task(self, wdl:str, inputs = None, expected_exception: Exception = None):
doc = WDL.parse_document(wdl)
assert len(doc.tasks) == 1
doc.typecheck()
if isinstance(inputs, dict):
inputs = WDL.values_from_json(inputs, doc.tasks[0].available_inputs, doc.tasks[0].required_inputs)
if expected_exception:
try:
WDL.runtime.run_local_task(doc.tasks[0], (inputs or []), parent_dir=self._dir)
except WDL.runtime.task.TaskFailure as exn:
self.assertIsInstance(exn.__context__, expected_exception)
return exn.__context__
self.assertFalse(str(expected_exception) + " not raised")
rundir, outputs = WDL.runtime.run_local_task(doc.tasks[0], (inputs or []), parent_dir=self._dir)
return WDL.values_to_json(outputs)
def test_size_polytype(self):
tmpl = """
version 1.0
task test_size {{
input {{
File file1
File file2
}}
{}
command <<<
echo "nop"
>>>
}}
"""
for case in [
"Float sz = size(file1)",
"Float sz = size(file1, 'GB')",
"Float sz = size([file1,file2], 'KB')",
"Float sz = size([file1,file2], 'KB')",
]:
doc = WDL.parse_document(tmpl.format(case))
doc.typecheck()
for case in [
("Float sz = size()", WDL.Error.WrongArity),
("Float sz = size(file1,file2,'MB')", WDL.Error.WrongArity),
("Float sz = size(42)", WDL.Error.StaticTypeMismatch),
("Float sz = size([42])", WDL.Error.StaticTypeMismatch),
("Float sz = size(file1,file2)", WDL.Error.StaticTypeMismatch),
("Float sz = size(file1,[file2])", WDL.Error.StaticTypeMismatch),
]:
doc = WDL.parse_document(tmpl.format(case[0]))
with self.assertRaises(case[1]):
doc.typecheck()
def test_length(self):
outputs = self._test_task(R"""
version 1.0
task test_length {
command {}
output {
Int l0 = length([])
Int l1 = length([42])
Int l2 = length([42,43])
}
}
""")
self.assertEqual(outputs, {"l0": 0, "l1": 1, "l2" : 2})
| import unittest
import logging
import tempfile
from .context import WDL
class TestStdLib(unittest.TestCase):
def setUp(self):
logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
self._dir = tempfile.mkdtemp(prefix="miniwdl_test_stdlib_")
def _test_task(self, wdl:str, inputs = None, expected_exception: Exception = None):
doc = WDL.parse_document(wdl)
assert len(doc.tasks) == 1
doc.typecheck()
if isinstance(inputs, dict):
inputs = WDL.values_from_json(inputs, doc.tasks[0].available_inputs, doc.tasks[0].required_inputs)
if expected_exception:
try:
WDL.runtime.run_local_task(doc.tasks[0], (inputs or []), parent_dir=self._dir)
except WDL.runtime.task.TaskFailure as exn:
self.assertIsInstance(exn.__context__, expected_exception)
return exn.__context__
self.assertFalse(str(expected_exception) + " not raised")
rundir, outputs = WDL.runtime.run_local_task(doc.tasks[0], (inputs or []), parent_dir=self._dir)
return WDL.values_to_json(outputs)
def test_size_polytype(self):
tmpl = """
version 1.0
task test_size {{
input {{
File file1
File file2
}}
{}
command <<<
echo "nop"
>>>
}}
"""
for case in [
"Float sz = size(file1)",
"Float sz = size(file1, 'GB')",
"Float sz = size([file1,file2], 'KB')",
"Float sz = size([file1,file2], 'KB')",
]:
doc = WDL.parse_document(tmpl.format(case))
doc.typecheck()
for case in [
("Float sz = size()", WDL.Error.WrongArity),
("Float sz = size(file1,file2,'MB')", WDL.Error.WrongArity),
("Float sz = size(42)", WDL.Error.StaticTypeMismatch),
("Float sz = size([42])", WDL.Error.StaticTypeMismatch),
("Float sz = size(file1,file2)", WDL.Error.StaticTypeMismatch),
("Float sz = size(file1,[file2])", WDL.Error.StaticTypeMismatch),
]:
doc = WDL.parse_document(tmpl.format(case[0]))
with self.assertRaises(case[1]):
doc.typecheck()
def test_length(self):
outputs = self._test_task(R"""
version 1.0
task test_length {
command {}
output {
Int l0 = length([])
Int l1 = length([42])
Int l2 = length([42,43])
}
}
""")
self.assertEqual(outputs, {"l0": 0, "l1": 1, "l2" : 2}) | en | 0.295095 | version 1.0 task test_size {{ input {{ File file1 File file2 }} {} command <<< echo "nop" >>> }} version 1.0 task test_length { command {} output { Int l0 = length([]) Int l1 = length([42]) Int l2 = length([42,43]) } } | 2.674008 | 3 |
NanoPreprocessSimple/bin/fast5_type.py | vares-gui/master_of_pores | 0 | 6620416 | #!/usr/bin/env python
import sys
from ont_fast5_api.multi_fast5 import MultiFast5File
from ont_fast5_api.fast5_info import _clean
__author__ = '<EMAIL>'
__version__ = '0.2'
__email__ = 'same as author'
usage = '''
python fast5_type.py fast5file
return:
0: single read fast5
1: multi-reads fast5
'''
if len (sys.argv) !=2:
print (usage, file=sys.stderr)
sys.exit()
def check_file_type(f5_file):
try:
return _clean(f5_file.handle.attrs['file_type'])
except KeyError:
if len(f5_file.handle) == 0 :
return 1
if len([read for read in f5_file.handle if read.startswith('read_')]) !=0 :
return 1
if 'UniqueGlobalKey' in f5_file.handle:
return 0
raise TypeError('file can not be indetified as single- or multi- read.\n' 'File path: {}'.format(f5_file.filename))
filepath = sys.argv[1]
f5_file = MultiFast5File (filepath, mode='r')
filetype = check_file_type (f5_file)
print (filetype)
| #!/usr/bin/env python
import sys
from ont_fast5_api.multi_fast5 import MultiFast5File
from ont_fast5_api.fast5_info import _clean
__author__ = '<EMAIL>'
__version__ = '0.2'
__email__ = 'same as author'
usage = '''
python fast5_type.py fast5file
return:
0: single read fast5
1: multi-reads fast5
'''
if len (sys.argv) !=2:
print (usage, file=sys.stderr)
sys.exit()
def check_file_type(f5_file):
try:
return _clean(f5_file.handle.attrs['file_type'])
except KeyError:
if len(f5_file.handle) == 0 :
return 1
if len([read for read in f5_file.handle if read.startswith('read_')]) !=0 :
return 1
if 'UniqueGlobalKey' in f5_file.handle:
return 0
raise TypeError('file can not be indetified as single- or multi- read.\n' 'File path: {}'.format(f5_file.filename))
filepath = sys.argv[1]
f5_file = MultiFast5File (filepath, mode='r')
filetype = check_file_type (f5_file)
print (filetype)
| en | 0.514197 | #!/usr/bin/env python python fast5_type.py fast5file return: 0: single read fast5 1: multi-reads fast5 | 2.52507 | 3 |
tests/run_tests.py | ff0000/scarlet | 9 | 6620417 | #!/usr/bin/python
import os
import sys
import argparse
import importlib
import imp
import django
from django.conf import settings
def setup_test_environment(settings_overide, with_scarlet_blog=False):
"""
Specific settings for testing
"""
apps = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'scarlet.cms',
'scarlet.assets',
'scarlet.accounts',
'scarlet.versioning',
'scarlet.scheduling',
'taggit',
'tests.version_models',
'tests.version_twomodels',
'tests.cms_bundles',
]
urls = 'tests.cms_bundles.urls'
if with_scarlet_blog:
apps.append('scarlet_blog.blog')
apps.append('scarlet_blog.galleries')
apps.append('scarlet_blog.comments')
settings_dict = {
'SECRET_KEY': "Please do not spew DeprecationWarnings",
'SITE_ID': 1,
'INSTALLED_APPS': apps,
'STATIC_URL': '/static/',
'ROOT_URLCONF': urls,
'USE_TZ': True,
'DATABASES': {
'default': {
'ENGINE': 'scarlet.versioning.postgres_backend',
'NAME': 'cms',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
},
},
'MIDDLEWARE_CLASSES': (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
),
'TEMPLATES': [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
],
'debug': True,
},
}, ]
}
if settings_overide:
settings_dict.update(settings_overide)
settings.configure(**settings_dict)
def runtests(settings_overide, test_args):
"""
Build a test environment and a test_runner specifically for scarlet testing
allows a settings overide file and runs scarlet blog tests
if that module is present in the environment
"""
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
scarlet_root = os.path.abspath(os.path.join(parent, '..'))
sys.path.insert(0, scarlet_root)
settings_dict = {}
if settings_overide:
mod = importlib.import_module(settings_overide)
for s in dir(mod):
if s == s.upper():
settings_dict[s] = getattr(mod, s)
with_scarlet_blog = False
if not test_args:
test_args = ['tests.cms_bundles', 'tests.version_models', 'tests.version_twomodels']
try:
imp.find_module('scarlet_blog')
test_args.append('blog')
with_scarlet_blog = True
except ImportError:
with_scarlet_blog = False
elif 'blog' in test_args:
with_scarlet_blog = True
setup_test_environment(settings_dict, with_scarlet_blog=with_scarlet_blog)
django.setup()
from django.test.utils import get_runner
def run_tests(test_args, verbosity, interactive):
runner = get_runner(settings)()
return runner.run_tests(test_args)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--settings", default='')
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args()
runtests(args.settings, args.args) | #!/usr/bin/python
import os
import sys
import argparse
import importlib
import imp
import django
from django.conf import settings
def setup_test_environment(settings_overide, with_scarlet_blog=False):
"""
Specific settings for testing
"""
apps = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'scarlet.cms',
'scarlet.assets',
'scarlet.accounts',
'scarlet.versioning',
'scarlet.scheduling',
'taggit',
'tests.version_models',
'tests.version_twomodels',
'tests.cms_bundles',
]
urls = 'tests.cms_bundles.urls'
if with_scarlet_blog:
apps.append('scarlet_blog.blog')
apps.append('scarlet_blog.galleries')
apps.append('scarlet_blog.comments')
settings_dict = {
'SECRET_KEY': "Please do not spew DeprecationWarnings",
'SITE_ID': 1,
'INSTALLED_APPS': apps,
'STATIC_URL': '/static/',
'ROOT_URLCONF': urls,
'USE_TZ': True,
'DATABASES': {
'default': {
'ENGINE': 'scarlet.versioning.postgres_backend',
'NAME': 'cms',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
},
},
'MIDDLEWARE_CLASSES': (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
),
'TEMPLATES': [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
],
'debug': True,
},
}, ]
}
if settings_overide:
settings_dict.update(settings_overide)
settings.configure(**settings_dict)
def runtests(settings_overide, test_args):
"""
Build a test environment and a test_runner specifically for scarlet testing
allows a settings overide file and runs scarlet blog tests
if that module is present in the environment
"""
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
scarlet_root = os.path.abspath(os.path.join(parent, '..'))
sys.path.insert(0, scarlet_root)
settings_dict = {}
if settings_overide:
mod = importlib.import_module(settings_overide)
for s in dir(mod):
if s == s.upper():
settings_dict[s] = getattr(mod, s)
with_scarlet_blog = False
if not test_args:
test_args = ['tests.cms_bundles', 'tests.version_models', 'tests.version_twomodels']
try:
imp.find_module('scarlet_blog')
test_args.append('blog')
with_scarlet_blog = True
except ImportError:
with_scarlet_blog = False
elif 'blog' in test_args:
with_scarlet_blog = True
setup_test_environment(settings_dict, with_scarlet_blog=with_scarlet_blog)
django.setup()
from django.test.utils import get_runner
def run_tests(test_args, verbosity, interactive):
runner = get_runner(settings)()
return runner.run_tests(test_args)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--settings", default='')
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args()
runtests(args.settings, args.args) | en | 0.794017 | #!/usr/bin/python Specific settings for testing Build a test environment and a test_runner specifically for scarlet testing allows a settings overide file and runs scarlet blog tests if that module is present in the environment | 1.847711 | 2 |
simtbx/nanoBragg/tst_multisource_background.py | dperl-sol/cctbx_project | 155 | 6620418 | from __future__ import absolute_import, division, print_function
from simtbx.nanoBragg import nanoBragg, nanoBragg_beam
from dials.array_family import flex
import numpy as np
"""Purpose of the test: compare nanoBragg background two ways:
1) single channel
2) multiple channels
Overall photon fluence is the same in both simulations.
Results will be nearly identical if the multiple channel bandpass is small,
and if the spectrum is even (tophat), not irregular (random).
"""
water = flex.vec2_double([(0,2.57),(0.0365,2.58),(0.07,2.8),(0.12,5),(0.162,8),(0.18,7.32),(0.2,6.75),(0.216,6.75),(0.236,6.5),(0.28,4.5),(0.3,4.3),(0.345,4.36),(0.436,3.77),(0.5,3.17)])
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
class run_background_simulation:
def __init__(self):
self.SIM = nanoBragg()
self.SIM.progress_meter = False
self.SIM.Fbg_vs_stol = water
self.SIM.amorphous_sample_thick_mm = 0.1
self.SIM.amorphous_density_gcm3 = 1
self.SIM.amorphous_molecular_weight_Da = 18
self.total_flux = self.SIM.flux = 1e12
self.verbose_beams = False
def make_multichannel_beam_simulation(self,
n_chan=5, wave_interval=(0.998, 1.002), spectrum='tophat'):
assert spectrum in ['tophat','random','gaussian']
beam = nanoBragg_beam.NBbeam()
waves = np.linspace(wave_interval[0], wave_interval[1], n_chan)
if spectrum=='tophat': fluences = np.ones(n_chan)
elif spectrum=='random': fluences = np.random.random(n_chan)
else: mu=(n_chan-1)/2.; sig=(n_chan-1)/6.; fluences = np.array([
gaussian(i,mu,sig) for i in range(n_chan)])
fluences /= fluences.sum() # sum of values is 1.
fluences *= self.total_flux # sum of values is SIM.flux
assert np.allclose(fluences.sum(), self.total_flux)
beam.spectrum = list(zip(waves, fluences))
return beam
def set_beam(self,beam):
self.SIM.verbose= 10 if self.verbose_beams else 0
self.SIM.xray_beams = beam.xray_beams
self.SIM.verbose=0
if beam._undo_nanoBragg_norm_by_nbeams:
assert np.allclose(self.SIM.flux, self.total_flux / len(beam.xray_beams))
else:
assert np.allclose(self.SIM.flux, self.total_flux)
def cpu_background(self,override_source=2):
self.SIM.raw_pixels *= 0
self.SIM.add_background()
self.bg_multi = self.SIM.raw_pixels.as_numpy_array()
self.SIM.raw_pixels *= 0
self.SIM.add_background(oversample=1, override_source=override_source)
self.bg_single = self.SIM.raw_pixels.as_numpy_array()
def validate(multi,single): # range of sources or single source
mean_single = single.mean()
mean_multi = multi.mean()
print("single source mean: %1.5g" % mean_single)
print("multi source mean: %1.5g" % mean_multi)
if np.allclose(mean_single, mean_multi): return True
else:
frac = mean_multi / mean_multi
print("Means are off by a factor of %.6f" % frac)
return False
def plot_one_and_multi(multi,single):
from matplotlib import pyplot as plt
fig,ax = plt.subplots(1,3)
scale = multi.max()
im = ax[0].imshow(multi, vmin=-scale, vmax=scale); ax[0].set_title("All sources")
ax[1].imshow(single, vmin=-scale, vmax=scale); ax[1].set_title("Single source")
ax[2].imshow(multi-single, vmin=-scale, vmax=scale); ax[2].set_title("Difference")
fig.subplots_adjust(right=0.88)
cbar = fig.add_axes([0.90,0.2,0.04,0.6]) # left, bottom, width, height
fig.colorbar(im, cax=cbar)
plt.show()
if __name__=="__main__":
import sys
run1 = run_background_simulation()
nbeam_norm_check = [] # all test cases should give approx equal background as flux is constant
print("test with thin bandpass and tophat spectrum")
beam = run1.make_multichannel_beam_simulation(n_chan=5)
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert validate(run1.bg_multi, run1.bg_single)
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with thin bandpass and tophat spectrum, more channels -- should fail")
beam = run1.make_multichannel_beam_simulation(n_chan=10)
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert not validate(run1.bg_multi, run1.bg_single) # fail since single-source isn't central
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with wider bandpass and tophat spectrum -- should fail")
beam = run1.make_multichannel_beam_simulation(wave_interval=(0.98, 1.02))
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert not validate(run1.bg_multi, run1.bg_single)
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with thin bandpass and gaussian spectrum -- it works")
beam = run1.make_multichannel_beam_simulation(n_chan=15, spectrum='gaussian')
run1.set_beam(beam)
run1.cpu_background(override_source=7)
nbeam_norm_check.append(run1.bg_multi.mean())
assert validate(run1.bg_multi, run1.bg_single)
print("compare mean background between tests: should be approx equal",nbeam_norm_check)
assert np.allclose(nbeam_norm_check, nbeam_norm_check[0], atol=1.0)
print("OK")
| from __future__ import absolute_import, division, print_function
from simtbx.nanoBragg import nanoBragg, nanoBragg_beam
from dials.array_family import flex
import numpy as np
"""Purpose of the test: compare nanoBragg background two ways:
1) single channel
2) multiple channels
Overall photon fluence is the same in both simulations.
Results will be nearly identical if the multiple channel bandpass is small,
and if the spectrum is even (tophat), not irregular (random).
"""
water = flex.vec2_double([(0,2.57),(0.0365,2.58),(0.07,2.8),(0.12,5),(0.162,8),(0.18,7.32),(0.2,6.75),(0.216,6.75),(0.236,6.5),(0.28,4.5),(0.3,4.3),(0.345,4.36),(0.436,3.77),(0.5,3.17)])
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
class run_background_simulation:
def __init__(self):
self.SIM = nanoBragg()
self.SIM.progress_meter = False
self.SIM.Fbg_vs_stol = water
self.SIM.amorphous_sample_thick_mm = 0.1
self.SIM.amorphous_density_gcm3 = 1
self.SIM.amorphous_molecular_weight_Da = 18
self.total_flux = self.SIM.flux = 1e12
self.verbose_beams = False
def make_multichannel_beam_simulation(self,
n_chan=5, wave_interval=(0.998, 1.002), spectrum='tophat'):
assert spectrum in ['tophat','random','gaussian']
beam = nanoBragg_beam.NBbeam()
waves = np.linspace(wave_interval[0], wave_interval[1], n_chan)
if spectrum=='tophat': fluences = np.ones(n_chan)
elif spectrum=='random': fluences = np.random.random(n_chan)
else: mu=(n_chan-1)/2.; sig=(n_chan-1)/6.; fluences = np.array([
gaussian(i,mu,sig) for i in range(n_chan)])
fluences /= fluences.sum() # sum of values is 1.
fluences *= self.total_flux # sum of values is SIM.flux
assert np.allclose(fluences.sum(), self.total_flux)
beam.spectrum = list(zip(waves, fluences))
return beam
def set_beam(self,beam):
self.SIM.verbose= 10 if self.verbose_beams else 0
self.SIM.xray_beams = beam.xray_beams
self.SIM.verbose=0
if beam._undo_nanoBragg_norm_by_nbeams:
assert np.allclose(self.SIM.flux, self.total_flux / len(beam.xray_beams))
else:
assert np.allclose(self.SIM.flux, self.total_flux)
def cpu_background(self,override_source=2):
self.SIM.raw_pixels *= 0
self.SIM.add_background()
self.bg_multi = self.SIM.raw_pixels.as_numpy_array()
self.SIM.raw_pixels *= 0
self.SIM.add_background(oversample=1, override_source=override_source)
self.bg_single = self.SIM.raw_pixels.as_numpy_array()
def validate(multi,single): # range of sources or single source
mean_single = single.mean()
mean_multi = multi.mean()
print("single source mean: %1.5g" % mean_single)
print("multi source mean: %1.5g" % mean_multi)
if np.allclose(mean_single, mean_multi): return True
else:
frac = mean_multi / mean_multi
print("Means are off by a factor of %.6f" % frac)
return False
def plot_one_and_multi(multi,single):
from matplotlib import pyplot as plt
fig,ax = plt.subplots(1,3)
scale = multi.max()
im = ax[0].imshow(multi, vmin=-scale, vmax=scale); ax[0].set_title("All sources")
ax[1].imshow(single, vmin=-scale, vmax=scale); ax[1].set_title("Single source")
ax[2].imshow(multi-single, vmin=-scale, vmax=scale); ax[2].set_title("Difference")
fig.subplots_adjust(right=0.88)
cbar = fig.add_axes([0.90,0.2,0.04,0.6]) # left, bottom, width, height
fig.colorbar(im, cax=cbar)
plt.show()
if __name__=="__main__":
import sys
run1 = run_background_simulation()
nbeam_norm_check = [] # all test cases should give approx equal background as flux is constant
print("test with thin bandpass and tophat spectrum")
beam = run1.make_multichannel_beam_simulation(n_chan=5)
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert validate(run1.bg_multi, run1.bg_single)
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with thin bandpass and tophat spectrum, more channels -- should fail")
beam = run1.make_multichannel_beam_simulation(n_chan=10)
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert not validate(run1.bg_multi, run1.bg_single) # fail since single-source isn't central
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with wider bandpass and tophat spectrum -- should fail")
beam = run1.make_multichannel_beam_simulation(wave_interval=(0.98, 1.02))
run1.set_beam(beam)
run1.cpu_background()
nbeam_norm_check.append(run1.bg_multi.mean())
assert not validate(run1.bg_multi, run1.bg_single)
if "plot" in sys.argv: plot_one_and_multi(run1.bg_multi, run1.bg_single)
print("test with thin bandpass and gaussian spectrum -- it works")
beam = run1.make_multichannel_beam_simulation(n_chan=15, spectrum='gaussian')
run1.set_beam(beam)
run1.cpu_background(override_source=7)
nbeam_norm_check.append(run1.bg_multi.mean())
assert validate(run1.bg_multi, run1.bg_single)
print("compare mean background between tests: should be approx equal",nbeam_norm_check)
assert np.allclose(nbeam_norm_check, nbeam_norm_check[0], atol=1.0)
print("OK")
| en | 0.885228 | Purpose of the test: compare nanoBragg background two ways: 1) single channel 2) multiple channels Overall photon fluence is the same in both simulations. Results will be nearly identical if the multiple channel bandpass is small, and if the spectrum is even (tophat), not irregular (random). # sum of values is 1. # sum of values is SIM.flux # range of sources or single source # left, bottom, width, height # all test cases should give approx equal background as flux is constant # fail since single-source isn't central | 2.205338 | 2 |
migrations/versions/0048.py | NewAcropolis/api | 1 | 6620419 | <filename>migrations/versions/0048.py
"""empty message
Revision ID: 0048 add book_to_order
Revises: 0047 add smtp
Create Date: 2020-11-28 00:20:17.353955
"""
# revision identifiers, used by Alembic.
revision = '0048 add book_to_order'
down_revision = '0047 add smtp'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('book_to_order',
sa.Column('book_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('order_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('quantity', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['book_id'], ['books.id'], ),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),
sa.PrimaryKeyConstraint('book_id', 'order_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('book_to_order')
# ### end Alembic commands ###
| <filename>migrations/versions/0048.py
"""empty message
Revision ID: 0048 add book_to_order
Revises: 0047 add smtp
Create Date: 2020-11-28 00:20:17.353955
"""
# revision identifiers, used by Alembic.
revision = '0048 add book_to_order'
down_revision = '0047 add smtp'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('book_to_order',
sa.Column('book_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('order_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('quantity', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['book_id'], ['books.id'], ),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),
sa.PrimaryKeyConstraint('book_id', 'order_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('book_to_order')
# ### end Alembic commands ###
| en | 0.468547 | empty message Revision ID: 0048 add book_to_order Revises: 0047 add smtp Create Date: 2020-11-28 00:20:17.353955 # revision identifiers, used by Alembic. # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### | 1.659171 | 2 |
tests/test_main.py | he7d3r/bistek2gnucash | 0 | 6620420 | <gh_stars>0
import datetime
import pandas as pd
from pandas.testing import assert_frame_equal
from src.main import (append_delivery_fee, clean_dataframe, extract_date,
extract_delivery_fee, extract_total, get_df_from_tuples,
get_gnucash_dataframe, get_item_tuples, get_text,
parse_float)
def get_one_item_text():
return ('Antes\nPrimeiro Item\n\n'
'SKU: 1234567\n'
' 3 R$4.242,42\nDepois')
def get_one_item_list():
return [('Primeiro Item', '1234567', '3', '4.242,42')]
def get_one_item_dataframe():
return pd.DataFrame({
'description': ['Primeiro Item'],
'code': ['1234567'],
'amount': ['3'],
'value': ['4.242,42']
})
def get_one_item_dataframe_clean():
return pd.DataFrame({
'description': ['Primeiro Item'],
'code': [1234567],
'amount': [3],
'value': [4242.42]
})
def get_many_items_text():
return ('Texto antes\n\n'
'Primeiro Item\n\n'
'SKU: 1231234\n'
' 10 R$0,42\n\n'
'2º produto\n\n'
'SKU: 1233210\n'
' 2 R$24.242,42\n\n'
'Texto depois\n\n'
'Item 3\n\n'
'SKU: 1212121\n'
' 100 R$2.424.242,42\n\n'
'Texto depois\n')
def get_many_items_list():
return [('Primeiro Item', '1231234', '10', '0,42'),
('2º produto', '1233210', '2', '24.242,42'),
('Item 3', '1212121', '100', '2.424.242,42')]
def get_many_items_dataframe():
return pd.DataFrame({
'description': ['Primeiro Item', '2º produto', 'Item 3'],
'code': ['1231234', '1233210', '1212121'],
'amount': ['10', '2', '100'],
'value': ['0,42', '24.242,42', '2.424.242,42']
})
def get_many_items_dataframe_clean():
return pd.DataFrame({
'description': ['Primeiro Item', '2º produto', 'Item 3'],
'code': [1231234, 1233210, 1212121],
'amount': [10, 2, 100],
'value': [0.42, 24242.42, 2424242.42]
})
def get_summary_text():
result = ('Subtotal R$432,10\n'
'Entrega & Manuseio R$8,90\n'
'Total R$441,00')
return result
def test_regex_for_single_item():
sample_text = get_one_item_text()
actual = get_item_tuples(sample_text)
expected = get_one_item_list()
assert actual == expected
def test_regex_for_multiple_items():
sample_text = get_many_items_text()
actual = get_item_tuples(sample_text)
expected = get_many_items_list()
assert actual == expected
def test_get_df_from_tuple():
tuples = get_one_item_list()
actual = get_df_from_tuples(tuples)
expected = get_one_item_dataframe()
assert_frame_equal(actual, expected)
def test_get_df_from_tuples():
tuples = get_many_items_list()
actual = get_df_from_tuples(tuples)
expected = get_many_items_dataframe()
assert_frame_equal(actual, expected)
def test_clean_dataframe_single_item():
df = get_one_item_dataframe()
actual = clean_dataframe(df)
expected = get_one_item_dataframe_clean()
assert_frame_equal(actual, expected)
def test_clean_dataframe_multiple_items():
df = get_many_items_dataframe()
actual = clean_dataframe(df)
expected = get_many_items_dataframe_clean()
assert_frame_equal(actual, expected)
def test_get_text_contains_basic_text():
text = get_text('tests/fake-text.txt')
order_header_text = 'Detalhes do seu pedido'
assert order_header_text in text
table_header_text = 'Itens Quantidade Preço'
assert table_header_text in text
code_prefix_text = 'SKU'
assert code_prefix_text in text
total_text = 'Total'
assert total_text in text
def test_extract_date():
sample_text = 'pedido de nº 123 feito em 1 de fev de 2021 15:16:17 foi'
actual = extract_date(sample_text)
expected = datetime.date(2021, 2, 1)
assert actual == expected
def test_get_gnucash_dataframe():
df = get_many_items_dataframe_clean()
df['date'] = datetime.date(2021, 2, 1)
actual = get_gnucash_dataframe(df, col_names={
'date': 'Date',
'description': 'Memo',
'value': 'Deposit'},
gnucash={'description': 'foo',
'expense': 'bar',
'payment': 'baz',
'currency': 'qux'})
actual_columns = actual.columns.tolist()
expected_columns = ['Date', 'Description', 'Transaction Commodity',
# 'Action',
'Memo', 'Account', 'Deposit',
# 'Reconciled',
'Price']
assert actual_columns == expected_columns
assert not pd.isnull(actual.loc[0, 'Date'])
assert actual.loc[1:, 'Date'].isnull().all()
assert actual.loc[1:, 'Description'].isnull().all()
assert not pd.isnull(actual.loc[0, 'Description'])
assert actual.loc[0, 'Description'] == 'foo'
assert actual.loc[1:, 'Transaction Commodity'].isnull().all()
assert not pd.isnull(actual.loc[0, 'Transaction Commodity'])
assert actual.loc[0, 'Transaction Commodity'] == 'qux'
assert not pd.isnull(actual.loc[len(actual)-1, 'Account'])
assert (actual.loc[0:len(actual)-2, 'Account'] == 'bar').all()
assert actual.loc[len(actual)-1, 'Account'] == 'baz'
assert (actual['Price'] == 1).all()
def test_parse_float():
sample = '1,23'
actual = parse_float(sample)
expected = 1.23
assert actual == expected
sample = '5.432,10'
actual = parse_float(sample)
expected = 5432.10
assert actual == expected
sample = '98.765.432,10'
actual = parse_float(sample)
expected = 98765432.10
assert actual == expected
def test_extract_total():
sample_text = get_summary_text()
actual = extract_total(sample_text)
expected = 441.00
assert actual == expected
def test_extract_delivery_fee():
sample_text = get_summary_text()
actual = extract_delivery_fee(sample_text)
expected = 8.90
assert actual == expected
def test_append_delivery_fee():
sample_df = get_many_items_dataframe_clean()
updated_df = append_delivery_fee(sample_df, 12.34)
actual_len = len(updated_df)
expected_len = len(sample_df) + 1
assert actual_len == expected_len
assert updated_df['value'].values[-1] == 12.34
| import datetime
import pandas as pd
from pandas.testing import assert_frame_equal
from src.main import (append_delivery_fee, clean_dataframe, extract_date,
extract_delivery_fee, extract_total, get_df_from_tuples,
get_gnucash_dataframe, get_item_tuples, get_text,
parse_float)
def get_one_item_text():
return ('Antes\nPrimeiro Item\n\n'
'SKU: 1234567\n'
' 3 R$4.242,42\nDepois')
def get_one_item_list():
return [('Primeiro Item', '1234567', '3', '4.242,42')]
def get_one_item_dataframe():
return pd.DataFrame({
'description': ['Primeiro Item'],
'code': ['1234567'],
'amount': ['3'],
'value': ['4.242,42']
})
def get_one_item_dataframe_clean():
return pd.DataFrame({
'description': ['Primeiro Item'],
'code': [1234567],
'amount': [3],
'value': [4242.42]
})
def get_many_items_text():
return ('Texto antes\n\n'
'Primeiro Item\n\n'
'SKU: 1231234\n'
' 10 R$0,42\n\n'
'2º produto\n\n'
'SKU: 1233210\n'
' 2 R$24.242,42\n\n'
'Texto depois\n\n'
'Item 3\n\n'
'SKU: 1212121\n'
' 100 R$2.424.242,42\n\n'
'Texto depois\n')
def get_many_items_list():
return [('Primeiro Item', '1231234', '10', '0,42'),
('2º produto', '1233210', '2', '24.242,42'),
('Item 3', '1212121', '100', '2.424.242,42')]
def get_many_items_dataframe():
return pd.DataFrame({
'description': ['Primeiro Item', '2º produto', 'Item 3'],
'code': ['1231234', '1233210', '1212121'],
'amount': ['10', '2', '100'],
'value': ['0,42', '24.242,42', '2.424.242,42']
})
def get_many_items_dataframe_clean():
return pd.DataFrame({
'description': ['Primeiro Item', '2º produto', 'Item 3'],
'code': [1231234, 1233210, 1212121],
'amount': [10, 2, 100],
'value': [0.42, 24242.42, 2424242.42]
})
def get_summary_text():
result = ('Subtotal R$432,10\n'
'Entrega & Manuseio R$8,90\n'
'Total R$441,00')
return result
def test_regex_for_single_item():
sample_text = get_one_item_text()
actual = get_item_tuples(sample_text)
expected = get_one_item_list()
assert actual == expected
def test_regex_for_multiple_items():
sample_text = get_many_items_text()
actual = get_item_tuples(sample_text)
expected = get_many_items_list()
assert actual == expected
def test_get_df_from_tuple():
tuples = get_one_item_list()
actual = get_df_from_tuples(tuples)
expected = get_one_item_dataframe()
assert_frame_equal(actual, expected)
def test_get_df_from_tuples():
tuples = get_many_items_list()
actual = get_df_from_tuples(tuples)
expected = get_many_items_dataframe()
assert_frame_equal(actual, expected)
def test_clean_dataframe_single_item():
df = get_one_item_dataframe()
actual = clean_dataframe(df)
expected = get_one_item_dataframe_clean()
assert_frame_equal(actual, expected)
def test_clean_dataframe_multiple_items():
df = get_many_items_dataframe()
actual = clean_dataframe(df)
expected = get_many_items_dataframe_clean()
assert_frame_equal(actual, expected)
def test_get_text_contains_basic_text():
text = get_text('tests/fake-text.txt')
order_header_text = 'Detalhes do seu pedido'
assert order_header_text in text
table_header_text = 'Itens Quantidade Preço'
assert table_header_text in text
code_prefix_text = 'SKU'
assert code_prefix_text in text
total_text = 'Total'
assert total_text in text
def test_extract_date():
sample_text = 'pedido de nº 123 feito em 1 de fev de 2021 15:16:17 foi'
actual = extract_date(sample_text)
expected = datetime.date(2021, 2, 1)
assert actual == expected
def test_get_gnucash_dataframe():
df = get_many_items_dataframe_clean()
df['date'] = datetime.date(2021, 2, 1)
actual = get_gnucash_dataframe(df, col_names={
'date': 'Date',
'description': 'Memo',
'value': 'Deposit'},
gnucash={'description': 'foo',
'expense': 'bar',
'payment': 'baz',
'currency': 'qux'})
actual_columns = actual.columns.tolist()
expected_columns = ['Date', 'Description', 'Transaction Commodity',
# 'Action',
'Memo', 'Account', 'Deposit',
# 'Reconciled',
'Price']
assert actual_columns == expected_columns
assert not pd.isnull(actual.loc[0, 'Date'])
assert actual.loc[1:, 'Date'].isnull().all()
assert actual.loc[1:, 'Description'].isnull().all()
assert not pd.isnull(actual.loc[0, 'Description'])
assert actual.loc[0, 'Description'] == 'foo'
assert actual.loc[1:, 'Transaction Commodity'].isnull().all()
assert not pd.isnull(actual.loc[0, 'Transaction Commodity'])
assert actual.loc[0, 'Transaction Commodity'] == 'qux'
assert not pd.isnull(actual.loc[len(actual)-1, 'Account'])
assert (actual.loc[0:len(actual)-2, 'Account'] == 'bar').all()
assert actual.loc[len(actual)-1, 'Account'] == 'baz'
assert (actual['Price'] == 1).all()
def test_parse_float():
sample = '1,23'
actual = parse_float(sample)
expected = 1.23
assert actual == expected
sample = '5.432,10'
actual = parse_float(sample)
expected = 5432.10
assert actual == expected
sample = '98.765.432,10'
actual = parse_float(sample)
expected = 98765432.10
assert actual == expected
def test_extract_total():
sample_text = get_summary_text()
actual = extract_total(sample_text)
expected = 441.00
assert actual == expected
def test_extract_delivery_fee():
sample_text = get_summary_text()
actual = extract_delivery_fee(sample_text)
expected = 8.90
assert actual == expected
def test_append_delivery_fee():
sample_df = get_many_items_dataframe_clean()
updated_df = append_delivery_fee(sample_df, 12.34)
actual_len = len(updated_df)
expected_len = len(sample_df) + 1
assert actual_len == expected_len
assert updated_df['value'].values[-1] == 12.34 | es | 0.079742 | # 'Action', # 'Reconciled', | 2.64036 | 3 |
client/forms.py | apiaas/drawer-api | 0 | 6620421 | from __future__ import unicode_literals
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import Client
class ClientCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
class Meta:
model = Client
fields = ("username",)
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
Client._default_manager.get(username=username)
except Client.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
class ClientChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = Client
fields = '__all__'
| from __future__ import unicode_literals
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import Client
class ClientCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
class Meta:
model = Client
fields = ("username",)
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
Client._default_manager.get(username=username)
except Client.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
class ClientChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = Client
fields = '__all__'
| en | 0.831439 | A form that creates a user, with no privileges, from the given username and password. # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. | 2.679273 | 3 |
ThinkGear.py | JephDiel/BCI | 0 | 6620422 | <filename>ThinkGear.py
import serial, math#, pygame
codes = [0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x83 ]
names = ["quality","heartrate","attention","meditation","8bit_raw","eeg_raw","eeg_asic"]
c_len = [1, 1, 1, 1, 1, 3, 25 ]
bands = ["delta","theta","low-alpha","high-alpha","low-beta","high-beta","low-gamma","mid-gamma"]
#convert signed bit/byte array to int
def signed_thing_to_int(b, length):
return b-((b >> (length-1)) & 1)*2**length #return b if first bit is 0, otherwise subtract max value representable with given number of bits and return
'''EEG Device Class'''
class ThinkGear(object):
def __init__(self, port, baudrate=57600):
self.ser = serial.Serial(port, baudrate) #initialize serial communication/connection
self.data = {}
def fetch_data(self):
self.data = {} #reset values
while True:
self.ser.read_until(b"\xAA\xAA") #wait for sync bytes
plength = ord(self.ser.read(1)) #payload length
payload = self.ser.read(plength) #read entire payload of given length
checksum = ~(int(math.fsum([b for b in payload])) & 0xFF) & 0xFF #calculate checksum by doing... checksum-calculation stuff (described in the docs)
if checksum == ord(self.ser.read(1)): break #checksums match, move on
else: print("ERROR: Checksum mismatch!") #checksum mismatch, repeat
i = 0
while i < len(payload)-1:
code = payload[i]
if code in codes: #check if current byte is a supported code
c = codes.index(code) #find corresponding index in the three code-related lists above
'''old code which I prefer (because it's technically one line) (sadly without a way to add comments)
self.data[names[c]] = payload[i+1] if c < 5 \
else signed_thing_to_int(payload[i+2] << 8 | payload[i+3], 16) if c == 5 \
else dict(zip(bands, [payload[b] << 16 | payload[b+1] << 8 | payload[b+2] for b in range(i+1, i+25, 3)]))
'''
if c < 5: #all single-byte codes (quality, heartrate, attention, meditation, 8bit_raw)
self.data[names[c]] = payload[i+1]
elif c == 5: #eeg_raw (fun fact: the first byte after the code is completely useless)
self.data[names[c]] = signed_thing_to_int(payload[i+2] << 8 | payload[i+3], 16)
elif c == 6: #eeg_asic
self.data[names[c]] = dict(zip(bands, [payload[b] << 16 | payload[b+1] << 8 | payload[b+2] for b in range(i+1, i+25, 3)]))
i += c_len[c] #add code-specific number of bytes to i
i += 1 #add 1 each time to avoid getting stuck on unused bytes
def close(self):
self.ser.close()
# print("Connecting Thinkgear")
# eeg_device = ThinkGear("COM5", 9600)
# print ("Connected")
# '''Visualization Stuff'''
# vis_points = 640 #number of eeg readings to be plotted at once
# size = (640, 480) #window size in pixels
# x_vals = [int(size[0]*(x+0.5)/vis_points) for x in range(vis_points)]
# y_vals = [int(size[1]/2) for x in range(vis_points)]
# surface = pygame.display.set_mode(size) #initialize window
# pygame.display.set_caption("EEG Visualizer") #...
# raw_eeg_range = 8192 #technically 2*32768=65536 (2^16), but for some reason it doesn't use the full available range
# clock = pygame.time.Clock()
# while True:
# try:
# clock.tick(30)
# print("Fetching")
# eeg_device.fetch_data()
# print("Fetched")
# if len(eeg_device.data) == 1: y_vals = y_vals[1:]+[int(size[1]/2-size[1]*eeg_device.data["eeg_raw"]/raw_eeg_range)]
# surface.fill((0,0,0)) #Do I really need to explain this?
# points = list(zip(x_vals, y_vals)) #zip x and y values to pairs (list(zip([x0,x1,...xN], [y0,y1,...,yN])) = [(x0,y0),(x1,y1),...,(xN,yN)])
# pygame.draw.lines(surface, (255,255,255), False, points) #draw continuous line segments through points
# pygame.display.flip() #display changes
# except KeyboardInterrupt: #I don't even know if this works, heck. <insert wrinkly Pikachu>
# pygame.quit()
| <filename>ThinkGear.py
import serial, math#, pygame
codes = [0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x83 ]
names = ["quality","heartrate","attention","meditation","8bit_raw","eeg_raw","eeg_asic"]
c_len = [1, 1, 1, 1, 1, 3, 25 ]
bands = ["delta","theta","low-alpha","high-alpha","low-beta","high-beta","low-gamma","mid-gamma"]
#convert signed bit/byte array to int
def signed_thing_to_int(b, length):
return b-((b >> (length-1)) & 1)*2**length #return b if first bit is 0, otherwise subtract max value representable with given number of bits and return
'''EEG Device Class'''
class ThinkGear(object):
def __init__(self, port, baudrate=57600):
self.ser = serial.Serial(port, baudrate) #initialize serial communication/connection
self.data = {}
def fetch_data(self):
self.data = {} #reset values
while True:
self.ser.read_until(b"\xAA\xAA") #wait for sync bytes
plength = ord(self.ser.read(1)) #payload length
payload = self.ser.read(plength) #read entire payload of given length
checksum = ~(int(math.fsum([b for b in payload])) & 0xFF) & 0xFF #calculate checksum by doing... checksum-calculation stuff (described in the docs)
if checksum == ord(self.ser.read(1)): break #checksums match, move on
else: print("ERROR: Checksum mismatch!") #checksum mismatch, repeat
i = 0
while i < len(payload)-1:
code = payload[i]
if code in codes: #check if current byte is a supported code
c = codes.index(code) #find corresponding index in the three code-related lists above
'''old code which I prefer (because it's technically one line) (sadly without a way to add comments)
self.data[names[c]] = payload[i+1] if c < 5 \
else signed_thing_to_int(payload[i+2] << 8 | payload[i+3], 16) if c == 5 \
else dict(zip(bands, [payload[b] << 16 | payload[b+1] << 8 | payload[b+2] for b in range(i+1, i+25, 3)]))
'''
if c < 5: #all single-byte codes (quality, heartrate, attention, meditation, 8bit_raw)
self.data[names[c]] = payload[i+1]
elif c == 5: #eeg_raw (fun fact: the first byte after the code is completely useless)
self.data[names[c]] = signed_thing_to_int(payload[i+2] << 8 | payload[i+3], 16)
elif c == 6: #eeg_asic
self.data[names[c]] = dict(zip(bands, [payload[b] << 16 | payload[b+1] << 8 | payload[b+2] for b in range(i+1, i+25, 3)]))
i += c_len[c] #add code-specific number of bytes to i
i += 1 #add 1 each time to avoid getting stuck on unused bytes
def close(self):
self.ser.close()
# print("Connecting Thinkgear")
# eeg_device = ThinkGear("COM5", 9600)
# print ("Connected")
# '''Visualization Stuff'''
# vis_points = 640 #number of eeg readings to be plotted at once
# size = (640, 480) #window size in pixels
# x_vals = [int(size[0]*(x+0.5)/vis_points) for x in range(vis_points)]
# y_vals = [int(size[1]/2) for x in range(vis_points)]
# surface = pygame.display.set_mode(size) #initialize window
# pygame.display.set_caption("EEG Visualizer") #...
# raw_eeg_range = 8192 #technically 2*32768=65536 (2^16), but for some reason it doesn't use the full available range
# clock = pygame.time.Clock()
# while True:
# try:
# clock.tick(30)
# print("Fetching")
# eeg_device.fetch_data()
# print("Fetched")
# if len(eeg_device.data) == 1: y_vals = y_vals[1:]+[int(size[1]/2-size[1]*eeg_device.data["eeg_raw"]/raw_eeg_range)]
# surface.fill((0,0,0)) #Do I really need to explain this?
# points = list(zip(x_vals, y_vals)) #zip x and y values to pairs (list(zip([x0,x1,...xN], [y0,y1,...,yN])) = [(x0,y0),(x1,y1),...,(xN,yN)])
# pygame.draw.lines(surface, (255,255,255), False, points) #draw continuous line segments through points
# pygame.display.flip() #display changes
# except KeyboardInterrupt: #I don't even know if this works, heck. <insert wrinkly Pikachu>
# pygame.quit()
| en | 0.617619 | #, pygame #convert signed bit/byte array to int #return b if first bit is 0, otherwise subtract max value representable with given number of bits and return EEG Device Class #initialize serial communication/connection #reset values #wait for sync bytes #payload length #read entire payload of given length #calculate checksum by doing... checksum-calculation stuff (described in the docs) #checksums match, move on #checksum mismatch, repeat #check if current byte is a supported code #find corresponding index in the three code-related lists above old code which I prefer (because it's technically one line) (sadly without a way to add comments) self.data[names[c]] = payload[i+1] if c < 5 \ else signed_thing_to_int(payload[i+2] << 8 | payload[i+3], 16) if c == 5 \ else dict(zip(bands, [payload[b] << 16 | payload[b+1] << 8 | payload[b+2] for b in range(i+1, i+25, 3)])) #all single-byte codes (quality, heartrate, attention, meditation, 8bit_raw) #eeg_raw (fun fact: the first byte after the code is completely useless) #eeg_asic #add code-specific number of bytes to i #add 1 each time to avoid getting stuck on unused bytes # print("Connecting Thinkgear") # eeg_device = ThinkGear("COM5", 9600) # print ("Connected") # '''Visualization Stuff''' # vis_points = 640 #number of eeg readings to be plotted at once # size = (640, 480) #window size in pixels # x_vals = [int(size[0]*(x+0.5)/vis_points) for x in range(vis_points)] # y_vals = [int(size[1]/2) for x in range(vis_points)] # surface = pygame.display.set_mode(size) #initialize window # pygame.display.set_caption("EEG Visualizer") #... # raw_eeg_range = 8192 #technically 2*32768=65536 (2^16), but for some reason it doesn't use the full available range # clock = pygame.time.Clock() # while True: # try: # clock.tick(30) # print("Fetching") # eeg_device.fetch_data() # print("Fetched") # if len(eeg_device.data) == 1: y_vals = y_vals[1:]+[int(size[1]/2-size[1]*eeg_device.data["eeg_raw"]/raw_eeg_range)] # surface.fill((0,0,0)) #Do I really need to explain this? # points = list(zip(x_vals, y_vals)) #zip x and y values to pairs (list(zip([x0,x1,...xN], [y0,y1,...,yN])) = [(x0,y0),(x1,y1),...,(xN,yN)]) # pygame.draw.lines(surface, (255,255,255), False, points) #draw continuous line segments through points # pygame.display.flip() #display changes # except KeyboardInterrupt: #I don't even know if this works, heck. <insert wrinkly Pikachu> # pygame.quit() | 3.150813 | 3 |
airflow/download_cdc_loss_state_weekly.py | darrida/covid-19-data-aggergation | 0 | 6620423 | import json
import pathlib
import pprint
import csv
import pandas
import airflow
import requests
from airflow import DAG
from airflow.operators.bash_operator import BashOperator #bash_operator
from airflow.operators.python_operator import PythonOperator #python_operator
dag = DAG(
dag_id="dl_cdc_morality_full_set",
start_date=airflow.utils.dates.days_ago(14),
schedule_interval="@daily")
def _api_death_all_data_json(**context):
uri = context['uri']
filename = context['filename']
results = requests.get(uri)
data = results.json()
with open(filename, 'w') as outfile:
json.dump(data, outfile)
get_cdc_mortality_weekly = PythonOperator(
task_id="dl_cdc_death_wk_json",
python_callable=_api_death_all_data_json,
op_kwargs={
"uri": "https://data.cdc.gov/resource/muzy-jte6.json",
"filename": '/tmp/cdc_api_testing/{{ execution_date.year }}{{ execution_date.month }}' \
'{{ execution_date.day }}{{ execution_date.hour }}.cdc_weekly_mortality.json'
},
provide_context=True,
dag=dag,
)
def _json_to_csv(**context):
json_input = context['filename']
output = context['output_name']
df = pandas.read_json(json_input)
df.to_csv(output)
json_to_csv = PythonOperator(
task_id="json_to_csv",
python_callable=_json_to_csv,
op_kwargs={
"filename": '/tmp/cdc_api_testing/{{ execution_date.year }}{{ execution_date.month }}' \
'{{ execution_date.day }}{{ execution_date.hour }}' \
'.cdc_weekly_mortality.json',
"output_name": "/tmp/cdc_api_testing/death_weekly_by_state.csv"
},
provide_context=True,
dag=dag
)
get_cdc_mortality_weekly >> json_to_csv | import json
import pathlib
import pprint
import csv
import pandas
import airflow
import requests
from airflow import DAG
from airflow.operators.bash_operator import BashOperator #bash_operator
from airflow.operators.python_operator import PythonOperator #python_operator
dag = DAG(
dag_id="dl_cdc_morality_full_set",
start_date=airflow.utils.dates.days_ago(14),
schedule_interval="@daily")
def _api_death_all_data_json(**context):
uri = context['uri']
filename = context['filename']
results = requests.get(uri)
data = results.json()
with open(filename, 'w') as outfile:
json.dump(data, outfile)
get_cdc_mortality_weekly = PythonOperator(
task_id="dl_cdc_death_wk_json",
python_callable=_api_death_all_data_json,
op_kwargs={
"uri": "https://data.cdc.gov/resource/muzy-jte6.json",
"filename": '/tmp/cdc_api_testing/{{ execution_date.year }}{{ execution_date.month }}' \
'{{ execution_date.day }}{{ execution_date.hour }}.cdc_weekly_mortality.json'
},
provide_context=True,
dag=dag,
)
def _json_to_csv(**context):
json_input = context['filename']
output = context['output_name']
df = pandas.read_json(json_input)
df.to_csv(output)
json_to_csv = PythonOperator(
task_id="json_to_csv",
python_callable=_json_to_csv,
op_kwargs={
"filename": '/tmp/cdc_api_testing/{{ execution_date.year }}{{ execution_date.month }}' \
'{{ execution_date.day }}{{ execution_date.hour }}' \
'.cdc_weekly_mortality.json',
"output_name": "/tmp/cdc_api_testing/death_weekly_by_state.csv"
},
provide_context=True,
dag=dag
)
get_cdc_mortality_weekly >> json_to_csv | en | 0.253615 | #bash_operator #python_operator | 2.809799 | 3 |
src/data/enzymes.py | petergroth/enzyme_graph_classification | 1 | 6620424 | import numpy as np
import pytorch_lightning as pl
import torch
import torch_geometric.transforms as transforms
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from src import project_dir
class EnzymesDataModule(pl.LightningDataModule):
def __init__(
self,
data_dir="/data/",
batch_size=64,
num_workers=0,
splits=[0.7, 0.15, 0.15],
seed=42,
):
super(EnzymesDataModule, self).__init__()
self.data_dir = project_dir + data_dir
self.batch_size = batch_size
self.num_workers = num_workers
self.splits = splits
self.seed = seed
self.transform = transforms.Compose(
[
transforms.NormalizeFeatures(),
]
)
# Number of graphs, classes and features
self.num_graphs = 600
self.num_classes = 6
self.num_features = 21
def prepare_data(self):
# Download data
TUDataset(
root=self.data_dir,
name="ENZYMES",
use_node_attr=True,
use_edge_attr=True,
pre_transform=self.transform,
)
def setup(self, stage=None):
initial_seed = torch.initial_seed()
torch.manual_seed(self.seed)
dataset = TUDataset(
root=self.data_dir,
name="ENZYMES",
use_node_attr=True,
use_edge_attr=True,
pre_transform=self.transform,
).shuffle()
split_idx = np.cumsum(
[int(len(dataset) * prop) for prop in self.splits])
self.data_train = dataset[: split_idx[0]]
self.data_val = dataset[split_idx[0]: split_idx[1]]
self.data_test = dataset[split_idx[1]:]
torch.manual_seed(initial_seed)
def train_dataloader(self):
return DataLoader(
self.data_train,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=True,
pin_memory=True,
)
def val_dataloader(self):
return DataLoader(
self.data_val,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=False,
pin_memory=True,
)
def test_dataloader(self):
return DataLoader(
self.data_test,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=False,
pin_memory=True,
)
@staticmethod
def add_model_specific_args(parent_parser):
parser = parent_parser.add_argument_group("EnzymesDataModule")
parser.add_argument(
"--data_dir", default=project_dir + "/data/", type=str)
parser.add_argument("--batch_size", default=64, type=int)
parser.add_argument("--num_workers", default=0, type=int)
parser.add_argument(
"--splits", default=[0.7, 0.15, 0.15], nargs=3, type=float)
parser.add_argument("--seed", default=42, type=int)
return parent_parser
@staticmethod
def from_argparse_args(namespace):
ns_dict = vars(namespace)
args = {
"data_dir": ns_dict.get("data_dir", project_dir + "/data/"),
"batch_size": ns_dict.get("batch_size", 64),
"num_workers": ns_dict.get("num_workers", 0),
"splits": ns_dict.get("splits", [0.7, 0.15, 0.15]),
"seed": ns_dict.get("seed", 42),
}
return args
if __name__ == "__main__":
dm = EnzymesDataModule(data_dir=project_dir + "/data/")
dm.prepare_data()
| import numpy as np
import pytorch_lightning as pl
import torch
import torch_geometric.transforms as transforms
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from src import project_dir
class EnzymesDataModule(pl.LightningDataModule):
def __init__(
self,
data_dir="/data/",
batch_size=64,
num_workers=0,
splits=[0.7, 0.15, 0.15],
seed=42,
):
super(EnzymesDataModule, self).__init__()
self.data_dir = project_dir + data_dir
self.batch_size = batch_size
self.num_workers = num_workers
self.splits = splits
self.seed = seed
self.transform = transforms.Compose(
[
transforms.NormalizeFeatures(),
]
)
# Number of graphs, classes and features
self.num_graphs = 600
self.num_classes = 6
self.num_features = 21
def prepare_data(self):
# Download data
TUDataset(
root=self.data_dir,
name="ENZYMES",
use_node_attr=True,
use_edge_attr=True,
pre_transform=self.transform,
)
def setup(self, stage=None):
initial_seed = torch.initial_seed()
torch.manual_seed(self.seed)
dataset = TUDataset(
root=self.data_dir,
name="ENZYMES",
use_node_attr=True,
use_edge_attr=True,
pre_transform=self.transform,
).shuffle()
split_idx = np.cumsum(
[int(len(dataset) * prop) for prop in self.splits])
self.data_train = dataset[: split_idx[0]]
self.data_val = dataset[split_idx[0]: split_idx[1]]
self.data_test = dataset[split_idx[1]:]
torch.manual_seed(initial_seed)
def train_dataloader(self):
return DataLoader(
self.data_train,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=True,
pin_memory=True,
)
def val_dataloader(self):
return DataLoader(
self.data_val,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=False,
pin_memory=True,
)
def test_dataloader(self):
return DataLoader(
self.data_test,
batch_size=self.batch_size,
num_workers=self.num_workers,
shuffle=False,
pin_memory=True,
)
@staticmethod
def add_model_specific_args(parent_parser):
parser = parent_parser.add_argument_group("EnzymesDataModule")
parser.add_argument(
"--data_dir", default=project_dir + "/data/", type=str)
parser.add_argument("--batch_size", default=64, type=int)
parser.add_argument("--num_workers", default=0, type=int)
parser.add_argument(
"--splits", default=[0.7, 0.15, 0.15], nargs=3, type=float)
parser.add_argument("--seed", default=42, type=int)
return parent_parser
@staticmethod
def from_argparse_args(namespace):
ns_dict = vars(namespace)
args = {
"data_dir": ns_dict.get("data_dir", project_dir + "/data/"),
"batch_size": ns_dict.get("batch_size", 64),
"num_workers": ns_dict.get("num_workers", 0),
"splits": ns_dict.get("splits", [0.7, 0.15, 0.15]),
"seed": ns_dict.get("seed", 42),
}
return args
if __name__ == "__main__":
dm = EnzymesDataModule(data_dir=project_dir + "/data/")
dm.prepare_data()
| en | 0.867038 | # Number of graphs, classes and features # Download data | 2.581893 | 3 |
python/trailing_bytes.py | SnoopJeDi/playground | 0 | 6620425 | <gh_stars>0
"""
Based on a question in Freenode #python on Dec 19, 2019 about how to read
a file 4 bytes at a time *except* a tail that may be up to 4 bytes long
"""
from io import BytesIO
from collections import deque
f = BytesIO(b"abcdefgh")
def chunks(s, n=4):
chunk = s.read(n)
while len(chunk):
yield chunk
chunk = s.read(n)
buf = deque(f.read(4))
for nibble in chunks(f):
buf.extend(nibble)
if 4 < len(buf) <= 8:
yummy = bytes(buf.popleft() for _ in range(4))
print(f"yummy bit: {yummy}")
print(f"not yummy tail: {bytes(buf)}")
| """
Based on a question in Freenode #python on Dec 19, 2019 about how to read
a file 4 bytes at a time *except* a tail that may be up to 4 bytes long
"""
from io import BytesIO
from collections import deque
f = BytesIO(b"abcdefgh")
def chunks(s, n=4):
chunk = s.read(n)
while len(chunk):
yield chunk
chunk = s.read(n)
buf = deque(f.read(4))
for nibble in chunks(f):
buf.extend(nibble)
if 4 < len(buf) <= 8:
yummy = bytes(buf.popleft() for _ in range(4))
print(f"yummy bit: {yummy}")
print(f"not yummy tail: {bytes(buf)}") | en | 0.936801 | Based on a question in Freenode #python on Dec 19, 2019 about how to read a file 4 bytes at a time *except* a tail that may be up to 4 bytes long | 3.070442 | 3 |
config/presets/Modes/Python/S - Aquarium/main.py | The-XOR/EYESY_OS | 18 | 6620426 | import os
import pygame
import random
speedList = [random.randrange(-1,1)+.1 for i in range(0,20)]
yList = [random.randrange(-50,770) for i in range(0,20)]
widthList = [random.randrange(20,200) for i in range(0,20)]
countList = [i for i in range(0,20)]
xden = 1
yden = 1
trigger = False
def setup(screen, etc) :
pass
def draw(screen, etc) :
global trigger, yList, widthList, countList, speedList, xden, yden
etc.color_picker_bg(etc.knob5)
color = etc.color_picker(etc.knob4) #on knob4
widthmax = int((200*etc.xres)/1280)
if yden != (int(etc.knob1 * 19) + 1) :
yden = (int(etc.knob1 * 19) + 1)
speedList = [random.randrange(-2,2)+.1 for i in range(0,20)]
yList = [random.randrange(-50,(etc.yres+50)) for i in range(0,20)]
widthList = [random.randrange(20,widthmax) for i in range(0,20)]
if xden != (int(etc.knob2 * 19) + 1) :
xden = (int(etc.knob2 * 19) + 1)
speedList = [random.randrange(-2,2)+.1 for i in range(0,20)]
yList = [random.randrange(-50,(etc.yres+50)) for i in range(0,20)]
widthList = [random.randrange(20,widthmax) for i in range(0,20)]
for i in range (0,yden) :
y0 = yList[i]
ymod = ((500*720)/etc.yres)
for j in range (0,xden) :
width = widthList[i]
y1 = y0 + (etc.audio_in[j+i] / ymod)
countList[i] = countList[i] + speedList[i]
modSpeed = countList[i]%(etc.xres+width*2)
x = (j * (width/5)) + (modSpeed-width)
pygame.draw.line(screen, color, [x, y1], [x, y0], int(etc.knob3*((100*etc.xres)/1280)+1))
if etc.audio_trig or etc.midi_note_new :
trigger = True
trigger = False
| import os
import pygame
import random
speedList = [random.randrange(-1,1)+.1 for i in range(0,20)]
yList = [random.randrange(-50,770) for i in range(0,20)]
widthList = [random.randrange(20,200) for i in range(0,20)]
countList = [i for i in range(0,20)]
xden = 1
yden = 1
trigger = False
def setup(screen, etc) :
pass
def draw(screen, etc) :
global trigger, yList, widthList, countList, speedList, xden, yden
etc.color_picker_bg(etc.knob5)
color = etc.color_picker(etc.knob4) #on knob4
widthmax = int((200*etc.xres)/1280)
if yden != (int(etc.knob1 * 19) + 1) :
yden = (int(etc.knob1 * 19) + 1)
speedList = [random.randrange(-2,2)+.1 for i in range(0,20)]
yList = [random.randrange(-50,(etc.yres+50)) for i in range(0,20)]
widthList = [random.randrange(20,widthmax) for i in range(0,20)]
if xden != (int(etc.knob2 * 19) + 1) :
xden = (int(etc.knob2 * 19) + 1)
speedList = [random.randrange(-2,2)+.1 for i in range(0,20)]
yList = [random.randrange(-50,(etc.yres+50)) for i in range(0,20)]
widthList = [random.randrange(20,widthmax) for i in range(0,20)]
for i in range (0,yden) :
y0 = yList[i]
ymod = ((500*720)/etc.yres)
for j in range (0,xden) :
width = widthList[i]
y1 = y0 + (etc.audio_in[j+i] / ymod)
countList[i] = countList[i] + speedList[i]
modSpeed = countList[i]%(etc.xres+width*2)
x = (j * (width/5)) + (modSpeed-width)
pygame.draw.line(screen, color, [x, y1], [x, y0], int(etc.knob3*((100*etc.xres)/1280)+1))
if etc.audio_trig or etc.midi_note_new :
trigger = True
trigger = False
| none | 1 | 2.754354 | 3 | |
Dataset/Leetcode/train/125/353.py | kkcookies99/UAST | 0 | 6620427 | class Solution:
def XXX(self, s: str) -> bool:
i = 0
j = len(s) - 1
while i <= j:
if s[i] == s[j] or s[i].lower() == s[j].lower():
i += 1
j -= 1
elif not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
else:
return False
return True
| class Solution:
def XXX(self, s: str) -> bool:
i = 0
j = len(s) - 1
while i <= j:
if s[i] == s[j] or s[i].lower() == s[j].lower():
i += 1
j -= 1
elif not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
else:
return False
return True
| none | 1 | 3.141674 | 3 | |
sopel_modules/nettools/__init__.py | anewmanRH/sopel-nettools | 0 | 6620428 | <gh_stars>0
# coding=utf8
"""Sopel Nettools
Sopel Network module
"""
from __future__ import unicode_literals, absolute_import, division, print_function
from .nettools import *
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| # coding=utf8
"""Sopel Nettools
Sopel Network module
"""
from __future__ import unicode_literals, absolute_import, division, print_function
from .nettools import *
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.1.0' | ca | 0.198001 | # coding=utf8 Sopel Nettools Sopel Network module | 0.921789 | 1 |
napeca/prepreprocess/bruker_marked_pts_process.py | Alex-de-Lecea/NAPE_imaging_analysis | 3 | 6620429 | #!/usr/bin/env python
# coding: utf-8
"""
The bruker scope turns off the PMT during stimulation times, so fluorescence on certain lines are balnked. Using a combination of setting a threshold for the pixel-averaged fluorescence time-series and stim times from analog ttl (extracted using bruker_data_process), identify the frames that contain stim.
Also plots the mark points stim ROIs on the mean image
Currently looks for "stim" keys in the analog event dictionary for analog signals that represent stimulation
"""
import h5py
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import xml.etree.ElementTree as ET
import pickle
import pandas as pd
import warnings
import utils_bruker
def check_exist_dir(path):
if not os.path.exists(path):
os.mkdir(path)
return path
### Loading functions
def load_ca_data(fdir, fname):
if not os.path.exists(os.path.join(fdir, fname + '.h5')):
warnings.warn('No h5 with frame data found! Rerun the main code with flag_make_h5_tiff set to True.')
else:
h5_file = h5py.File(os.path.join(fdir, fname + '.h5'), 'r')
return h5_file.get(list(h5_file)[0])[()] # [()] grabs the values
# takes bruker marked points xml data, goes through each iteration, group, and point and grabs meta data
# all times are in ms
def load_mark_pt_xml_df(path_vars, im_shape):
mark_pt_xml_parse = ET.parse(path_vars['mark_pt_xml_path']).getroot()
mk_pt_dict = {'iterations': int(mark_pt_xml_parse.attrib['Iterations']),
'iter_delay': float(mark_pt_xml_parse.attrib['IterationDelay'])}
mk_pt_df = pd.DataFrame()
point_counter = 0
for type_tag in mark_pt_xml_parse.findall('PVMarkPointElement'):
laser_pow = float(type_tag.attrib['UncagingLaserPower'])*100
reps = int(type_tag.attrib['Repetitions'])
for group_tag in type_tag.findall('PVGalvoPointElement'):
duration = float(group_tag.attrib['Duration'])
IPI = float(group_tag.attrib['InterPointDelay'])
initial_delay = float(group_tag.attrib['InitialDelay'])
try:
group = group_tag.attrib['Points']
except:
print('No Group')
for point in group_tag.findall('Point'):
mk_pt_df.loc[point_counter, 'group'] = group
mk_pt_df.loc[point_counter, 'repetitions'] = reps
mk_pt_df.loc[point_counter, 'height'] = np.round(float(point.attrib['SpiralHeight'])*im_shape[0])
mk_pt_df.loc[point_counter, 'width'] = np.round(float(point.attrib['SpiralWidth'])*im_shape[1])
mk_pt_df.loc[point_counter, 'IsSpiral'] = point.attrib['IsSpiral']
mk_pt_df.loc[point_counter, 'Y'] = np.round(float(point.attrib['Y'])*im_shape[0])
mk_pt_df.loc[point_counter, 'X'] = np.round(float(point.attrib['X'])*im_shape[1])
mk_pt_df.loc[point_counter, 'duration'] = duration
mk_pt_df.loc[point_counter, 'IPI'] = IPI
mk_pt_df.loc[point_counter, 'initial_delay'] = initial_delay
mk_pt_df.loc[point_counter, 'pow'] = laser_pow
mk_pt_df.loc[point_counter, 'index'] = float(point.attrib['Index'])
point_counter += 1
return mk_pt_df
# loads dict of analog events dict
def load_analog_stim_samples(analog_event_path):
if os.path.exists(analog_event_path):
with open(analog_event_path, 'rb') as handle:
analog_event_dict = pickle.load(handle)
if 'stim' in analog_event_dict.keys():
return np.array(list(set(analog_event_dict['stim'])))
else:
return []
else:
return []
### analysis functions
# take avg fluorescene across pixels and take threshold
def std_thresh_stim_detect(im, thresh_std=1.5):
im_pix_avg = np.squeeze(np.mean(im, axis=(1,2)))
im_pix_avg_std = np.std(im_pix_avg)
im_pix_avg_avg = np.mean(im_pix_avg)
thresh = im_pix_avg_avg - im_pix_avg_std*thresh_std
return np.where(im_pix_avg < thresh)[0], thresh
### plotting functions
# plot pix-avg t-series of video, blanked frames t-series, and threshold
def plot_blanked_frames(save_dir, im_pix_avg, stimmed_frames, thresh_val, lims = None):
im_pix_avg_copy = np.copy(im_pix_avg)
im_pix_avg_copy[stimmed_frames['samples']] = np.nan
fig, ax = plt.subplots(1,1)
ax.plot(im_pix_avg)
ax.plot(im_pix_avg_copy)
ax.plot(np.ones(len(im_pix_avg))*thresh_val)
if lims:
ax.set_xlim(lims)
ax.legend(['original', 'blanked_stim', 'threshold'])
plt.savefig(os.path.join(save_dir, 'stim_frame_thresholding.png'))
def plot_stim_locations(im, path_vars):
img_mean = np.mean(im, axis=0)
img_mean_clims = [np.min(img_mean)*1.2, np.max(img_mean)*0.6]
mk_pt_df = load_mark_pt_xml_df(path_vars, img_mean.shape)[['height', 'width', 'X', 'Y', 'index']].drop_duplicates()
point_counter = 0
fig, ax = plt.subplots(1,1, figsize=(10,10))
ax.imshow(img_mean, clim=img_mean_clims, cmap='gray')
plot_mk_pts = True
if plot_mk_pts:
for df_idx, row in mk_pt_df.iterrows():
roi_color = np.random.rand(3)
mk_pt_ellipse = matplotlib.patches.Ellipse((row['X'], row['Y']),
row['height'], row['width'])
ax.add_artist(mk_pt_ellipse)
mk_pt_ellipse.set_clip_box(ax.bbox)
mk_pt_ellipse.set_edgecolor(roi_color)
mk_pt_ellipse.set_facecolor('None')
plt.text(row['X']+row['width'], row['Y']+row['height'], str(int(row['index'])), fontsize=10, color=roi_color)
ax.axis('off')
plt.savefig(os.path.join(path_vars['figs_savepath'], 'stim_roi_locs.png'))
# In[14]:
def main_detect_save_stim_frames(fdir, fname, detection_threshold=1.5, flag_plot_mk_pts=False):
path_vars = {}
path_vars['tseries_xml_path'] = os.path.join(fdir, fname + '.xml')
path_vars['mark_pt_xml_path'] = os.path.join(fdir, fname + '_Cycle00001_MarkPoints.xml')
path_vars['analog_event_path'] = os.path.join(fdir, 'framenumberforevents_{}.pkl'.format(fname))
path_vars['mk_pt_h5_savepath'] = os.path.join(fdir, fname + 'mk_pt_meta.h5')
path_vars['stim_frames_savepath'] = os.path.join(fdir, fname + '_stimmed_frames.pkl')
path_vars['figs_savepath'] = check_exist_dir(os.path.join(fdir, fname + '_output_images'))
fs_2p = utils_bruker.bruker_xml_get_2p_fs(path_vars['tseries_xml_path'])
im = load_ca_data(fdir, fname)
# load, analyze, and combine detected stim frames
analog_detected_stims = load_analog_stim_samples(path_vars['analog_event_path']) # these are detected stim frames calculated from the analog xml meta data
thresh_detected_stims, thresh_val = std_thresh_stim_detect(im, thresh_std=detection_threshold) # these are detected stim frames from pixel-avg thresholding
analog_thresh_detected_stims = np.union1d(analog_detected_stims, thresh_detected_stims).astype('int') # combine detected frames from the two methods
# add stimmed frames to dict
stimmed_frames = {}
stimmed_frames['samples'] = analog_thresh_detected_stims
stimmed_frames['times'] = analog_thresh_detected_stims/fs_2p
# save pickled dict that contains frames and corresponding frame times where pulses occurred
with open(path_vars['stim_frames_savepath'], 'wb') as handle:
pickle.dump(stimmed_frames, handle, protocol=pickle.HIGHEST_PROTOCOL)
# plot pix-avg t-series, t-series with blanked frames, and threshold
im_pix_avg = np.squeeze(np.nanmean(im, axis=(1,2)))
plot_blanked_frames(path_vars['figs_savepath'], im_pix_avg, stimmed_frames, thresh_val, lims = None)
# plot mark point stim locations on mean img
if flag_plot_mk_pts:
plot_stim_locations(im, path_vars)
if __name__ == "__main__":
fname = 'vj_ofc_imageactivate_001_20200828-003'
fdir = r'D:\bruker_data\vj_ofc_imageactivate_001_20200828\vj_ofc_imageactivate_001_20200828-003'
detection_threshold = 1.5
flag_plot_mk_pts = True
main_detect_save_stim_frames(fdir, fname, detection_threshold, flag_plot_mk_pts)
# In[ ]:
| #!/usr/bin/env python
# coding: utf-8
"""
The bruker scope turns off the PMT during stimulation times, so fluorescence on certain lines are balnked. Using a combination of setting a threshold for the pixel-averaged fluorescence time-series and stim times from analog ttl (extracted using bruker_data_process), identify the frames that contain stim.
Also plots the mark points stim ROIs on the mean image
Currently looks for "stim" keys in the analog event dictionary for analog signals that represent stimulation
"""
import h5py
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import xml.etree.ElementTree as ET
import pickle
import pandas as pd
import warnings
import utils_bruker
def check_exist_dir(path):
if not os.path.exists(path):
os.mkdir(path)
return path
### Loading functions
def load_ca_data(fdir, fname):
if not os.path.exists(os.path.join(fdir, fname + '.h5')):
warnings.warn('No h5 with frame data found! Rerun the main code with flag_make_h5_tiff set to True.')
else:
h5_file = h5py.File(os.path.join(fdir, fname + '.h5'), 'r')
return h5_file.get(list(h5_file)[0])[()] # [()] grabs the values
# takes bruker marked points xml data, goes through each iteration, group, and point and grabs meta data
# all times are in ms
def load_mark_pt_xml_df(path_vars, im_shape):
mark_pt_xml_parse = ET.parse(path_vars['mark_pt_xml_path']).getroot()
mk_pt_dict = {'iterations': int(mark_pt_xml_parse.attrib['Iterations']),
'iter_delay': float(mark_pt_xml_parse.attrib['IterationDelay'])}
mk_pt_df = pd.DataFrame()
point_counter = 0
for type_tag in mark_pt_xml_parse.findall('PVMarkPointElement'):
laser_pow = float(type_tag.attrib['UncagingLaserPower'])*100
reps = int(type_tag.attrib['Repetitions'])
for group_tag in type_tag.findall('PVGalvoPointElement'):
duration = float(group_tag.attrib['Duration'])
IPI = float(group_tag.attrib['InterPointDelay'])
initial_delay = float(group_tag.attrib['InitialDelay'])
try:
group = group_tag.attrib['Points']
except:
print('No Group')
for point in group_tag.findall('Point'):
mk_pt_df.loc[point_counter, 'group'] = group
mk_pt_df.loc[point_counter, 'repetitions'] = reps
mk_pt_df.loc[point_counter, 'height'] = np.round(float(point.attrib['SpiralHeight'])*im_shape[0])
mk_pt_df.loc[point_counter, 'width'] = np.round(float(point.attrib['SpiralWidth'])*im_shape[1])
mk_pt_df.loc[point_counter, 'IsSpiral'] = point.attrib['IsSpiral']
mk_pt_df.loc[point_counter, 'Y'] = np.round(float(point.attrib['Y'])*im_shape[0])
mk_pt_df.loc[point_counter, 'X'] = np.round(float(point.attrib['X'])*im_shape[1])
mk_pt_df.loc[point_counter, 'duration'] = duration
mk_pt_df.loc[point_counter, 'IPI'] = IPI
mk_pt_df.loc[point_counter, 'initial_delay'] = initial_delay
mk_pt_df.loc[point_counter, 'pow'] = laser_pow
mk_pt_df.loc[point_counter, 'index'] = float(point.attrib['Index'])
point_counter += 1
return mk_pt_df
# loads dict of analog events dict
def load_analog_stim_samples(analog_event_path):
if os.path.exists(analog_event_path):
with open(analog_event_path, 'rb') as handle:
analog_event_dict = pickle.load(handle)
if 'stim' in analog_event_dict.keys():
return np.array(list(set(analog_event_dict['stim'])))
else:
return []
else:
return []
### analysis functions
# take avg fluorescene across pixels and take threshold
def std_thresh_stim_detect(im, thresh_std=1.5):
im_pix_avg = np.squeeze(np.mean(im, axis=(1,2)))
im_pix_avg_std = np.std(im_pix_avg)
im_pix_avg_avg = np.mean(im_pix_avg)
thresh = im_pix_avg_avg - im_pix_avg_std*thresh_std
return np.where(im_pix_avg < thresh)[0], thresh
### plotting functions
# plot pix-avg t-series of video, blanked frames t-series, and threshold
def plot_blanked_frames(save_dir, im_pix_avg, stimmed_frames, thresh_val, lims = None):
im_pix_avg_copy = np.copy(im_pix_avg)
im_pix_avg_copy[stimmed_frames['samples']] = np.nan
fig, ax = plt.subplots(1,1)
ax.plot(im_pix_avg)
ax.plot(im_pix_avg_copy)
ax.plot(np.ones(len(im_pix_avg))*thresh_val)
if lims:
ax.set_xlim(lims)
ax.legend(['original', 'blanked_stim', 'threshold'])
plt.savefig(os.path.join(save_dir, 'stim_frame_thresholding.png'))
def plot_stim_locations(im, path_vars):
img_mean = np.mean(im, axis=0)
img_mean_clims = [np.min(img_mean)*1.2, np.max(img_mean)*0.6]
mk_pt_df = load_mark_pt_xml_df(path_vars, img_mean.shape)[['height', 'width', 'X', 'Y', 'index']].drop_duplicates()
point_counter = 0
fig, ax = plt.subplots(1,1, figsize=(10,10))
ax.imshow(img_mean, clim=img_mean_clims, cmap='gray')
plot_mk_pts = True
if plot_mk_pts:
for df_idx, row in mk_pt_df.iterrows():
roi_color = np.random.rand(3)
mk_pt_ellipse = matplotlib.patches.Ellipse((row['X'], row['Y']),
row['height'], row['width'])
ax.add_artist(mk_pt_ellipse)
mk_pt_ellipse.set_clip_box(ax.bbox)
mk_pt_ellipse.set_edgecolor(roi_color)
mk_pt_ellipse.set_facecolor('None')
plt.text(row['X']+row['width'], row['Y']+row['height'], str(int(row['index'])), fontsize=10, color=roi_color)
ax.axis('off')
plt.savefig(os.path.join(path_vars['figs_savepath'], 'stim_roi_locs.png'))
# In[14]:
def main_detect_save_stim_frames(fdir, fname, detection_threshold=1.5, flag_plot_mk_pts=False):
path_vars = {}
path_vars['tseries_xml_path'] = os.path.join(fdir, fname + '.xml')
path_vars['mark_pt_xml_path'] = os.path.join(fdir, fname + '_Cycle00001_MarkPoints.xml')
path_vars['analog_event_path'] = os.path.join(fdir, 'framenumberforevents_{}.pkl'.format(fname))
path_vars['mk_pt_h5_savepath'] = os.path.join(fdir, fname + 'mk_pt_meta.h5')
path_vars['stim_frames_savepath'] = os.path.join(fdir, fname + '_stimmed_frames.pkl')
path_vars['figs_savepath'] = check_exist_dir(os.path.join(fdir, fname + '_output_images'))
fs_2p = utils_bruker.bruker_xml_get_2p_fs(path_vars['tseries_xml_path'])
im = load_ca_data(fdir, fname)
# load, analyze, and combine detected stim frames
analog_detected_stims = load_analog_stim_samples(path_vars['analog_event_path']) # these are detected stim frames calculated from the analog xml meta data
thresh_detected_stims, thresh_val = std_thresh_stim_detect(im, thresh_std=detection_threshold) # these are detected stim frames from pixel-avg thresholding
analog_thresh_detected_stims = np.union1d(analog_detected_stims, thresh_detected_stims).astype('int') # combine detected frames from the two methods
# add stimmed frames to dict
stimmed_frames = {}
stimmed_frames['samples'] = analog_thresh_detected_stims
stimmed_frames['times'] = analog_thresh_detected_stims/fs_2p
# save pickled dict that contains frames and corresponding frame times where pulses occurred
with open(path_vars['stim_frames_savepath'], 'wb') as handle:
pickle.dump(stimmed_frames, handle, protocol=pickle.HIGHEST_PROTOCOL)
# plot pix-avg t-series, t-series with blanked frames, and threshold
im_pix_avg = np.squeeze(np.nanmean(im, axis=(1,2)))
plot_blanked_frames(path_vars['figs_savepath'], im_pix_avg, stimmed_frames, thresh_val, lims = None)
# plot mark point stim locations on mean img
if flag_plot_mk_pts:
plot_stim_locations(im, path_vars)
if __name__ == "__main__":
fname = 'vj_ofc_imageactivate_001_20200828-003'
fdir = r'D:\bruker_data\vj_ofc_imageactivate_001_20200828\vj_ofc_imageactivate_001_20200828-003'
detection_threshold = 1.5
flag_plot_mk_pts = True
main_detect_save_stim_frames(fdir, fname, detection_threshold, flag_plot_mk_pts)
# In[ ]:
| en | 0.802211 | #!/usr/bin/env python # coding: utf-8 The bruker scope turns off the PMT during stimulation times, so fluorescence on certain lines are balnked. Using a combination of setting a threshold for the pixel-averaged fluorescence time-series and stim times from analog ttl (extracted using bruker_data_process), identify the frames that contain stim. Also plots the mark points stim ROIs on the mean image Currently looks for "stim" keys in the analog event dictionary for analog signals that represent stimulation ### Loading functions # [()] grabs the values # takes bruker marked points xml data, goes through each iteration, group, and point and grabs meta data # all times are in ms # loads dict of analog events dict ### analysis functions # take avg fluorescene across pixels and take threshold ### plotting functions # plot pix-avg t-series of video, blanked frames t-series, and threshold # In[14]: # load, analyze, and combine detected stim frames # these are detected stim frames calculated from the analog xml meta data # these are detected stim frames from pixel-avg thresholding # combine detected frames from the two methods # add stimmed frames to dict # save pickled dict that contains frames and corresponding frame times where pulses occurred # plot pix-avg t-series, t-series with blanked frames, and threshold # plot mark point stim locations on mean img # In[ ]: | 2.414451 | 2 |
tests/test_hg_agent_periodic.py | metricfire/hg-agent-periodic | 0 | 6620430 | <filename>tests/test_hg_agent_periodic.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import os
import signal
import socket
import textwrap
import threading
import unittest
import httmock
import mock
import requests
import yaml
from pyfakefs import fake_filesystem_unittest
from hg_agent_periodic import periodic
# NB: we print exception messages to allow visual inspection that we're failing
# the right thing.
class TestConfigSchema(unittest.TestCase):
def test_barestring(self):
y = yaml.load('bare string')
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_ok(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
def test_ok_proxy(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
https_proxy: "http://10.10.1.10:1080"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
def test_unknown_key(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
something: "whatever"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_missing_required_key(self):
cfg = '''
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_api_key(self):
cfg = '''
api_key: "<KEY>"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_endpoint(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint: "not a hostname"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_endpoint_url(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "not a URL"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_proxy(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
https_proxy: "not a proxy URI"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_spelling(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
ednpoint: "a.carbon.endpoint"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
class TestDiamondConfigGen(unittest.TestCase):
def test_gen(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn('host = localhost', lines)
self.assertIn(
'path_prefix = hg_agent',
lines)
def test_custom_prefix(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
custom_prefix: "no_2_hg_agent"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn(
'path_prefix = no_2_hg_agent',
lines)
def test_hostname_method(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
hostname_method: "fqdn"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn('hostname_method = fqdn', lines)
def test_generated_configs_differ(self):
cfg1 = textwrap.dedent('''A line,
a line we should ignore,
another line''')
cfg2 = textwrap.dedent('''A line,
a line we should ignore and not worry about,
another line''')
cfg3 = textwrap.dedent('''Some line,
a line we should ignore,
Some other line''')
self.assertFalse(
periodic.generated_configs_differ(cfg1, cfg2,
ignore='ignore'))
self.assertTrue(
periodic.generated_configs_differ(cfg1, cfg3,
ignore='ignore'))
ConfigArgs = collections.namedtuple('ConfigArgs', ['config', 'diamond_config'])
class TestConfigOnce(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
periodic.remember_config({})
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.validate_agent_config')
def test_config_load_error(self, mock_validate, mock_logging):
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_logging.error.assert_called()
# If load fails, we never reach validate
mock_validate.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_invalid(self, mock_gen, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
invalid_key: "test"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
# If validation fails, we never reach gen.
mock_logging.error.assert_called()
mock_gen.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_new_diamond(self, mock_gen, mock_restart):
# As jinja2 uses the filesystem, we need to mock this out here (but
# note its functionality is tested in TestDiamondConfigGen above).
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
self.assertFalse(os.path.exists('/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
self.assertTrue(os.path.exists('/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_diamond_unchanged(self, mock_gen, mock_restart):
old_diamond = 'a fake diamond config\n'
mock_gen.return_value = old_diamond
self.fs.CreateFile('/diamond.cfg', contents=old_diamond)
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_no_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is not restarted without `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_unchanged_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is not restarted with unchanged `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_changed_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder/receiver are restarted with changed `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://other-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
mock_restart.assert_any_call(mock.ANY, 'receiver')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_unchanged_api_key(self, mock_gen, mock_restart):
'''The forwarder is not restarted with unchanged `api_key`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_changed_api_key(self, mock_gen, mock_restart):
'''The forwarder/receiver are restarted with changed `api_key`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "10000000-0000-0000-0000-000000000001"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
mock_restart.assert_any_call(mock.ANY, 'receiver')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_new_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is restarted with an entirely new `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_write_except(self, mock_gen, mock_restart, mock_logging):
mock_gen.return_value = 'a fake diamond config\n'
mock_restart.side_effect = Exception('test')
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_logging.exception.assert_called()
HeartbeatArgs = collections.namedtuple('HeartbeatArgs',
['config', 'agent_version',
'periodic_logfile', 'heartbeat'])
# httmock setup
@httmock.urlmatch(netloc=r'^heartbeat_ok.*$')
def heartbeat_ok_mock(url, request):
return 'OK'
@httmock.urlmatch(netloc=r'^heartbeat_timeout.*$')
def heartbeat_timeout_mock(url, request):
raise requests.exceptions.Timeout('Connection timed out.')
@httmock.urlmatch(netloc=r'^heartbeat_authfail.*$')
def heartbeat_authfail_mock(url, request):
return httmock.response(401)
@httmock.urlmatch(netloc=r'^heartbeat_unhandled.*$')
def heartbeat_unhandled_mock(url, request):
raise requests.exceptions.RequestException('test')
class TestHeartbeatOnce(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_get_primary_ip(self):
a = periodic.get_primary_ip()
try:
socket.inet_aton(a)
except socket.error:
self.fail('address from get_primary_ip does not parse '
'properly: %s' % a)
def test_get_version(self):
self.fs.CreateFile('/version', contents='0.1\n')
result = periodic.get_version('/nonexistent')
self.assertEqual(None, result)
result = periodic.get_version('/version')
self.assertEqual('0.1', result)
def test_collect_logs(self):
data = ['line %.02d' % i for i in range(20)]
self.fs.CreateFile('/test.log', contents='\n'.join(data) + '\n')
result = periodic.collect_logs('/nonexistent.log')
self.assertEqual([], result)
result = periodic.collect_logs('/test.log')
self.assertEqual(data[10:], result)
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.validate_agent_config')
def test_config_load_error(self, mock_validate, mock_logging):
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
mock_logging.error.assert_called()
# If load fails, we never reach validate
mock_validate.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.get_version')
def test_config_invalid(self, mock_version, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
invalid_key: "test"
'''))
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
# If validation fails, we never reach version.
mock_logging.error.assert_called()
mock_version.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.collect_logs')
def test_version_invalid(self, mock_collect, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
# If version fails, we never reach collect_logs.
mock_logging.error.assert_called()
mock_collect.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.send_heartbeat')
@mock.patch('hg_agent_periodic.periodic.platform')
def test_heartbeat(self, mock_platform, mock_send):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
self.fs.CreateFile('/version', contents='0.1\n')
data = ['line %.02d' % i for i in range(20)]
self.fs.CreateFile('/test.log', contents='\n'.join(data) + '\n')
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
mock_platform.platform.assert_called()
mock_send.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_ok(self, mock_logging):
endpoint = 'https://heartbeat_ok.hg.com/beat'
with httmock.HTTMock(heartbeat_ok_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_timeout(self, mock_logging):
endpoint = 'https://heartbeat_timeout.hg.com/beat'
with httmock.HTTMock(heartbeat_timeout_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_auth_fail(self, mock_logging):
endpoint = 'https://heartbeat_authfail.hg.com/beat'
with httmock.HTTMock(heartbeat_authfail_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_unhandled(self, mock_logging):
endpoint = 'https://heartbeat_unhandled.hg.com/beat'
with httmock.HTTMock(heartbeat_unhandled_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.requests')
def test_send_proxied(self, mock_requests):
mock_response = mock.MagicMock(requests.Response)
mock_requests.put.return_value = mock_response
periodic.send_heartbeat('endpoint', '{"fake": "json"}')
mock_requests.put.assert_called_once_with(mock.ANY,
json=mock.ANY,
timeout=mock.ANY)
mock_requests.reset_mock()
periodic.send_heartbeat('endpoint', '{"fake": "json"}',
proxies={'https': 'dummy'})
mock_requests.put.assert_called_once_with(mock.ANY,
json=mock.ANY,
timeout=mock.ANY,
proxies={'https': 'dummy'})
class TestMiscFunctions(unittest.TestCase):
def test_get_args(self):
args = periodic.get_args([])
self.assertFalse(args.debug)
self.assertTrue(args.config_interval > 0)
self.assertTrue(args.heartbeat_interval > 0)
def test_create_shutdown_event(self):
s = periodic.create_shutdown_event()
self.assertFalse(s.is_set())
os.kill(os.getpid(), signal.SIGTERM)
self.assertTrue(s.is_set())
@mock.patch('hg_agent_periodic.periodic.time.time')
@mock.patch('hg_agent_periodic.periodic.time.sleep')
@mock.patch('hg_agent_periodic.periodic.logging')
def test_periodic_task(self, mock_logger, mock_sleep, mock_time):
# We mock out some period of 6 seconds.
mock_time.side_effect = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0]
# Gives our mock `func` a `__name__` attribute for logging.
def dummy():
pass
func = mock.Mock(spec=dummy)
# Expect to call this once at the start + twice in 5s at 2s intervals.
# To test the exception path, have the last call throw.
func.side_effect = [True, True, Exception('test')]
# Loop 6 times before shutdown.
shutdown = mock.create_autospec(threading.Event())
shutdown.is_set.side_effect = 5 * [False] + [True]
periodic.periodic_task(func, None, 2, shutdown)
mock_logger.exception.assert_called()
self.assertEqual(func.call_count, 3)
| <filename>tests/test_hg_agent_periodic.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import os
import signal
import socket
import textwrap
import threading
import unittest
import httmock
import mock
import requests
import yaml
from pyfakefs import fake_filesystem_unittest
from hg_agent_periodic import periodic
# NB: we print exception messages to allow visual inspection that we're failing
# the right thing.
class TestConfigSchema(unittest.TestCase):
def test_barestring(self):
y = yaml.load('bare string')
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_ok(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
def test_ok_proxy(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
https_proxy: "http://10.10.1.10:1080"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
def test_unknown_key(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
something: "whatever"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_missing_required_key(self):
cfg = '''
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_api_key(self):
cfg = '''
api_key: "<KEY>"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_endpoint(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint: "not a hostname"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_endpoint_url(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "not a URL"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_bad_proxy(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
https_proxy: "not a proxy URI"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
def test_spelling(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
ednpoint: "a.carbon.endpoint"
'''
y = yaml.load(textwrap.dedent(cfg))
with self.assertRaises(periodic.ValidationError) as cm:
periodic.validate_agent_config(y)
print cm.exception.message
class TestDiamondConfigGen(unittest.TestCase):
def test_gen(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn('host = localhost', lines)
self.assertIn(
'path_prefix = hg_agent',
lines)
def test_custom_prefix(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
custom_prefix: "no_2_hg_agent"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn(
'path_prefix = no_2_hg_agent',
lines)
def test_hostname_method(self):
cfg = '''
api_key: "00000000-0000-0000-0000-000000000000"
hostname_method: "fqdn"
'''
y = yaml.load(textwrap.dedent(cfg))
periodic.validate_agent_config(y)
diamond = periodic.gen_diamond_config(y)
lines = diamond.split('\n')
self.assertIn('hostname_method = fqdn', lines)
def test_generated_configs_differ(self):
cfg1 = textwrap.dedent('''A line,
a line we should ignore,
another line''')
cfg2 = textwrap.dedent('''A line,
a line we should ignore and not worry about,
another line''')
cfg3 = textwrap.dedent('''Some line,
a line we should ignore,
Some other line''')
self.assertFalse(
periodic.generated_configs_differ(cfg1, cfg2,
ignore='ignore'))
self.assertTrue(
periodic.generated_configs_differ(cfg1, cfg3,
ignore='ignore'))
ConfigArgs = collections.namedtuple('ConfigArgs', ['config', 'diamond_config'])
class TestConfigOnce(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
periodic.remember_config({})
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.validate_agent_config')
def test_config_load_error(self, mock_validate, mock_logging):
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_logging.error.assert_called()
# If load fails, we never reach validate
mock_validate.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_invalid(self, mock_gen, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
invalid_key: "test"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
# If validation fails, we never reach gen.
mock_logging.error.assert_called()
mock_gen.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_new_diamond(self, mock_gen, mock_restart):
# As jinja2 uses the filesystem, we need to mock this out here (but
# note its functionality is tested in TestDiamondConfigGen above).
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
self.assertFalse(os.path.exists('/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
self.assertTrue(os.path.exists('/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_diamond_unchanged(self, mock_gen, mock_restart):
old_diamond = 'a fake diamond config\n'
mock_gen.return_value = old_diamond
self.fs.CreateFile('/diamond.cfg', contents=old_diamond)
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_no_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is not restarted without `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_unchanged_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is not restarted with unchanged `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_changed_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder/receiver are restarted with changed `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://other-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
mock_restart.assert_any_call(mock.ANY, 'receiver')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_unchanged_api_key(self, mock_gen, mock_restart):
'''The forwarder is not restarted with unchanged `api_key`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_called_once_with(mock.ANY, 'diamond')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_changed_api_key(self, mock_gen, mock_restart):
'''The forwarder/receiver are restarted with changed `api_key`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "10000000-0000-0000-0000-000000000001"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
mock_restart.assert_any_call(mock.ANY, 'receiver')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_new_endpoint_url(self, mock_gen, mock_restart):
'''The forwarder is restarted with an entirely new `endpoint_url`'''
mock_gen.return_value = 'a fake diamond config\n'
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
config = self.fs.get_object('/hg-agent.cfg')
config.set_contents(textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
endpoint_url: "https://my-endpoint"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_restart.assert_any_call(mock.ANY, 'forwarder')
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.restart_process')
@mock.patch('hg_agent_periodic.periodic.gen_diamond_config')
def test_config_write_except(self, mock_gen, mock_restart, mock_logging):
mock_gen.return_value = 'a fake diamond config\n'
mock_restart.side_effect = Exception('test')
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
periodic.config_once(ConfigArgs('/hg-agent.cfg', '/diamond.cfg'))
mock_logging.exception.assert_called()
HeartbeatArgs = collections.namedtuple('HeartbeatArgs',
['config', 'agent_version',
'periodic_logfile', 'heartbeat'])
# httmock setup
@httmock.urlmatch(netloc=r'^heartbeat_ok.*$')
def heartbeat_ok_mock(url, request):
return 'OK'
@httmock.urlmatch(netloc=r'^heartbeat_timeout.*$')
def heartbeat_timeout_mock(url, request):
raise requests.exceptions.Timeout('Connection timed out.')
@httmock.urlmatch(netloc=r'^heartbeat_authfail.*$')
def heartbeat_authfail_mock(url, request):
return httmock.response(401)
@httmock.urlmatch(netloc=r'^heartbeat_unhandled.*$')
def heartbeat_unhandled_mock(url, request):
raise requests.exceptions.RequestException('test')
class TestHeartbeatOnce(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_get_primary_ip(self):
a = periodic.get_primary_ip()
try:
socket.inet_aton(a)
except socket.error:
self.fail('address from get_primary_ip does not parse '
'properly: %s' % a)
def test_get_version(self):
self.fs.CreateFile('/version', contents='0.1\n')
result = periodic.get_version('/nonexistent')
self.assertEqual(None, result)
result = periodic.get_version('/version')
self.assertEqual('0.1', result)
def test_collect_logs(self):
data = ['line %.02d' % i for i in range(20)]
self.fs.CreateFile('/test.log', contents='\n'.join(data) + '\n')
result = periodic.collect_logs('/nonexistent.log')
self.assertEqual([], result)
result = periodic.collect_logs('/test.log')
self.assertEqual(data[10:], result)
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.validate_agent_config')
def test_config_load_error(self, mock_validate, mock_logging):
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
mock_logging.error.assert_called()
# If load fails, we never reach validate
mock_validate.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.get_version')
def test_config_invalid(self, mock_version, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
invalid_key: "test"
'''))
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
# If validation fails, we never reach version.
mock_logging.error.assert_called()
mock_version.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
@mock.patch('hg_agent_periodic.periodic.collect_logs')
def test_version_invalid(self, mock_collect, mock_logging):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
# If version fails, we never reach collect_logs.
mock_logging.error.assert_called()
mock_collect.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.send_heartbeat')
@mock.patch('hg_agent_periodic.periodic.platform')
def test_heartbeat(self, mock_platform, mock_send):
self.fs.CreateFile('/hg-agent.cfg',
contents=textwrap.dedent('''
api_key: "00000000-0000-0000-0000-000000000000"
'''))
self.fs.CreateFile('/version', contents='0.1\n')
data = ['line %.02d' % i for i in range(20)]
self.fs.CreateFile('/test.log', contents='\n'.join(data) + '\n')
args = HeartbeatArgs('/hg-agent.cfg', '/version', '/test.log',
'endpoint')
periodic.heartbeat_once(args)
mock_platform.platform.assert_called()
mock_send.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_ok(self, mock_logging):
endpoint = 'https://heartbeat_ok.hg.com/beat'
with httmock.HTTMock(heartbeat_ok_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_not_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_timeout(self, mock_logging):
endpoint = 'https://heartbeat_timeout.hg.com/beat'
with httmock.HTTMock(heartbeat_timeout_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_auth_fail(self, mock_logging):
endpoint = 'https://heartbeat_authfail.hg.com/beat'
with httmock.HTTMock(heartbeat_authfail_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.logging')
def test_send_unhandled(self, mock_logging):
endpoint = 'https://heartbeat_unhandled.hg.com/beat'
with httmock.HTTMock(heartbeat_unhandled_mock):
periodic.send_heartbeat(endpoint, '{"fake": "json"}')
mock_logging.error.assert_called()
@mock.patch('hg_agent_periodic.periodic.requests')
def test_send_proxied(self, mock_requests):
mock_response = mock.MagicMock(requests.Response)
mock_requests.put.return_value = mock_response
periodic.send_heartbeat('endpoint', '{"fake": "json"}')
mock_requests.put.assert_called_once_with(mock.ANY,
json=mock.ANY,
timeout=mock.ANY)
mock_requests.reset_mock()
periodic.send_heartbeat('endpoint', '{"fake": "json"}',
proxies={'https': 'dummy'})
mock_requests.put.assert_called_once_with(mock.ANY,
json=mock.ANY,
timeout=mock.ANY,
proxies={'https': 'dummy'})
class TestMiscFunctions(unittest.TestCase):
def test_get_args(self):
args = periodic.get_args([])
self.assertFalse(args.debug)
self.assertTrue(args.config_interval > 0)
self.assertTrue(args.heartbeat_interval > 0)
def test_create_shutdown_event(self):
s = periodic.create_shutdown_event()
self.assertFalse(s.is_set())
os.kill(os.getpid(), signal.SIGTERM)
self.assertTrue(s.is_set())
@mock.patch('hg_agent_periodic.periodic.time.time')
@mock.patch('hg_agent_periodic.periodic.time.sleep')
@mock.patch('hg_agent_periodic.periodic.logging')
def test_periodic_task(self, mock_logger, mock_sleep, mock_time):
# We mock out some period of 6 seconds.
mock_time.side_effect = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0]
# Gives our mock `func` a `__name__` attribute for logging.
def dummy():
pass
func = mock.Mock(spec=dummy)
# Expect to call this once at the start + twice in 5s at 2s intervals.
# To test the exception path, have the last call throw.
func.side_effect = [True, True, Exception('test')]
# Loop 6 times before shutdown.
shutdown = mock.create_autospec(threading.Event())
shutdown.is_set.side_effect = 5 * [False] + [True]
periodic.periodic_task(func, None, 2, shutdown)
mock_logger.exception.assert_called()
self.assertEqual(func.call_count, 3)
| en | 0.568386 | #!/usr/bin/env python # -*- coding: utf-8 -*- # NB: we print exception messages to allow visual inspection that we're failing # the right thing. api_key: "00000000-0000-0000-0000-000000000000" api_key: "00000000-0000-0000-0000-000000000000" https_proxy: "http://10.10.1.10:1080" api_key: "00000000-0000-0000-0000-000000000000" something: "whatever" api_key: "<KEY>" api_key: "00000000-0000-0000-0000-000000000000" endpoint: "not a hostname" api_key: "00000000-0000-0000-0000-000000000000" endpoint_url: "not a URL" api_key: "00000000-0000-0000-0000-000000000000" https_proxy: "not a proxy URI" api_key: "00000000-0000-0000-0000-000000000000" ednpoint: "a.carbon.endpoint" api_key: "00000000-0000-0000-0000-000000000000" api_key: "00000000-0000-0000-0000-000000000000" custom_prefix: "no_2_hg_agent" api_key: "00000000-0000-0000-0000-000000000000" hostname_method: "fqdn" A line, a line we should ignore, another line A line, a line we should ignore and not worry about, another line Some line, a line we should ignore, Some other line # If load fails, we never reach validate api_key: "00000000-0000-0000-0000-000000000000" invalid_key: "test" # If validation fails, we never reach gen. # As jinja2 uses the filesystem, we need to mock this out here (but # note its functionality is tested in TestDiamondConfigGen above). api_key: "00000000-0000-0000-0000-000000000000" api_key: "00000000-0000-0000-0000-000000000000" The forwarder is not restarted without `endpoint_url` api_key: "00000000-0000-0000-0000-000000000000" The forwarder is not restarted with unchanged `endpoint_url` api_key: "00000000-0000-0000-0000-000000000000" endpoint_url: "https://my-endpoint" The forwarder/receiver are restarted with changed `endpoint_url` api_key: "00000000-0000-0000-0000-000000000000" endpoint_url: "https://my-endpoint" api_key: "00000000-0000-0000-0000-000000000000" endpoint_url: "https://other-endpoint" The forwarder is not restarted with unchanged `api_key` api_key: "00000000-0000-0000-0000-000000000000" The forwarder/receiver are restarted with changed `api_key` api_key: "00000000-0000-0000-0000-000000000000" api_key: "10000000-0000-0000-0000-000000000001" The forwarder is restarted with an entirely new `endpoint_url` api_key: "00000000-0000-0000-0000-000000000000" api_key: "00000000-0000-0000-0000-000000000000" endpoint_url: "https://my-endpoint" api_key: "00000000-0000-0000-0000-000000000000" # httmock setup # If load fails, we never reach validate api_key: "00000000-0000-0000-0000-000000000000" invalid_key: "test" # If validation fails, we never reach version. api_key: "00000000-0000-0000-0000-000000000000" # If version fails, we never reach collect_logs. api_key: "00000000-0000-0000-0000-000000000000" # We mock out some period of 6 seconds. # Gives our mock `func` a `__name__` attribute for logging. # Expect to call this once at the start + twice in 5s at 2s intervals. # To test the exception path, have the last call throw. # Loop 6 times before shutdown. | 2.202785 | 2 |
src/wheezy/core/tests/test_benchmark.py | akornatskyy/wheezy.core | 0 | 6620431 | """ Unit tests for ``wheezy.core.benchmark``.
"""
import unittest
from unittest.mock import Mock, PropertyMock
from wheezy.core.benchmark import Benchmark, Timer
class BenchmarkTestCase(unittest.TestCase):
def test_run(self):
"""Ensure targets are called."""
t1 = Mock()
t1.__name__ = "t1"
t2 = Mock()
t2.__name__ = "t2"
b = Benchmark((t1, t2), 20)
r = list(b.run())
assert 2 == len(r)
name, timing = r[0]
assert "t1" == name
assert timing >= 0
name, timing = r[1]
assert "t2" == name
assert timing >= 0
assert 30 == t1.call_count
assert 30 == t2.call_count
def test_run_timer(self):
"""Ensure timer is used."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timing = PropertyMock(return_value=5)
type(mock_timer).timing = mock_timing
b = Benchmark((t1,), 20, timer=mock_timer)
name, timing = list(b.run())[0]
assert "t1" == name
assert 5 == timing
mock_timer.start.assert_called_with()
assert 2 == mock_timer.start.call_count
mock_timer.stop.assert_called_with()
assert 2 == mock_timer.stop.call_count
mock_timing.assert_called_with()
assert 2 == mock_timing.call_count
def test_zero_division_error(self):
"""ZeroDivisionError is not raised when timing is 0."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timer.timing = 0
b = Benchmark((t1,), 10, timer=mock_timer)
b.report("sample")
def test_report(self):
"""Ensure report is printed."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timer.timing = 1
b = Benchmark((t1,), 10, timer=mock_timer)
b.report("sample")
class TimerTestCase(unittest.TestCase):
def test_start_stop(self):
"""Ensure a call is intercepted."""
mock_target = Mock()
mock_name = Mock()
mock_target.name = mock_name
t = Timer(mock_target, "name")
t.start()
assert mock_name != mock_target.name
mock_target.name()
t.stop()
assert mock_name == mock_target.name
| """ Unit tests for ``wheezy.core.benchmark``.
"""
import unittest
from unittest.mock import Mock, PropertyMock
from wheezy.core.benchmark import Benchmark, Timer
class BenchmarkTestCase(unittest.TestCase):
def test_run(self):
"""Ensure targets are called."""
t1 = Mock()
t1.__name__ = "t1"
t2 = Mock()
t2.__name__ = "t2"
b = Benchmark((t1, t2), 20)
r = list(b.run())
assert 2 == len(r)
name, timing = r[0]
assert "t1" == name
assert timing >= 0
name, timing = r[1]
assert "t2" == name
assert timing >= 0
assert 30 == t1.call_count
assert 30 == t2.call_count
def test_run_timer(self):
"""Ensure timer is used."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timing = PropertyMock(return_value=5)
type(mock_timer).timing = mock_timing
b = Benchmark((t1,), 20, timer=mock_timer)
name, timing = list(b.run())[0]
assert "t1" == name
assert 5 == timing
mock_timer.start.assert_called_with()
assert 2 == mock_timer.start.call_count
mock_timer.stop.assert_called_with()
assert 2 == mock_timer.stop.call_count
mock_timing.assert_called_with()
assert 2 == mock_timing.call_count
def test_zero_division_error(self):
"""ZeroDivisionError is not raised when timing is 0."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timer.timing = 0
b = Benchmark((t1,), 10, timer=mock_timer)
b.report("sample")
def test_report(self):
"""Ensure report is printed."""
t1 = Mock()
t1.__name__ = "t1"
mock_timer = Mock()
mock_timer.timing = 1
b = Benchmark((t1,), 10, timer=mock_timer)
b.report("sample")
class TimerTestCase(unittest.TestCase):
def test_start_stop(self):
"""Ensure a call is intercepted."""
mock_target = Mock()
mock_name = Mock()
mock_target.name = mock_name
t = Timer(mock_target, "name")
t.start()
assert mock_name != mock_target.name
mock_target.name()
t.stop()
assert mock_name == mock_target.name
| en | 0.919842 | Unit tests for ``wheezy.core.benchmark``. Ensure targets are called. Ensure timer is used. ZeroDivisionError is not raised when timing is 0. Ensure report is printed. Ensure a call is intercepted. | 3.048226 | 3 |
error_handling.py | DanteAlucard98/Learn_Python_Django | 0 | 6620432 | <reponame>DanteAlucard98/Learn_Python_Django
"""error_handling"""
"""def division(int1,int2):
try:
return int1/int2
except :
raise Exception('No podemos dividir entre cero')
print(division(0,0))
"""
"""
import sys
def linux_function():
assert('linux' in sys.platform),"This code only run on Linux"
print('Doing something')
try:
linux_function()
except AssertionError as error:
print(error)
print("Linux function was not executed")
"""
"""
assert
if 'linux' in sys.platform:
pass
else:
raise Exception("OS Error: This code only runs on Linux")
"""
import sys
def linux_validation():
assert('win32' in sys.platform),"This code only run on Linux"
print('Doing something')
try:
linux_validation()
except AssertionError as error:
print(error)
else:
try:
with open('file.log')as file:
read_data = file.read()
except FileNotFoundError as file_error:
print(file_error)
finally:
print('This is the finally clause')
| """error_handling"""
"""def division(int1,int2):
try:
return int1/int2
except :
raise Exception('No podemos dividir entre cero')
print(division(0,0))
"""
"""
import sys
def linux_function():
assert('linux' in sys.platform),"This code only run on Linux"
print('Doing something')
try:
linux_function()
except AssertionError as error:
print(error)
print("Linux function was not executed")
"""
"""
assert
if 'linux' in sys.platform:
pass
else:
raise Exception("OS Error: This code only runs on Linux")
"""
import sys
def linux_validation():
assert('win32' in sys.platform),"This code only run on Linux"
print('Doing something')
try:
linux_validation()
except AssertionError as error:
print(error)
else:
try:
with open('file.log')as file:
read_data = file.read()
except FileNotFoundError as file_error:
print(file_error)
finally:
print('This is the finally clause') | en | 0.429652 | error_handling def division(int1,int2): try: return int1/int2 except : raise Exception('No podemos dividir entre cero') print(division(0,0)) import sys def linux_function(): assert('linux' in sys.platform),"This code only run on Linux" print('Doing something') try: linux_function() except AssertionError as error: print(error) print("Linux function was not executed") assert if 'linux' in sys.platform: pass else: raise Exception("OS Error: This code only runs on Linux") | 3.811926 | 4 |
commands/developer_commands/generate_captcha.py | HedTB/OutDashRewrite | 1 | 6620433 | ## -- IMPORTING -- ##
# MODULES
import disnake
import os
import random
import asyncio
import datetime
import certifi
import string
from disnake.ext import commands
from disnake.errors import Forbidden, HTTPException
from disnake.ext.commands import errors
from pymongo import MongoClient
from dotenv import load_dotenv
from captcha.image import ImageCaptcha
# FILES
import extra.config as config
import extra.functions as functions
## -- VARIABLES -- ##
load_dotenv()
## -- COG -- ##
class GenerateCaptcha(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(hidden=True)
async def generatecaptcha(self, ctx: commands.Context):
if ctx.author.id not in config.owners:
return
captcha = functions.generate_captcha()
await ctx.send(file=disnake.File(f"{captcha}.png"))
os.remove(f"{captcha}.png")
def check(message2):
return message2.author == ctx.message.author and message2.content.upper() == captcha
try:
await self.bot.wait_for("message", timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send(f"{config.no} the captcha was: `" + captcha + "`")
else:
await ctx.send(config.yes)
def setup(bot):
bot.add_cog(GenerateCaptcha(bot)) | ## -- IMPORTING -- ##
# MODULES
import disnake
import os
import random
import asyncio
import datetime
import certifi
import string
from disnake.ext import commands
from disnake.errors import Forbidden, HTTPException
from disnake.ext.commands import errors
from pymongo import MongoClient
from dotenv import load_dotenv
from captcha.image import ImageCaptcha
# FILES
import extra.config as config
import extra.functions as functions
## -- VARIABLES -- ##
load_dotenv()
## -- COG -- ##
class GenerateCaptcha(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(hidden=True)
async def generatecaptcha(self, ctx: commands.Context):
if ctx.author.id not in config.owners:
return
captcha = functions.generate_captcha()
await ctx.send(file=disnake.File(f"{captcha}.png"))
os.remove(f"{captcha}.png")
def check(message2):
return message2.author == ctx.message.author and message2.content.upper() == captcha
try:
await self.bot.wait_for("message", timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send(f"{config.no} the captcha was: `" + captcha + "`")
else:
await ctx.send(config.yes)
def setup(bot):
bot.add_cog(GenerateCaptcha(bot)) | ta | 0.089093 | ## -- IMPORTING -- ## # MODULES # FILES ## -- VARIABLES -- ## ## -- COG -- ## | 2.287308 | 2 |
io-cesium-ion/globals.py | AnalyticalGraphicsInc/ion-blender-exporter | 6 | 6620434 | <reponame>AnalyticalGraphicsInc/ion-blender-exporter<filename>io-cesium-ion/globals.py
APP_CATEGORY = "Cesium ion"
APP_OPERATOR_PREFIX = "csm"
APP_PACKAGE = __package__
LOCAL = False
if LOCAL:
CLIENT_ID = "4"
ION_ADDRESS = "http://composer.test:8081"
API_ADDRESS = "http://api.composer.test:8081"
else:
CLIENT_ID = "19"
ION_ADDRESS = "https://cesium.com"
API_ADDRESS = "https://api.cesium.com"
REDIRECT_ADDRESS = "localhost"
REDIRECT_PORT = 10101
| APP_CATEGORY = "Cesium ion"
APP_OPERATOR_PREFIX = "csm"
APP_PACKAGE = __package__
LOCAL = False
if LOCAL:
CLIENT_ID = "4"
ION_ADDRESS = "http://composer.test:8081"
API_ADDRESS = "http://api.composer.test:8081"
else:
CLIENT_ID = "19"
ION_ADDRESS = "https://cesium.com"
API_ADDRESS = "https://api.cesium.com"
REDIRECT_ADDRESS = "localhost"
REDIRECT_PORT = 10101 | none | 1 | 1.261469 | 1 | |
mep/books/tests/test_books_utils.py | making-books-ren-today/test_eval_3_shxco | 3 | 6620435 | <reponame>making-books-ren-today/test_eval_3_shxco
from django.test import TestCase
from mep.books.models import Work
from mep.books.utils import creator_lastname, generate_sort_title, \
nonstop_words, work_slug
def test_nonstop_words():
assert nonstop_words('Time and Tide') == ['Time', 'Tide']
assert nonstop_words('transition') == ['transition']
assert nonstop_words('A Portrait of the Artist') == ['Portrait', 'Artist']
assert nonstop_words("L'Infini Turbulent") == ['Infini', 'Turbulent']
assert nonstop_words("La Vie et L'Habitude") == ['Vie', 'Habitude']
assert nonstop_words("Gray's Anatomy") == ['Grays', 'Anatomy']
assert nonstop_words("Why Didn't They Ask Evans?") == \
["Didnt", "Ask", "Evans"]
assert nonstop_words('"Car"') == ["Car"]
class TestCreatorLastname(TestCase):
fixtures = ['multi_creator_work']
def test_creator_lastname(self):
# multi-author work fixture
work = Work.objects.get(pk=4126)
# use first author
assert creator_lastname(work) == work.authors[0].short_name
# if no author, use first editor
work.creator_set.all().filter(creator_type__name='Author').delete()
assert creator_lastname(work) == work.editors[0].short_name
# if no authors or editors, no last name
work.creator_set.all().delete()
assert creator_lastname(work) == ''
class TestWorkSlug(TestCase):
fixtures = ['multi_creator_work']
def test_work_slug(self):
# multi-author work fixture
work = Work.objects.get(pk=4126)
# title: The English Novelists: A Survey of the Novel ...
assert work_slug(work) == 'bates-english-novelists-survey'
assert work_slug(work, max_words=4) == \
'bates-english-novelists-survey-novel'
work = Work(title="La Vie et L'Habitude")
assert work_slug(work) == 'vie-habitude'
work.title = "Gray's Anatomy"
assert work_slug(work) == 'grays-anatomy'
work.title = "Why Didn't They Ask Evans?"
assert work_slug(work) == "didnt-ask-evans"
work.title = '"Car"'
assert work_slug(work) == "car"
def test_generate_sort_title():
assert generate_sort_title('My Book') == 'My Book'
assert generate_sort_title('Book') == 'Book'
assert generate_sort_title('The Book') == 'Book'
assert generate_sort_title('"Car"') == 'Car"'
assert generate_sort_title('[unclear]') == 'unclear]'
assert generate_sort_title('L\'Infini') == 'Infini'
assert generate_sort_title('Of Mice and Men') == 'Of Mice and Men'
assert generate_sort_title('A Portrait of the Artist') == \
'Portrait of the Artist'
| from django.test import TestCase
from mep.books.models import Work
from mep.books.utils import creator_lastname, generate_sort_title, \
nonstop_words, work_slug
def test_nonstop_words():
assert nonstop_words('Time and Tide') == ['Time', 'Tide']
assert nonstop_words('transition') == ['transition']
assert nonstop_words('A Portrait of the Artist') == ['Portrait', 'Artist']
assert nonstop_words("L'Infini Turbulent") == ['Infini', 'Turbulent']
assert nonstop_words("La Vie et L'Habitude") == ['Vie', 'Habitude']
assert nonstop_words("Gray's Anatomy") == ['Grays', 'Anatomy']
assert nonstop_words("Why Didn't They Ask Evans?") == \
["Didnt", "Ask", "Evans"]
assert nonstop_words('"Car"') == ["Car"]
class TestCreatorLastname(TestCase):
fixtures = ['multi_creator_work']
def test_creator_lastname(self):
# multi-author work fixture
work = Work.objects.get(pk=4126)
# use first author
assert creator_lastname(work) == work.authors[0].short_name
# if no author, use first editor
work.creator_set.all().filter(creator_type__name='Author').delete()
assert creator_lastname(work) == work.editors[0].short_name
# if no authors or editors, no last name
work.creator_set.all().delete()
assert creator_lastname(work) == ''
class TestWorkSlug(TestCase):
fixtures = ['multi_creator_work']
def test_work_slug(self):
# multi-author work fixture
work = Work.objects.get(pk=4126)
# title: The English Novelists: A Survey of the Novel ...
assert work_slug(work) == 'bates-english-novelists-survey'
assert work_slug(work, max_words=4) == \
'bates-english-novelists-survey-novel'
work = Work(title="La Vie et L'Habitude")
assert work_slug(work) == 'vie-habitude'
work.title = "Gray's Anatomy"
assert work_slug(work) == 'grays-anatomy'
work.title = "Why Didn't They Ask Evans?"
assert work_slug(work) == "didnt-ask-evans"
work.title = '"Car"'
assert work_slug(work) == "car"
def test_generate_sort_title():
assert generate_sort_title('My Book') == 'My Book'
assert generate_sort_title('Book') == 'Book'
assert generate_sort_title('The Book') == 'Book'
assert generate_sort_title('"Car"') == 'Car"'
assert generate_sort_title('[unclear]') == 'unclear]'
assert generate_sort_title('L\'Infini') == 'Infini'
assert generate_sort_title('Of Mice and Men') == 'Of Mice and Men'
assert generate_sort_title('A Portrait of the Artist') == \
'Portrait of the Artist' | en | 0.78166 | # multi-author work fixture # use first author # if no author, use first editor # if no authors or editors, no last name # multi-author work fixture # title: The English Novelists: A Survey of the Novel ... | 2.416411 | 2 |
cogdl/layers/actlinear_layer.py | li-ziang/cogdl | 6 | 6620436 | <gh_stars>1-10
import torch.nn as nn
from actnn.conf import config
from actnn.qscheme import QScheme
from cogdl.operators.linear import linear
class QLinear(nn.Linear):
num_layers = 0
def __init__(self, input_features, output_features, bias=True, group=0, rp_ratio=2):
super(QLinear, self).__init__(input_features, output_features, bias)
if config.adaptive_conv_scheme:
self.scheme = QScheme(self, group=group)
else:
self.scheme = None
self.rp_ratio = rp_ratio
def forward(self, input):
if config.training:
return linear.apply(input, self.weight, self.bias, self.scheme, self.rp_ratio)
else:
return super(QLinear, self).forward(input)
| import torch.nn as nn
from actnn.conf import config
from actnn.qscheme import QScheme
from cogdl.operators.linear import linear
class QLinear(nn.Linear):
num_layers = 0
def __init__(self, input_features, output_features, bias=True, group=0, rp_ratio=2):
super(QLinear, self).__init__(input_features, output_features, bias)
if config.adaptive_conv_scheme:
self.scheme = QScheme(self, group=group)
else:
self.scheme = None
self.rp_ratio = rp_ratio
def forward(self, input):
if config.training:
return linear.apply(input, self.weight, self.bias, self.scheme, self.rp_ratio)
else:
return super(QLinear, self).forward(input) | none | 1 | 2.370685 | 2 | |
assignment2/reducer.py | IITDU-BSSE06/ads-demystifying-the-logs-mehedi-iitdu | 0 | 6620437 | #!/usr/bin/python
import sys
count = 0
for line in sys.stdin:
if "/assets/js/the-associates.js" in line:
count = count + 1
print(count) | #!/usr/bin/python
import sys
count = 0
for line in sys.stdin:
if "/assets/js/the-associates.js" in line:
count = count + 1
print(count) | ru | 0.258958 | #!/usr/bin/python | 2.385108 | 2 |
tests/i18n/urls.py | iMerica/dj-models | 5 | 6620438 | from djmodels.conf.urls import url
from djmodels.conf.urls.i18n import i18n_patterns
from djmodels.http import HttpResponse, StreamingHttpResponse
from djmodels.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
url(r'^simple/$', lambda r: HttpResponse()),
url(r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
)
| from djmodels.conf.urls import url
from djmodels.conf.urls.i18n import i18n_patterns
from djmodels.http import HttpResponse, StreamingHttpResponse
from djmodels.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
url(r'^simple/$', lambda r: HttpResponse()),
url(r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
)
| none | 1 | 2.052576 | 2 | |
graalpython/com.oracle.graal.python.test/testData/testFiles/FuncDefTests/functionDef13.py | transposit/graalpython | 1 | 6620439 | <gh_stars>1-10
def outer ():
x = 10
def inner():
x = 5
print("Inner, local x:", x)
inner()
print("Outer, local x:", x)
outer() | def outer ():
x = 10
def inner():
x = 5
print("Inner, local x:", x)
inner()
print("Outer, local x:", x)
outer() | none | 1 | 3.181219 | 3 | |
Police_Witness_Clustering.py | rafvasq/Incident-Accuracy-Reporting-System | 50 | 6620440 | <gh_stars>10-100
#!/usr/bin/env python
# coding: utf-8
# In[4]:
"""Importing dependencies"""
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import os
from nltk.stem.snowball import SnowballStemmer
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
import re
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
from sklearn.manifold import MDS
import pandas as pd
from sklearn.metrics import accuracy_score
from scipy.cluster.hierarchy import ward, dendrogram
# In[5]:
"""The tokenize_and_stem function below does the following: It removes the
stopwords, tokenizes the messages and also stems the individual words by converting
words of similar meaning to the same stem words"""
def tokenize_and_stem(text):
stemmer = SnowballStemmer("english")
# first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
filtered_tokens = []
# filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
for token in tokens:
if re.search('[a-zA-Z]', token):
filtered_tokens.append(token)
stems = [stemmer.stem(t) for t in filtered_tokens]
return stems
# In[55]:
"""Fetching the dataset"""
# @hidden_cell
# The following code contains the credentials for a file in your IBM Cloud Object Storage.
# You might want to remove those credentials before you share your notebook.
import types
import pandas as pd
from botocore.client import Config
import ibm_boto3
def __iter__(self): return 0
# @hidden_cell
# The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials.
# You might want to remove those credentials before you share the notebook.
client_72c2da47609b4ceea8396c4332b98ef3 = ibm_boto3.client(service_name='s3',
ibm_api_key_id='<KEY>',
ibm_auth_endpoint="https://iam.cloud.ibm.com/oidc/token",
config=Config(signature_version='oauth'),
endpoint_url='https://s3-api.us-geo.objectstorage.service.networklayer.com')
body = client_72c2da47609b4ceea8396c4332b98ef3.get_object(Bucket='embrace2-donotdelete-pr-wpnplsoeambclj',Key='sample_data.xlsx')['Body']
# add missing __iter__ method, so pandas accepts body as file-like object
if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType( __iter__, body )
df_data_0 = pd.read_excel(body)
#df_data_0.tail()
# In[11]:
"""Converting DataFrame into a list of reports"""
doc_file = []
for i in df_data_0[df_data_0.columns[1]]:
doc_file.append(i)
len(doc_file)
# In[21]:
"""labelling each datapoint"""
doc_label = []
#true_label = []
t=0
u=0
for i in doc_file:
t=t+1
if t<=100:
q='W'+str(t)
doc_label.append(q)
#true_label.append(0)
else:
#u=u+1
q='POLICE'
doc_label.append(q)
#true_label.append(1)
# In[14]:
# import nltk
# nltk.download('punkt')
# In[15]:
"""Vectorizing the data"""
vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,min_df=0.2,tokenizer=tokenize_and_stem,input='content',use_idf=True, stop_words='english',ngram_range=(1,3))
X = vectorizer.fit_transform(doc_file)
dist_vector = 1 - cosine_similarity(X)
# In[22]:
"""Running the kMeans Algorithm"""
true_k = 2
clustering_model = KMeans(n_clusters=true_k)
clustering_model.fit(X)
clusters = clustering_model.labels_.tolist()
print
print("Top terms per cluster:")
order_centroids = clustering_model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(true_k):
print ("Cluster %d:" % i,)
for t in order_centroids[i, :10]:
print (' %s' % terms[t],)
print()
# In[52]:
"""Creating a dataframe for the better presentation of the clusters.
This will also be used in generating some plots for a proper
visualization of the data points after running the algorithm"""
docs = { 'label': doc_label, 'documents': doc_file, 'cluster': clusters }
cluster_frame = pd.DataFrame(docs, index = [clusters] , columns = ['label', 'cluster'])
print()
print(cluster_frame['cluster'].value_counts())
mds = MDS(n_components=2, dissimilarity="precomputed", random_state=1)
pos = mds.fit_transform(dist_vector) # shape (n_components, n_samples)
xs, ys = pos[:, 0], pos[:, 1]
cluster_colors = {0: 'r', 1: 'b'}
cluster_names = {0: 'cluster 0', 1: 'cluster 1'}
#create data frame that has the result of the MDS plus the cluster numbers and labels
df = pd.DataFrame(dict(x=xs, y=ys, doc_cluster=clusters, label=doc_label))
#group by cluster
groups = df.groupby('doc_cluster')
# In[54]:
# for name, group in groups:
# print(group)
# In[53]:
""" setting up plot"""
fig, ax = plt.subplots(figsize=(18, 10))
ax.margins(0.05)
"""iterate through groups to layer the plotusing cluster_name and cluster_color
dicts with the 'name' lookup to return the appropriate color/label"""
plt.figure(1)
for name, group in groups:
ax.plot(group.x[:-1], group.y[:-1], marker='o', linestyle='', ms=12,
label=cluster_names[name], color=cluster_colors[name],
mec='none')
ax.set_aspect('auto')
ax.tick_params(axis= 'x', which='both', bottom='off', top='off', labelbottom='off')
ax.tick_params(axis= 'y', which='both', left='off', top='off', labelleft='off')
ax.legend(numpoints=1) #show legend with only 1 point
#add label in x,y position with the label as the class folder name
for i in range(len(df)):
ax.text(df.ix[i]['x'], df.ix[i]['y'], df.ix[i]['label'], size=12)
ax.plot(group.x[-1:], group.y[-1:], marker='o', linestyle='', ms=20,
label=cluster_names[name][-1:], color='g',
mec='none')
# In[ ]:
| #!/usr/bin/env python
# coding: utf-8
# In[4]:
"""Importing dependencies"""
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import os
from nltk.stem.snowball import SnowballStemmer
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
import re
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
from sklearn.manifold import MDS
import pandas as pd
from sklearn.metrics import accuracy_score
from scipy.cluster.hierarchy import ward, dendrogram
# In[5]:
"""The tokenize_and_stem function below does the following: It removes the
stopwords, tokenizes the messages and also stems the individual words by converting
words of similar meaning to the same stem words"""
def tokenize_and_stem(text):
stemmer = SnowballStemmer("english")
# first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
filtered_tokens = []
# filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
for token in tokens:
if re.search('[a-zA-Z]', token):
filtered_tokens.append(token)
stems = [stemmer.stem(t) for t in filtered_tokens]
return stems
# In[55]:
"""Fetching the dataset"""
# @hidden_cell
# The following code contains the credentials for a file in your IBM Cloud Object Storage.
# You might want to remove those credentials before you share your notebook.
import types
import pandas as pd
from botocore.client import Config
import ibm_boto3
def __iter__(self): return 0
# @hidden_cell
# The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials.
# You might want to remove those credentials before you share the notebook.
client_72c2da47609b4ceea8396c4332b98ef3 = ibm_boto3.client(service_name='s3',
ibm_api_key_id='<KEY>',
ibm_auth_endpoint="https://iam.cloud.ibm.com/oidc/token",
config=Config(signature_version='oauth'),
endpoint_url='https://s3-api.us-geo.objectstorage.service.networklayer.com')
body = client_72c2da47609b4ceea8396c4332b98ef3.get_object(Bucket='embrace2-donotdelete-pr-wpnplsoeambclj',Key='sample_data.xlsx')['Body']
# add missing __iter__ method, so pandas accepts body as file-like object
if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType( __iter__, body )
df_data_0 = pd.read_excel(body)
#df_data_0.tail()
# In[11]:
"""Converting DataFrame into a list of reports"""
doc_file = []
for i in df_data_0[df_data_0.columns[1]]:
doc_file.append(i)
len(doc_file)
# In[21]:
"""labelling each datapoint"""
doc_label = []
#true_label = []
t=0
u=0
for i in doc_file:
t=t+1
if t<=100:
q='W'+str(t)
doc_label.append(q)
#true_label.append(0)
else:
#u=u+1
q='POLICE'
doc_label.append(q)
#true_label.append(1)
# In[14]:
# import nltk
# nltk.download('punkt')
# In[15]:
"""Vectorizing the data"""
vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,min_df=0.2,tokenizer=tokenize_and_stem,input='content',use_idf=True, stop_words='english',ngram_range=(1,3))
X = vectorizer.fit_transform(doc_file)
dist_vector = 1 - cosine_similarity(X)
# In[22]:
"""Running the kMeans Algorithm"""
true_k = 2
clustering_model = KMeans(n_clusters=true_k)
clustering_model.fit(X)
clusters = clustering_model.labels_.tolist()
print
print("Top terms per cluster:")
order_centroids = clustering_model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(true_k):
print ("Cluster %d:" % i,)
for t in order_centroids[i, :10]:
print (' %s' % terms[t],)
print()
# In[52]:
"""Creating a dataframe for the better presentation of the clusters.
This will also be used in generating some plots for a proper
visualization of the data points after running the algorithm"""
docs = { 'label': doc_label, 'documents': doc_file, 'cluster': clusters }
cluster_frame = pd.DataFrame(docs, index = [clusters] , columns = ['label', 'cluster'])
print()
print(cluster_frame['cluster'].value_counts())
mds = MDS(n_components=2, dissimilarity="precomputed", random_state=1)
pos = mds.fit_transform(dist_vector) # shape (n_components, n_samples)
xs, ys = pos[:, 0], pos[:, 1]
cluster_colors = {0: 'r', 1: 'b'}
cluster_names = {0: 'cluster 0', 1: 'cluster 1'}
#create data frame that has the result of the MDS plus the cluster numbers and labels
df = pd.DataFrame(dict(x=xs, y=ys, doc_cluster=clusters, label=doc_label))
#group by cluster
groups = df.groupby('doc_cluster')
# In[54]:
# for name, group in groups:
# print(group)
# In[53]:
""" setting up plot"""
fig, ax = plt.subplots(figsize=(18, 10))
ax.margins(0.05)
"""iterate through groups to layer the plotusing cluster_name and cluster_color
dicts with the 'name' lookup to return the appropriate color/label"""
plt.figure(1)
for name, group in groups:
ax.plot(group.x[:-1], group.y[:-1], marker='o', linestyle='', ms=12,
label=cluster_names[name], color=cluster_colors[name],
mec='none')
ax.set_aspect('auto')
ax.tick_params(axis= 'x', which='both', bottom='off', top='off', labelbottom='off')
ax.tick_params(axis= 'y', which='both', left='off', top='off', labelleft='off')
ax.legend(numpoints=1) #show legend with only 1 point
#add label in x,y position with the label as the class folder name
for i in range(len(df)):
ax.text(df.ix[i]['x'], df.ix[i]['y'], df.ix[i]['label'], size=12)
ax.plot(group.x[-1:], group.y[-1:], marker='o', linestyle='', ms=20,
label=cluster_names[name][-1:], color='g',
mec='none')
# In[ ]: | en | 0.785491 | #!/usr/bin/env python # coding: utf-8 # In[4]: Importing dependencies # In[5]: The tokenize_and_stem function below does the following: It removes the stopwords, tokenizes the messages and also stems the individual words by converting words of similar meaning to the same stem words # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation) # In[55]: Fetching the dataset # @hidden_cell # The following code contains the credentials for a file in your IBM Cloud Object Storage. # You might want to remove those credentials before you share your notebook. # @hidden_cell # The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials. # You might want to remove those credentials before you share the notebook. # add missing __iter__ method, so pandas accepts body as file-like object #df_data_0.tail() # In[11]: Converting DataFrame into a list of reports # In[21]: labelling each datapoint #true_label = [] #true_label.append(0) #u=u+1 #true_label.append(1) # In[14]: # import nltk # nltk.download('punkt') # In[15]: Vectorizing the data # In[22]: Running the kMeans Algorithm # In[52]: Creating a dataframe for the better presentation of the clusters. This will also be used in generating some plots for a proper visualization of the data points after running the algorithm # shape (n_components, n_samples) #create data frame that has the result of the MDS plus the cluster numbers and labels #group by cluster # In[54]: # for name, group in groups: # print(group) # In[53]: setting up plot iterate through groups to layer the plotusing cluster_name and cluster_color dicts with the 'name' lookup to return the appropriate color/label #show legend with only 1 point #add label in x,y position with the label as the class folder name # In[ ]: | 2.642534 | 3 |
tools/redis_test.py | WeiSanJin/MxOnline | 1 | 6620441 | # -*- coding: utf-8 -*-
# @File : redis_test.py
# @Author :WeiSanJin
# @Time :2021/04/04 22:47
# @Site :https://github.com/WeiSanJin
import redis
r = redis.Redis(host="localhost", port=6379, charset="utf8", decode_responses=True)
r.set("mobile", "10086")
r.expire("mobile", 1)
import time
time.sleep(1)
print(r.get("mobile"))
| # -*- coding: utf-8 -*-
# @File : redis_test.py
# @Author :WeiSanJin
# @Time :2021/04/04 22:47
# @Site :https://github.com/WeiSanJin
import redis
r = redis.Redis(host="localhost", port=6379, charset="utf8", decode_responses=True)
r.set("mobile", "10086")
r.expire("mobile", 1)
import time
time.sleep(1)
print(r.get("mobile"))
| en | 0.537608 | # -*- coding: utf-8 -*- # @File : redis_test.py # @Author :WeiSanJin # @Time :2021/04/04 22:47 # @Site :https://github.com/WeiSanJin | 2.179576 | 2 |
xmpp/user.py | nokitakaze/point | 0 | 6620442 | from point.core.user import User, NotAuthorized
import geweb.db.pgsql as db
from psycopg2 import IntegrityError
from point.util import RedisPool
from point.util import cache_get, cache_store, cache_del
import json
try:
import re2 as re
except ImportError:
import re
import settings
class ImUser(User):
_profile_table = 'users.profile_im'
_profile = {
'off': {'type':'bool', 'default':False},
'xhtml': {'type':'bool', 'default':False},
'highlight': {'type':'bool', 'default':False},
'user_resource': {'type':'bool', 'default':False},
'post_resource': {'type':'bool', 'default':False},
'cut': {'type': 'int', 'default': 0},
'auto_switch': {'type':'bool', 'default':True},
}
def session(self, callback=None, **data):
sessid = 'im_session.%s' % self.get_active_account('xmpp')
if data:
self._sess = _Session(sessid, callback, **data)
else:
try:
return self._sess
except AttributeError:
self._sess = _Session(sessid)
return self._sess
def session_destroy(self):
try:
self._sess.destroy()
except AttributeError:
pass
def alias_list(self):
aliases = {}
if self.id:
aliases['user'] = cache_get('aliases:%s' % self.id)
if aliases['user'] is None:
aliases['user'] = dict(db.fetchall(
"SELECT alias, command FROM users.user_aliases "
"WHERE user_id=%s;", [self.id]))
cache_store('aliases:%s' % self.id, aliases['user'])
aliases['global'] = cache_get('aliases:global')
if aliases['global'] is None:
aliases['global'] = dict(db.fetchall(
"SELECT alias, command FROM users.aliases;"))
cache_store('aliases:global', aliases['global'], 300)
return aliases
def get_alias(self, alias):
aliases = {}
if self.id:
aliases['user'] = dict(db.fetchall(
"SELECT alias, command FROM users.user_aliases "
"WHERE user_id=%s AND LOWER(alias)=%s;",
[self.id, alias.lower()]))
aliases['global'] = dict(db.fetchall(
"SELECT alias, command FROM users.aliases "
"WHERE LOWER(alias)=%s;",
[alias.lower()]))
return aliases
def set_alias(self, alias, command):
if not self.id:
raise NotAuthorized
try:
db.perform("INSERT INTO users.user_aliases "
"(user_id, alias, command) VALUES (%s, %s, %s);",
[self.id, alias.lower(), command])
except IntegrityError:
db.perform("UPDATE users.user_aliases SET alias=%s, command=%s "
"WHERE user_id=%s;", [alias.lower(), command, self.id])
cache_del('aliases:%s' % self.id)
def delete_alias(self, alias):
if not self.id:
raise NotAuthorized
res = db.fetchone("DELETE FROM users.user_aliases "
"WHERE user_id=%s AND alias=%s "
"RETURNING alias;", [self.id, alias.lower()])
if not res:
return False
cache_del('aliases:%s' % self.id)
return True
def resolve_aliases(self, message):
aliases = self.alias_list()
for i in ('user', 'global'):
try:
lst = aliases[i]
except KeyError:
continue
lmessage = message.lower()
for alias, command in lst.iteritems():
#r = r'^%s(?=\s|$)' % alias
#if re.match(r, message.lower(), re.I):
# return re.sub(r, command, message)
if alias == lmessage:
return command
if lmessage.startswith("%s " % alias):
l = len(alias)
return "%s %s" % (command, message[l:])
return message
def update_tune_data(self, data):
cache_key = 'user_tune:%s' % self.id
if data:
cache_store(cache_key, data)
else:
cache_del(cache_key)
class SessionCallError(Exception):
pass
class _Session(object):
def __init__(self, sessid, callback=None, **data):
self.sessid = sessid
self._redis = RedisPool(settings.storage_socket)
if callback and data:
data['__callback__'] = [callback.__module__, callback.__name__]
self._redis.set(sessid, json.dumps(data))
del data['__callback__']
self._redis.expire(self.sessid, settings.session_expire)
self._callback = callback
self._data = data
else:
data = self._redis.get(self.sessid)
if not data:
self._callback = None
self._data = None
return
data = json.loads(data)
if '__callback__' in data:
mod, fn = tuple(data['__callback__'])
mod = __import__(mod, globals(), locals(), [fn], -1)
self._callback = getattr(mod, fn)
del data['__callback__']
else:
self._callback = None
self._data = data
def __call__(self, data):
if self._callback:
return self._callback(data)
raise SessionCallError
def __getitem__(self, key):
return self._data[key]
def data(self):
return self._data
def destroy(self):
self._redis.delete(self.sessid)
| from point.core.user import User, NotAuthorized
import geweb.db.pgsql as db
from psycopg2 import IntegrityError
from point.util import RedisPool
from point.util import cache_get, cache_store, cache_del
import json
try:
import re2 as re
except ImportError:
import re
import settings
class ImUser(User):
_profile_table = 'users.profile_im'
_profile = {
'off': {'type':'bool', 'default':False},
'xhtml': {'type':'bool', 'default':False},
'highlight': {'type':'bool', 'default':False},
'user_resource': {'type':'bool', 'default':False},
'post_resource': {'type':'bool', 'default':False},
'cut': {'type': 'int', 'default': 0},
'auto_switch': {'type':'bool', 'default':True},
}
def session(self, callback=None, **data):
sessid = 'im_session.%s' % self.get_active_account('xmpp')
if data:
self._sess = _Session(sessid, callback, **data)
else:
try:
return self._sess
except AttributeError:
self._sess = _Session(sessid)
return self._sess
def session_destroy(self):
try:
self._sess.destroy()
except AttributeError:
pass
def alias_list(self):
aliases = {}
if self.id:
aliases['user'] = cache_get('aliases:%s' % self.id)
if aliases['user'] is None:
aliases['user'] = dict(db.fetchall(
"SELECT alias, command FROM users.user_aliases "
"WHERE user_id=%s;", [self.id]))
cache_store('aliases:%s' % self.id, aliases['user'])
aliases['global'] = cache_get('aliases:global')
if aliases['global'] is None:
aliases['global'] = dict(db.fetchall(
"SELECT alias, command FROM users.aliases;"))
cache_store('aliases:global', aliases['global'], 300)
return aliases
def get_alias(self, alias):
aliases = {}
if self.id:
aliases['user'] = dict(db.fetchall(
"SELECT alias, command FROM users.user_aliases "
"WHERE user_id=%s AND LOWER(alias)=%s;",
[self.id, alias.lower()]))
aliases['global'] = dict(db.fetchall(
"SELECT alias, command FROM users.aliases "
"WHERE LOWER(alias)=%s;",
[alias.lower()]))
return aliases
def set_alias(self, alias, command):
if not self.id:
raise NotAuthorized
try:
db.perform("INSERT INTO users.user_aliases "
"(user_id, alias, command) VALUES (%s, %s, %s);",
[self.id, alias.lower(), command])
except IntegrityError:
db.perform("UPDATE users.user_aliases SET alias=%s, command=%s "
"WHERE user_id=%s;", [alias.lower(), command, self.id])
cache_del('aliases:%s' % self.id)
def delete_alias(self, alias):
if not self.id:
raise NotAuthorized
res = db.fetchone("DELETE FROM users.user_aliases "
"WHERE user_id=%s AND alias=%s "
"RETURNING alias;", [self.id, alias.lower()])
if not res:
return False
cache_del('aliases:%s' % self.id)
return True
def resolve_aliases(self, message):
aliases = self.alias_list()
for i in ('user', 'global'):
try:
lst = aliases[i]
except KeyError:
continue
lmessage = message.lower()
for alias, command in lst.iteritems():
#r = r'^%s(?=\s|$)' % alias
#if re.match(r, message.lower(), re.I):
# return re.sub(r, command, message)
if alias == lmessage:
return command
if lmessage.startswith("%s " % alias):
l = len(alias)
return "%s %s" % (command, message[l:])
return message
def update_tune_data(self, data):
cache_key = 'user_tune:%s' % self.id
if data:
cache_store(cache_key, data)
else:
cache_del(cache_key)
class SessionCallError(Exception):
pass
class _Session(object):
def __init__(self, sessid, callback=None, **data):
self.sessid = sessid
self._redis = RedisPool(settings.storage_socket)
if callback and data:
data['__callback__'] = [callback.__module__, callback.__name__]
self._redis.set(sessid, json.dumps(data))
del data['__callback__']
self._redis.expire(self.sessid, settings.session_expire)
self._callback = callback
self._data = data
else:
data = self._redis.get(self.sessid)
if not data:
self._callback = None
self._data = None
return
data = json.loads(data)
if '__callback__' in data:
mod, fn = tuple(data['__callback__'])
mod = __import__(mod, globals(), locals(), [fn], -1)
self._callback = getattr(mod, fn)
del data['__callback__']
else:
self._callback = None
self._data = data
def __call__(self, data):
if self._callback:
return self._callback(data)
raise SessionCallError
def __getitem__(self, key):
return self._data[key]
def data(self):
return self._data
def destroy(self):
self._redis.delete(self.sessid)
| zh | 0.081248 | #r = r'^%s(?=\s|$)' % alias #if re.match(r, message.lower(), re.I): # return re.sub(r, command, message) | 2.111736 | 2 |
valpid.py | zl101/heart_rate_sentinel_server | 0 | 6620443 | <reponame>zl101/heart_rate_sentinel_server<gh_stars>0
import logging
def validatePid(pid, patientDict, hrDict):
"""
Validates patient id input for checking tachycardic
:returns: -1 if not successful, 1 if successful
"""
if(not isinstance(pid, type(""))):
logging.error("didn't pass in string")
return -1
if pid not in patientDict.keys():
logging.error("patient not initialized")
return -1
if pid not in hrDict.keys():
logging.error("This should never happen")
return -1
if(len(hrDict[pid]) == 0):
logging.error("No Heart Rate Data Available")
return -1
return 1
| import logging
def validatePid(pid, patientDict, hrDict):
"""
Validates patient id input for checking tachycardic
:returns: -1 if not successful, 1 if successful
"""
if(not isinstance(pid, type(""))):
logging.error("didn't pass in string")
return -1
if pid not in patientDict.keys():
logging.error("patient not initialized")
return -1
if pid not in hrDict.keys():
logging.error("This should never happen")
return -1
if(len(hrDict[pid]) == 0):
logging.error("No Heart Rate Data Available")
return -1
return 1 | en | 0.570706 | Validates patient id input for checking tachycardic :returns: -1 if not successful, 1 if successful | 3.036117 | 3 |
scripts/utils.py | princedpw/nv | 6 | 6620444 | <filename>scripts/utils.py
#!/usr/bin/env python3
from dataclasses import dataclass
from enum import Enum, IntEnum
import re
from typing import Optional
class Bgp:
"""A simplified version of the BGP attribute."""
def __init__(
self,
aslen: int | str,
comms: set[int] = set(),
bgpAd: int = 20,
lp: int = 100,
med: int = 80,
):
self.aslen = aslen
self.comms = comms
self.bgpAd = bgpAd
self.lp = lp
self.med = med
def __str__(self):
aslen = f"{self.aslen}u32" if isinstance(self.aslen, int) else self.aslen
comms = "{ " + "; ".join(map(str, self.comms)) + "_ |-> false" + " }"
return f"{{ aslen= {aslen}; bgpAd= {self.bgpAd}u8; comms= {comms}; lp= {self.lp}u32; med= {self.med}u32; }}"
@staticmethod
def TypeDeclaration() -> str:
return "type bgpType = {aslen: int; bgpAd: int8; comms: set[int]; lp: int; med: int;}"
@dataclass
class Rib:
"""A simplified version of the RIB attribute."""
bgp: Optional[Bgp] = None
static: Optional[int | str] = None
selected: Optional[int | str] = None
def select(self):
# determine the selected attribute
if self.static:
self.selected = 1
elif self.bgp:
self.selected = 3
else:
self.selected = None
return self
def __str__(self):
match self.selected:
case None:
sel = "None"
case int() as v:
sel = f"Some {v}u2"
case str() as v:
sel = v
case _:
raise Exception("Invalid self.selected type")
match self.static:
case None:
static = "None"
case int() as v:
static = f"Some {v}u8"
case str() as v:
static = v
case _:
raise Exception("Invalid self.static type")
bgp = "None" if self.bgp is None else f"Some {self.bgp}"
return f"{{ bgp= {bgp}; connected= None; ospf= None; selected= {sel}; static= {static}; }}"
@staticmethod
def TypeDeclaration() -> str:
return "type rib = {\n connected:option[int8]\n static:option[int8];\n ospf:option[ospfType];\n bgp:option[bgpType];\n selected:option[int2]; }"
class AttrType(Enum):
"""Control which type of attribute the file uses."""
INT_OPTION = 0
RIB = 1
BGP = 2
@staticmethod
def parse_from_file(text):
pat = re.compile(r"type attribute = (.*)")
m = pat.search(text)
if m:
match m.group(1):
case "option[int]" | "option[int32]":
return AttrType.INT_OPTION
case "rib":
return AttrType.RIB
case "option[bgpType]":
return AttrType.BGP
case _:
raise ValueError(
f"Couldn't determine attribute type from file contents: found {m.group(1)}"
)
else:
raise ValueError("Couldn't find attribute declaration in NV file.")
class NetType(Enum):
SP = 0
FATPOL = 1
MAINTENANCE = 2
FT = 3
AP = 4
RAND = 5
OTHER = 6
def is_fattree(self):
"""Return True if the network is a fattree network (SP, FATPOL or MAINTENANCE)."""
match self:
case NetType.SP | NetType.FATPOL | NetType.MAINTENANCE | NetType.FT | NetType.AP:
return True
case _:
return False
@staticmethod
def from_filename(fname):
if re.match(r"sp\d*", fname):
return NetType.SP
elif re.match(r"ap\d*", fname):
return NetType.AP
elif re.match(r"fat\d*Pol", fname):
return NetType.FATPOL
elif re.match(r"rand_\d*_\d*", fname):
return NetType.RAND
elif re.match(r"maintenance\d*", fname) or re.match(
r"fat\d*Maintenance", fname
):
return NetType.MAINTENANCE
else:
return NetType.OTHER
class NodeGroup(IntEnum):
"""
Core nodes are on the spine, edge nodes are ToR,
and aggregation nodes are between core and edge nodes.
None is used when nodes are not in fattree networks.
"""
CORE = 0
AGGREGATION = 1
EDGE = 2
NONE = 3
@staticmethod
def parse(name):
if name == "core":
return NodeGroup.CORE
elif name == "aggregation":
return NodeGroup.AGGREGATION
elif name == "edge":
return NodeGroup.EDGE
else:
return NodeGroup.NONE
class FattreeCut(Enum):
VERTICAL = ("v", "vertical")
HORIZONTAL = ("h", "horizontal")
PODS = ("p", "pods")
SPINES = ("s", "spines")
FULL = ("f", "full")
def __init__(self, short: str, long: str):
self.short = short
self.long = long
@property
def desc(self):
# description
match self:
case FattreeCut.VERTICAL:
return "Vertically partitioned"
case FattreeCut.HORIZONTAL:
return "Horizontally partitioned"
case FattreeCut.PODS:
return "Partitioned into pods"
case FattreeCut.SPINES:
return "Partitioned into pods and individual spines"
case FattreeCut.FULL:
return "Fully partitioned"
@staticmethod
def as_list() -> list[str]:
return [s for c in list(FattreeCut) for s in [c.short, c.long]]
@staticmethod
def from_str(s):
for e in list(FattreeCut):
if s == e.short or s == e.long:
return e
raise KeyError("cut not found")
| <filename>scripts/utils.py
#!/usr/bin/env python3
from dataclasses import dataclass
from enum import Enum, IntEnum
import re
from typing import Optional
class Bgp:
"""A simplified version of the BGP attribute."""
def __init__(
self,
aslen: int | str,
comms: set[int] = set(),
bgpAd: int = 20,
lp: int = 100,
med: int = 80,
):
self.aslen = aslen
self.comms = comms
self.bgpAd = bgpAd
self.lp = lp
self.med = med
def __str__(self):
aslen = f"{self.aslen}u32" if isinstance(self.aslen, int) else self.aslen
comms = "{ " + "; ".join(map(str, self.comms)) + "_ |-> false" + " }"
return f"{{ aslen= {aslen}; bgpAd= {self.bgpAd}u8; comms= {comms}; lp= {self.lp}u32; med= {self.med}u32; }}"
@staticmethod
def TypeDeclaration() -> str:
return "type bgpType = {aslen: int; bgpAd: int8; comms: set[int]; lp: int; med: int;}"
@dataclass
class Rib:
"""A simplified version of the RIB attribute."""
bgp: Optional[Bgp] = None
static: Optional[int | str] = None
selected: Optional[int | str] = None
def select(self):
# determine the selected attribute
if self.static:
self.selected = 1
elif self.bgp:
self.selected = 3
else:
self.selected = None
return self
def __str__(self):
match self.selected:
case None:
sel = "None"
case int() as v:
sel = f"Some {v}u2"
case str() as v:
sel = v
case _:
raise Exception("Invalid self.selected type")
match self.static:
case None:
static = "None"
case int() as v:
static = f"Some {v}u8"
case str() as v:
static = v
case _:
raise Exception("Invalid self.static type")
bgp = "None" if self.bgp is None else f"Some {self.bgp}"
return f"{{ bgp= {bgp}; connected= None; ospf= None; selected= {sel}; static= {static}; }}"
@staticmethod
def TypeDeclaration() -> str:
return "type rib = {\n connected:option[int8]\n static:option[int8];\n ospf:option[ospfType];\n bgp:option[bgpType];\n selected:option[int2]; }"
class AttrType(Enum):
"""Control which type of attribute the file uses."""
INT_OPTION = 0
RIB = 1
BGP = 2
@staticmethod
def parse_from_file(text):
pat = re.compile(r"type attribute = (.*)")
m = pat.search(text)
if m:
match m.group(1):
case "option[int]" | "option[int32]":
return AttrType.INT_OPTION
case "rib":
return AttrType.RIB
case "option[bgpType]":
return AttrType.BGP
case _:
raise ValueError(
f"Couldn't determine attribute type from file contents: found {m.group(1)}"
)
else:
raise ValueError("Couldn't find attribute declaration in NV file.")
class NetType(Enum):
SP = 0
FATPOL = 1
MAINTENANCE = 2
FT = 3
AP = 4
RAND = 5
OTHER = 6
def is_fattree(self):
"""Return True if the network is a fattree network (SP, FATPOL or MAINTENANCE)."""
match self:
case NetType.SP | NetType.FATPOL | NetType.MAINTENANCE | NetType.FT | NetType.AP:
return True
case _:
return False
@staticmethod
def from_filename(fname):
if re.match(r"sp\d*", fname):
return NetType.SP
elif re.match(r"ap\d*", fname):
return NetType.AP
elif re.match(r"fat\d*Pol", fname):
return NetType.FATPOL
elif re.match(r"rand_\d*_\d*", fname):
return NetType.RAND
elif re.match(r"maintenance\d*", fname) or re.match(
r"fat\d*Maintenance", fname
):
return NetType.MAINTENANCE
else:
return NetType.OTHER
class NodeGroup(IntEnum):
"""
Core nodes are on the spine, edge nodes are ToR,
and aggregation nodes are between core and edge nodes.
None is used when nodes are not in fattree networks.
"""
CORE = 0
AGGREGATION = 1
EDGE = 2
NONE = 3
@staticmethod
def parse(name):
if name == "core":
return NodeGroup.CORE
elif name == "aggregation":
return NodeGroup.AGGREGATION
elif name == "edge":
return NodeGroup.EDGE
else:
return NodeGroup.NONE
class FattreeCut(Enum):
VERTICAL = ("v", "vertical")
HORIZONTAL = ("h", "horizontal")
PODS = ("p", "pods")
SPINES = ("s", "spines")
FULL = ("f", "full")
def __init__(self, short: str, long: str):
self.short = short
self.long = long
@property
def desc(self):
# description
match self:
case FattreeCut.VERTICAL:
return "Vertically partitioned"
case FattreeCut.HORIZONTAL:
return "Horizontally partitioned"
case FattreeCut.PODS:
return "Partitioned into pods"
case FattreeCut.SPINES:
return "Partitioned into pods and individual spines"
case FattreeCut.FULL:
return "Fully partitioned"
@staticmethod
def as_list() -> list[str]:
return [s for c in list(FattreeCut) for s in [c.short, c.long]]
@staticmethod
def from_str(s):
for e in list(FattreeCut):
if s == e.short or s == e.long:
return e
raise KeyError("cut not found")
| en | 0.809782 | #!/usr/bin/env python3 A simplified version of the BGP attribute. A simplified version of the RIB attribute. # determine the selected attribute Control which type of attribute the file uses. Return True if the network is a fattree network (SP, FATPOL or MAINTENANCE). Core nodes are on the spine, edge nodes are ToR, and aggregation nodes are between core and edge nodes. None is used when nodes are not in fattree networks. # description | 3.183053 | 3 |
py/keras/integrate.py | YodaEmbedding/experiments | 0 | 6620445 | import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
Dense = tf.keras.layers.Dense
Sequential = tf.keras.models.Sequential
# TODO eager execution vs static graph...
# TODO generalize
X_MIN = 0.0
X_MAX = 2 * np.pi
N = 256
def integrate(f, a, b):
x = tf.lin_space(a, b, N)
y = f(x)
return K.sum(y)
def f_model(w, x):
return w[0] * K.sin(x)
def loss(y_true, y_pred):
f = lambda x: K.abs(f_model(y_true, x) - f_model(y_pred, x))
return integrate(f, X_MIN, X_MAX)
labels = np.array([0.1])
x = np.linspace(X_MIN, X_MAX, N)
inputs = np.array([0.1 * np.sin(x)])
model = Sequential()
model.add(Dense(units=64, activation="relu"))
model.add(Dense(units=32, activation="relu"))
model.add(Dense(units=1, activation="linear"))
model.compile(loss=loss, optimizer="sgd", metrics=["accuracy"])
model.fit(
inputs, labels, epochs=5, batch_size=1
) # batch size of 1 for maximum kappa
scores = model.evaluate(inputs, labels)
preds = model.predict(inputs)
print()
print(
"\n".join(
f"{name}: {score}" for name, score in zip(model.metrics_names, scores)
)
)
print(preds)
| import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
Dense = tf.keras.layers.Dense
Sequential = tf.keras.models.Sequential
# TODO eager execution vs static graph...
# TODO generalize
X_MIN = 0.0
X_MAX = 2 * np.pi
N = 256
def integrate(f, a, b):
x = tf.lin_space(a, b, N)
y = f(x)
return K.sum(y)
def f_model(w, x):
return w[0] * K.sin(x)
def loss(y_true, y_pred):
f = lambda x: K.abs(f_model(y_true, x) - f_model(y_pred, x))
return integrate(f, X_MIN, X_MAX)
labels = np.array([0.1])
x = np.linspace(X_MIN, X_MAX, N)
inputs = np.array([0.1 * np.sin(x)])
model = Sequential()
model.add(Dense(units=64, activation="relu"))
model.add(Dense(units=32, activation="relu"))
model.add(Dense(units=1, activation="linear"))
model.compile(loss=loss, optimizer="sgd", metrics=["accuracy"])
model.fit(
inputs, labels, epochs=5, batch_size=1
) # batch size of 1 for maximum kappa
scores = model.evaluate(inputs, labels)
preds = model.predict(inputs)
print()
print(
"\n".join(
f"{name}: {score}" for name, score in zip(model.metrics_names, scores)
)
)
print(preds)
| en | 0.657873 | # TODO eager execution vs static graph... # TODO generalize # batch size of 1 for maximum kappa | 2.900101 | 3 |
sns_portfolio/sample_app/views.py | SnSation/PortfolioWebsite | 0 | 6620446 | <gh_stars>0
from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
def index(request):
newest_questions = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([f"Text: {question.question_text} | ID:{question.id}" for question in newest_questions])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("Details: Question %s" % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s:"
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're vogint on question %s:" % question_id) | from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
def index(request):
newest_questions = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([f"Text: {question.question_text} | ID:{question.id}" for question in newest_questions])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("Details: Question %s" % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s:"
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're vogint on question %s:" % question_id) | none | 1 | 2.243847 | 2 | |
train_rguo/train_code/models/base_models/pretrained/__init__.py | DrHB/PANDA-2nd-place-solution | 17 | 6620447 | <filename>train_rguo/train_code/models/base_models/pretrained/__init__.py
from .senet import *
from .torchvision_models import resnet18,resnet34,resnet50,resnet101,resnet152,resnet34_seblock | <filename>train_rguo/train_code/models/base_models/pretrained/__init__.py
from .senet import *
from .torchvision_models import resnet18,resnet34,resnet50,resnet101,resnet152,resnet34_seblock | none | 1 | 1.192868 | 1 | |
src/macdirectorywatcher.py | chadaustin/ibb | 4 | 6620448 | import threading
import AppKit
import FSEvents
class DirectoryWatcher:
DIE = 'DIE'
def __init__(self, directory, onFileChange, onResetAll):
self.__directory = directory
self.__onFileChange = onFileChange
self.__onResetAll = onResetAll
self.__started = threading.Event()
self.__done = threading.Event() # TODO: post shutdown event to run loop?
self.__thread = threading.Thread(target=self.__thread)
self.__thread.setDaemon(True)
self.__thread.start()
# Once we know the thread has called ReadDirectoryChangesW
# once, we will not miss change notifications. The change
# queue is created on the first call to ReadDirectoryChangesW.
self.__started.wait()
def dispose(self):
self.__done.set()
self.__thread.join()
def __thread(self):
# will automatically release on thread exit
pool = AppKit.NSAutoreleasePool.alloc().init()
eventStream = FSEvents.FSEventStreamCreate(
None,
self.__callback,
None,
[self.__directory],
FSEvents.kFSEventStreamEventIdSinceNow,
0.1, # 100 ms
# kFSEventStreamCreateFlagIgnoreSelf?
FSEvents.kFSEventStreamCreateFlagNoDefer | FSEvents.kFSEventStreamCreateFlagWatchRoot | getattr(FSEvents, 'kFSEventStreamCreateFlagFileEvents', 0x00000010))
# at this point, we will not lose any events, so unblock creating thread
self.__started.set()
try:
FSEvents.FSEventStreamScheduleWithRunLoop(
eventStream,
FSEvents.CFRunLoopGetCurrent(),
FSEvents.kCFRunLoopDefaultMode)
assert FSEvents.FSEventStreamStart(eventStream), 'event stream could not be started'
while not self.__done.isSet():
# TODO: check return value?
FSEvents.CFRunLoopRunInMode(
FSEvents.kCFRunLoopDefaultMode,
0.1, # 100 ms
False) # returnAfterSourceHandled
finally:
FSEvents.FSEventStreamRelease(eventStream)
def __callback(self, eventStream, clientCallBackInfo, numEvents, paths, eventFlags, eventIds):
# TODO: hard links are not understood
assert numEvents == len(paths)
for path in paths:
self.__onFileChange(path)
| import threading
import AppKit
import FSEvents
class DirectoryWatcher:
DIE = 'DIE'
def __init__(self, directory, onFileChange, onResetAll):
self.__directory = directory
self.__onFileChange = onFileChange
self.__onResetAll = onResetAll
self.__started = threading.Event()
self.__done = threading.Event() # TODO: post shutdown event to run loop?
self.__thread = threading.Thread(target=self.__thread)
self.__thread.setDaemon(True)
self.__thread.start()
# Once we know the thread has called ReadDirectoryChangesW
# once, we will not miss change notifications. The change
# queue is created on the first call to ReadDirectoryChangesW.
self.__started.wait()
def dispose(self):
self.__done.set()
self.__thread.join()
def __thread(self):
# will automatically release on thread exit
pool = AppKit.NSAutoreleasePool.alloc().init()
eventStream = FSEvents.FSEventStreamCreate(
None,
self.__callback,
None,
[self.__directory],
FSEvents.kFSEventStreamEventIdSinceNow,
0.1, # 100 ms
# kFSEventStreamCreateFlagIgnoreSelf?
FSEvents.kFSEventStreamCreateFlagNoDefer | FSEvents.kFSEventStreamCreateFlagWatchRoot | getattr(FSEvents, 'kFSEventStreamCreateFlagFileEvents', 0x00000010))
# at this point, we will not lose any events, so unblock creating thread
self.__started.set()
try:
FSEvents.FSEventStreamScheduleWithRunLoop(
eventStream,
FSEvents.CFRunLoopGetCurrent(),
FSEvents.kCFRunLoopDefaultMode)
assert FSEvents.FSEventStreamStart(eventStream), 'event stream could not be started'
while not self.__done.isSet():
# TODO: check return value?
FSEvents.CFRunLoopRunInMode(
FSEvents.kCFRunLoopDefaultMode,
0.1, # 100 ms
False) # returnAfterSourceHandled
finally:
FSEvents.FSEventStreamRelease(eventStream)
def __callback(self, eventStream, clientCallBackInfo, numEvents, paths, eventFlags, eventIds):
# TODO: hard links are not understood
assert numEvents == len(paths)
for path in paths:
self.__onFileChange(path)
| en | 0.814924 | # TODO: post shutdown event to run loop? # Once we know the thread has called ReadDirectoryChangesW # once, we will not miss change notifications. The change # queue is created on the first call to ReadDirectoryChangesW. # will automatically release on thread exit # 100 ms # kFSEventStreamCreateFlagIgnoreSelf? # at this point, we will not lose any events, so unblock creating thread # TODO: check return value? # 100 ms # returnAfterSourceHandled # TODO: hard links are not understood | 2.345278 | 2 |
ZmPublish/LDAPPublisher.py | Zimbra-Community/zmpublish | 1 | 6620449 | <reponame>Zimbra-Community/zmpublish<filename>ZmPublish/LDAPPublisher.py
import logging
import ldap
import re
class LDAPPublisher:
"""
Publish a Zimbra addressbook to a LDAP server
"""
addressbook = None
""" Zimbra Addressbook to publish """
config = None
""" Publisher configuration """
attribute_map = {
"cn": "fileAsStr",
"sn": "_attrs/lastName",
"givenname": "_attrs/firstName",
"street": "_attrs/workStreet",
"l": "_attrs/workCity",
"st": "_attrs/workState",
"postalCode": "_attrs/workPostalCode",
"telephoneNumber": "_attrs/workPhone",
"facsimileTelephoneNumber": "_attrs/workFax",
"mobile": "_attrs/mobilePhone",
"mail": "_attrs/email",
"labeleduri": "_attrs/workURL",
"o": "_attrs/company",
"ou": "_attrs/department",
"description": "_attrs/notes"
}
""" Attribute Map Zimbra <> LDAP """
ldap_connect = None
""" LDAP-Connection used by the publisher """
mandatory_attributes = ["cn", "sn"]
""" Mandatory LDAP attributes """
attribute_alternatives = {
"sn": "o",
"sn": "cn"
}
""" Alternatives for specific attributes if empty """
log_attribute = "cn"
""" Attribute to use when logging """
def __init__(self, config, addressbook):
""" Initialize Publisher """
self.addressbook = addressbook
self.config = config
logging.debug("Initialised Publisher %s" % (self.config["name"]))
def drop_tree(self, dn):
""" Recursively drop a LDAP tree """
logging.debug("Deleting dn %s" % (dn))
result = self.ldap_connect.search_s(
dn,
ldap.SCOPE_ONELEVEL # @UndefinedVariable
)
if len(result) > 0:
for leaf in result:
self.drop_tree(leaf[0])
self.ldap_connect.delete_s(dn)
def run(self):
""" Publish the addressbook """
# Bind to ldap
self.ldap_connect = ldap.initialize(self.config["ldap_url"])
self.ldap_connect.simple_bind_s(
self.config["bind_uid"],
self.config["bind_pw"],
)
logging.debug("Connected to LDAP-Server %s as user %s" %
(
self.config["ldap_url"],
self.config["bind_uid"]
)
)
ldap_dn = "ou=%s,%s" % (self.config["name"], self.config["base_dn"])
# Find our branch
result = self.ldap_connect.search_s(
self.config["base_dn"],
ldap.SCOPE_SUBTREE, # @UndefinedVariable
"ou=%s" % (self.config["name"])
)
if len(result) > 0 and self.config["drop"] == "1":
# Branch exists, but needs to be recreated
logging.info("Dropping branch %s" % (ldap_dn))
self.drop_tree(ldap_dn)
if (len(result) == 0) or (
len(result) > 0 and self.config["drop"] == "1"
):
# Branch doesn't exists or is recently dropped. Recreate!
add_data = [
("objectclass", ["top", "organizationalUnit"]),
("ou", [self.config["name"]])
]
logging.info("Recreating tree %s" % (ldap_dn))
self.ldap_connect.add_s(ldap_dn, add_data)
uid = 0
for address in self.addressbook:
current_item = ""
converted_addressbook = {}
for attribute in self.attribute_map:
matched_attribute = re.search(
"_attrs/(.*)",
self.attribute_map[attribute]
)
if matched_attribute != None:
if matched_attribute.group(1) in address["_attrs"]:
attribute_value = \
address["_attrs"][matched_attribute.group(1)]
else:
attribute_value = ""
else:
attribute_value = address[self.attribute_map[attribute]]
if (self.attribute_map[attribute] in address):
attribute_value = \
address[self.attribute_map[attribute]]
else:
attribute_value = ""
if attribute == self.log_attribute:
current_item = attribute_value
try:
ldap_value = attribute_value.encode('ascii')
except UnicodeEncodeError:
ldap_value = attribute_value.encode('utf-8')
converted_addressbook[attribute] = ldap_value
# Apply alternatives
for attribute in self.attribute_alternatives:
alternate_attribute = self.attribute_alternatives[attribute]
if converted_addressbook[attribute] == "" and\
converted_addressbook[alternate_attribute] != "":
converted_addressbook[attribute] = \
converted_addressbook[alternate_attribute]
sanity_checked = True
for attribute in self.mandatory_attributes:
if converted_addressbook[attribute] == "":
sanity_checked = False
if sanity_checked:
logging.info("Adding entry %s" % (current_item))
add_data = [
("objectClass", [
'top',
'person',
'organizationalperson',
'inetorgperson'
])
]
for entry in converted_addressbook:
if converted_addressbook[entry] != "":
add_data.append(
(
entry,
[converted_addressbook[entry]]
)
)
dn = "uid=%d,%s" % (uid, ldap_dn)
logging.debug(
"Adding entry at dn %s with the following data:\n %s" % (
dn,
add_data
)
)
self.ldap_connect.add_s(dn, add_data)
uid = uid + 1
| import logging
import ldap
import re
class LDAPPublisher:
"""
Publish a Zimbra addressbook to a LDAP server
"""
addressbook = None
""" Zimbra Addressbook to publish """
config = None
""" Publisher configuration """
attribute_map = {
"cn": "fileAsStr",
"sn": "_attrs/lastName",
"givenname": "_attrs/firstName",
"street": "_attrs/workStreet",
"l": "_attrs/workCity",
"st": "_attrs/workState",
"postalCode": "_attrs/workPostalCode",
"telephoneNumber": "_attrs/workPhone",
"facsimileTelephoneNumber": "_attrs/workFax",
"mobile": "_attrs/mobilePhone",
"mail": "_attrs/email",
"labeleduri": "_attrs/workURL",
"o": "_attrs/company",
"ou": "_attrs/department",
"description": "_attrs/notes"
}
""" Attribute Map Zimbra <> LDAP """
ldap_connect = None
""" LDAP-Connection used by the publisher """
mandatory_attributes = ["cn", "sn"]
""" Mandatory LDAP attributes """
attribute_alternatives = {
"sn": "o",
"sn": "cn"
}
""" Alternatives for specific attributes if empty """
log_attribute = "cn"
""" Attribute to use when logging """
def __init__(self, config, addressbook):
""" Initialize Publisher """
self.addressbook = addressbook
self.config = config
logging.debug("Initialised Publisher %s" % (self.config["name"]))
def drop_tree(self, dn):
""" Recursively drop a LDAP tree """
logging.debug("Deleting dn %s" % (dn))
result = self.ldap_connect.search_s(
dn,
ldap.SCOPE_ONELEVEL # @UndefinedVariable
)
if len(result) > 0:
for leaf in result:
self.drop_tree(leaf[0])
self.ldap_connect.delete_s(dn)
def run(self):
""" Publish the addressbook """
# Bind to ldap
self.ldap_connect = ldap.initialize(self.config["ldap_url"])
self.ldap_connect.simple_bind_s(
self.config["bind_uid"],
self.config["bind_pw"],
)
logging.debug("Connected to LDAP-Server %s as user %s" %
(
self.config["ldap_url"],
self.config["bind_uid"]
)
)
ldap_dn = "ou=%s,%s" % (self.config["name"], self.config["base_dn"])
# Find our branch
result = self.ldap_connect.search_s(
self.config["base_dn"],
ldap.SCOPE_SUBTREE, # @UndefinedVariable
"ou=%s" % (self.config["name"])
)
if len(result) > 0 and self.config["drop"] == "1":
# Branch exists, but needs to be recreated
logging.info("Dropping branch %s" % (ldap_dn))
self.drop_tree(ldap_dn)
if (len(result) == 0) or (
len(result) > 0 and self.config["drop"] == "1"
):
# Branch doesn't exists or is recently dropped. Recreate!
add_data = [
("objectclass", ["top", "organizationalUnit"]),
("ou", [self.config["name"]])
]
logging.info("Recreating tree %s" % (ldap_dn))
self.ldap_connect.add_s(ldap_dn, add_data)
uid = 0
for address in self.addressbook:
current_item = ""
converted_addressbook = {}
for attribute in self.attribute_map:
matched_attribute = re.search(
"_attrs/(.*)",
self.attribute_map[attribute]
)
if matched_attribute != None:
if matched_attribute.group(1) in address["_attrs"]:
attribute_value = \
address["_attrs"][matched_attribute.group(1)]
else:
attribute_value = ""
else:
attribute_value = address[self.attribute_map[attribute]]
if (self.attribute_map[attribute] in address):
attribute_value = \
address[self.attribute_map[attribute]]
else:
attribute_value = ""
if attribute == self.log_attribute:
current_item = attribute_value
try:
ldap_value = attribute_value.encode('ascii')
except UnicodeEncodeError:
ldap_value = attribute_value.encode('utf-8')
converted_addressbook[attribute] = ldap_value
# Apply alternatives
for attribute in self.attribute_alternatives:
alternate_attribute = self.attribute_alternatives[attribute]
if converted_addressbook[attribute] == "" and\
converted_addressbook[alternate_attribute] != "":
converted_addressbook[attribute] = \
converted_addressbook[alternate_attribute]
sanity_checked = True
for attribute in self.mandatory_attributes:
if converted_addressbook[attribute] == "":
sanity_checked = False
if sanity_checked:
logging.info("Adding entry %s" % (current_item))
add_data = [
("objectClass", [
'top',
'person',
'organizationalperson',
'inetorgperson'
])
]
for entry in converted_addressbook:
if converted_addressbook[entry] != "":
add_data.append(
(
entry,
[converted_addressbook[entry]]
)
)
dn = "uid=%d,%s" % (uid, ldap_dn)
logging.debug(
"Adding entry at dn %s with the following data:\n %s" % (
dn,
add_data
)
)
self.ldap_connect.add_s(dn, add_data)
uid = uid + 1 | en | 0.77413 | Publish a Zimbra addressbook to a LDAP server Zimbra Addressbook to publish Publisher configuration Attribute Map Zimbra <> LDAP LDAP-Connection used by the publisher Mandatory LDAP attributes Alternatives for specific attributes if empty Attribute to use when logging Initialize Publisher Recursively drop a LDAP tree # @UndefinedVariable Publish the addressbook # Bind to ldap # Find our branch # @UndefinedVariable # Branch exists, but needs to be recreated # Branch doesn't exists or is recently dropped. Recreate! # Apply alternatives | 2.451087 | 2 |
regscrape/regs_common/commands/create_dockets.py | sunlightlabs/regulations-scraper | 13 | 6620450 | from optparse import OptionParser
arg_parser = OptionParser()
arg_parser.add_option("-a", "--agency", dest="agency", action="store", type="string", default=None, help="Specify an agency to which to limit the dump.")
arg_parser.add_option("-d", "--docket", dest="docket", action="store", type="string", default=None, help="Specify a docket to which to limit the dump.")
def run(options, args):
import regs_models as models
from collections import defaultdict
db = models.Docket._get_db()
new = 0
print 'Starting docket query...'
conditions = {}
if options.agency:
conditions['agency'] = options.agency
if options.docket:
conditions['id'] = options.docket
# there's no way to do this aggregation without a map-reduce in Mongo 2.0, so do it on the Python side for now
# once 2.2 is final, this can trivially be replaced with a $group + $addToSet pipeline using the new aggregation framework
dockets = defaultdict(set)
for doc in db.docs.find(conditions, fields=['docket_id', 'agency']):
if 'docket_id' not in doc:
continue
dockets[doc['docket_id']].add(doc['agency'])
for docket_id, agencies in dockets.iteritems():
if docket_id:
agency = list(agencies)[0] if len(agencies) == 1 else sorted(agencies, key=lambda a: docket_id.startswith(a), reverse=True)[0]
try:
docket = models.Docket(id=docket_id, agency=agency)
docket.save(force_insert=True)
new += 1
except:
# we already have this one
pass
total = len(dockets.keys())
print 'Iterated over %s dockets, of which %s were new.' % (total, new)
return {'total': total, 'new': new}
| from optparse import OptionParser
arg_parser = OptionParser()
arg_parser.add_option("-a", "--agency", dest="agency", action="store", type="string", default=None, help="Specify an agency to which to limit the dump.")
arg_parser.add_option("-d", "--docket", dest="docket", action="store", type="string", default=None, help="Specify a docket to which to limit the dump.")
def run(options, args):
import regs_models as models
from collections import defaultdict
db = models.Docket._get_db()
new = 0
print 'Starting docket query...'
conditions = {}
if options.agency:
conditions['agency'] = options.agency
if options.docket:
conditions['id'] = options.docket
# there's no way to do this aggregation without a map-reduce in Mongo 2.0, so do it on the Python side for now
# once 2.2 is final, this can trivially be replaced with a $group + $addToSet pipeline using the new aggregation framework
dockets = defaultdict(set)
for doc in db.docs.find(conditions, fields=['docket_id', 'agency']):
if 'docket_id' not in doc:
continue
dockets[doc['docket_id']].add(doc['agency'])
for docket_id, agencies in dockets.iteritems():
if docket_id:
agency = list(agencies)[0] if len(agencies) == 1 else sorted(agencies, key=lambda a: docket_id.startswith(a), reverse=True)[0]
try:
docket = models.Docket(id=docket_id, agency=agency)
docket.save(force_insert=True)
new += 1
except:
# we already have this one
pass
total = len(dockets.keys())
print 'Iterated over %s dockets, of which %s were new.' % (total, new)
return {'total': total, 'new': new}
| en | 0.867272 | # there's no way to do this aggregation without a map-reduce in Mongo 2.0, so do it on the Python side for now # once 2.2 is final, this can trivially be replaced with a $group + $addToSet pipeline using the new aggregation framework # we already have this one | 2.46613 | 2 |